Full answer
Sometimes the same check needs different settings: "admin only" on one route, "teacher or admin" on another. Writing require_admin, require_teacher, require_teacher_or_admin duplicates code.
Option 1: a callable instance
class RoleChecker:
def __init__(self, allowed: list[str]):
self.allowed = allowed
def __call__(self, user: User = Depends(get_current_user)) -> User:
if user.role not in self.allowed:
raise HTTPException(403, "Not allowed")
return user
@app.delete("/marks/{id}", dependencies=[Depends(RoleChecker(["admin"]))])RoleChecker(["admin"]) runs once when the module loads. FastAPI inspects __call__'s signature and calls it per request.
Option 2: a factory function
def require_role(*roles):
def checker(user: User = Depends(get_current_user)):
...
return checkerSame idea with a closure. Simple and readable.
Option 3: a class as the dependency itself
class Filters:
def __init__(self, q: str | None = None, page: int = 1): ...
def list_items(f: Annotated[Filters, Depends()]): ...FastAPI calls Filters(q=..., page=...) using the __init__ parameters. Depends() with no argument means "use the type annotation". Since FastAPI 0.115 a Pydantic model with Query() is often cleaner for grouped query parameters.
Notes:
- The instance in option 1 is shared across requests, so do not store per-request state on
self. - Overriding in tests: override the inner dependency (
get_current_user), not eachRoleCheckerinstance, because instances are different objects. - Combine with
Security()and scopes when the roles map to OAuth2 scopes.
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel
app = FastAPI()
USERS = {"t1": {"name": "Ms. Kapoor", "role": "teacher"}, "a1": {"name": "Mr. Rao", "role": "admin"},
"s1": {"name": "Ishaan", "role": "student"}}
class User(BaseModel):
name: str
role: str
def get_current_user(x_token: Annotated[str, Header()]) -> User:
if x_token not in USERS:
raise HTTPException(status_code=401, detail="Unknown token")
return User(**USERS[x_token])
class RoleChecker:
def __init__(self, allowed: list[str]):
self.allowed = allowed
def __call__(self, user: User = Depends(get_current_user)) -> User:
if user.role not in self.allowed:
raise HTTPException(status_code=403, detail=f"Requires one of {self.allowed}")
return user
class MarkFilters:
def __init__(self, subject: str | None = None, min_score: int = 0):
self.subject, self.min_score = subject, min_score
@app.get("/marks")
def list_marks(f: Annotated[MarkFilters, Depends()],
user: Annotated[User, Depends(RoleChecker(["teacher", "admin"]))]):
return {"viewer": user.name, "subject": f.subject, "min_score": f.min_score}
@app.delete("/marks/{mark_id}", dependencies=[Depends(RoleChecker(["admin"]))])
def delete_mark(mark_id: int):
return {"deleted": mark_id}
c = TestClient(app)
print(c.get("/marks?subject=Physics&min_score=40", headers={"X-Token": "t1"}).json())
print(c.get("/marks", headers={"X-Token": "s1"}).json())
print(c.delete("/marks/5", headers={"X-Token": "t1"}).status_code, c.delete("/marks/5", headers={"X-Token": "a1"}).json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'viewer': 'Ms. Kapoor', 'subject': 'Physics', 'min_score': 40} {'detail': "Requires one of ['teacher', 'admin']"} 403 {'deleted': 5}
Key points
- Any callable can be a dependency
- Callable instances hold config in __init__ and check in __call__
- Factory functions with closures do the same
- Depends() with no argument uses the annotated class
- Do not keep per-request state on shared instances
Common mistakes
- Writing a separate dependency function for every role combination
- Storing request data on a shared dependency instance
- Trying to override each RoleChecker instance in tests instead of the user dependency
- Forgetting that Depends() without arguments needs a type annotation
Follow-ups
- How would you combine roles with OAuth2 scopes?
- How do you test endpoints guarded by RoleChecker?
- What is the difference between Depends() and Depends(SomeClass)?
Tips
- Show the callable-instance pattern and explain when __init__ and __call__ run
- Mention the shared-instance state pitfall
- Explain the testing approach