Chapter 21: Filters, Dependencies, and Cross-Cutting Concerns
ASP.NET Core has filters for MVC and Razor Pages. FastAPI does not have the same filter taxonomy. The closest tools are:
- Dependencies for preconditions and request-scoped values.
- Middleware for cross-cutting request/response wrapping.
- Custom
APIRouteclasses for advanced route behavior. - Exception handlers for consistent error translation.
Authorization dependency:
from fastapi import Depends, HTTPException, status
def require_admin(user: CurrentUser) -> None:
if "admin" not in user.roles:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin role required",
)
Apply to a route:
@router.delete(
"/{recipe_id}",
dependencies=[Depends(require_admin)],
status_code=204,
)
def delete_recipe(recipe_id: int, db: DbSession) -> None:
recipes_service.delete_recipe(db, recipe_id)
Use the smallest mechanism that fits. Do not build a filter framework until your app proves it needs one.