Python / FastAPI Interview Questions
How do you implement role-based access control (RBAC) using FastAPI dependencies?
FastAPI's dependency injection makes RBAC clean: create a higher-order dependency that checks the current user's role. Inject it into routes that require elevated permissions.
from fastapi import FastAPI, Depends, HTTPException, status
from typing import Annotated
from enum import Enum
app = FastAPI()
class Role(str, Enum):
user = "user"
admin = "admin"
class User:
def __init__(self, username: str, role: Role):
self.username = username
self.role = role
# Simulated auth — in reality decode a JWT
def get_current_user() -> User:
return User(username="alice", role=Role.user)
# Higher-order dependency factory — creates a role checker
def require_role(role: Role):
def checker(user: Annotated[User, Depends(get_current_user)]) -> User:
if user.role != role:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Requires {role} role",
)
return user
return checker
# Public route — any authenticated user
@app.get("/profile")
def profile(user: Annotated[User, Depends(get_current_user)]):
return {"username": user.username, "role": user.role}
# Admin-only route
@app.delete("/users/{user_id}")
def delete_user(
user_id: int,
_: Annotated[User, Depends(require_role(Role.admin))],
):
return {"deleted": user_id}
# Router-level dependency — apply to all routes in a router
from fastapi import APIRouter
admin_router = APIRouter(
prefix="/admin",
dependencies=[Depends(require_role(Role.admin))],
)
@admin_router.get("/stats")
def admin_stats():
return {"total_users": 42}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
