0
0
FastAPIframework~30 mins

Role-based access control in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Role-based access control
📖 Scenario: You are building a simple web API for a company. Different users have different roles like 'admin' and 'user'. You want to control which parts of the API each role can access.
🎯 Goal: Create a FastAPI app that defines user roles and restricts access to an endpoint based on the user's role.
📋 What You'll Learn
Create a dictionary called users with usernames as keys and their roles as values.
Create a variable called allowed_roles that lists roles allowed to access a protected endpoint.
Write a function called check_access that takes a username and returns True if the user role is in allowed_roles, otherwise False.
Create a FastAPI endpoint /protected that returns a message only if the user has access, otherwise returns a 403 error.
💡 Why This Matters
🌍 Real World
Role-based access control is used in many web apps to protect sensitive data and features. For example, only admins can change settings, while regular users can only view content.
💼 Career
Understanding how to implement role-based access control is important for backend developers and security engineers to build secure applications.
Progress0 / 4 steps
1
Create user roles dictionary
Create a dictionary called users with these exact entries: 'alice': 'admin', 'bob': 'user', 'carol': 'guest'.
FastAPI
Need a hint?

Use curly braces to create a dictionary. Keys are usernames, values are roles as strings.

2
Define allowed roles list
Create a list called allowed_roles containing the strings 'admin' and 'user'.
FastAPI
Need a hint?

Use square brackets to create a list of allowed roles.

3
Write access check function
Write a function called check_access that takes a parameter username. It should return True if users[username] is in allowed_roles, otherwise False. Use users.get(username) to safely get the role.
FastAPI
Need a hint?

Use def to define the function. Use users.get(username) to get the role safely.

4
Create protected FastAPI endpoint
Import FastAPI and HTTPException from fastapi. Create a FastAPI app called app. Add a GET endpoint /protected that takes a query parameter username. Use check_access to allow access only if it returns True. If access is denied, raise HTTPException with status code 403 and detail 'Access denied'. If allowed, return a JSON message {'message': 'Welcome, {username}!'}.
FastAPI
Need a hint?

Use @app.get decorator to create the endpoint. Use raise HTTPException to block access.