Dependencies can depend on other dependencies, so you can compose small checks (get a token, then the current user, then verify the role).
A class with init can be a dependency (FastAPI calls it like a function); common for pagination parameters.
You can attach dependencies to a router or the whole app (dependencies=[Depends(...)]) so every route in it is protected, even when the dependency's return value is not used.
from typing import Annotated
class Pagination:
def __init__(self, skip: int = 0, limit: int = 20):
self.skip, self.limit = skip, limit
def require_admin(user: Annotated[User, Depends(get_current_user)]):
if not user.is_admin:
raise HTTPException(status_code=403, detail="Admin only")
return user
@app.get("/admin/users", dependencies=[Depends(require_admin)])
def admin_users(page: Annotated[Pagination, Depends()]):
return {"skip": page.skip, "limit": page.limit}