0
0
FastAPIframework~10 mins

Role-based access control in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the FastAPI class.

FastAPI
from fastapi import [1]
app = [1]()
Drag options to blanks, or click blank then click option'
AFastAPI
BRequest
CHTTPException
DDepends
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Request instead of FastAPI
Trying to create app without importing FastAPI
2fill in blank
medium

Complete the code to define a dependency that checks user roles.

FastAPI
from fastapi import Depends, HTTPException

def get_current_user(role: str):
    def role_checker(user=Depends(get_user)):
        if user.role != [1]:
            raise HTTPException(status_code=403, detail="Forbidden")
        return user
    return role_checker
Drag options to blanks, or click blank then click option'
Aguest
Badmin
Cuser
Dmoderator
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong role string
Not raising HTTPException on role mismatch
3fill in blank
hard

Fix the error in the route dependency injection for role-based access.

FastAPI
@app.get("/admin")
async def admin_panel(user=Depends([1]("admin"))):
    return {"message": f"Welcome {user.name} to admin panel"}
Drag options to blanks, or click blank then click option'
Aget_user
BDepends
Cget_current_user
DHTTPException
Attempts:
3 left
💡 Hint
Common Mistakes
Using Depends directly instead of the role-checking function
Using get_user which does not check roles
4fill in blank
hard

Fill both blanks to create a route that allows only moderators to access.

FastAPI
@app.get("/moderator")
async def mod_panel(user=Depends([1]([2]))):
    return {"message": f"Hello {user.name}, you are a moderator"}
Drag options to blanks, or click blank then click option'
Aget_current_user
B"moderator"
C"admin"
Dget_user
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 'admin' instead of 'moderator'
Using get_user which does not enforce roles
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension filtering users by role.

FastAPI
users = [
    {"name": "Alice", "role": "admin"},
    {"name": "Bob", "role": "user"},
    {"name": "Carol", "role": "moderator"}
]
admin_users = {user[[1]]: user for user in users if user[[2]] == [3]
Drag options to blanks, or click blank then click option'
A"name"
B"role"
C"admin"
D"user"
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'role' as key instead of 'name'
Filtering by wrong role string