Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

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:

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.