Complete the code to import the FastAPI class.
from fastapi import [1] app = [1]()
The FastAPI class is imported from the fastapi module to create the app instance.
Complete the code to define a dependency that checks user roles.
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
The role_checker checks if the user's role matches the required role, here 'admin'.
Fix the error in the route dependency injection for role-based access.
@app.get("/admin") async def admin_panel(user=Depends([1]("admin"))): return {"message": f"Welcome {user.name} to admin panel"}
The route depends on the get_current_user function with the role 'admin' to enforce access control.
Fill both blanks to create a route that allows only moderators to access.
@app.get("/moderator") async def mod_panel(user=Depends([1]([2]))): return {"message": f"Hello {user.name}, you are a moderator"}
The route uses get_current_user with the role 'moderator' to restrict access.
Fill all three blanks to create a dictionary comprehension filtering users by role.
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]The comprehension creates a dictionary of users whose role is 'admin', using their name as the key.