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 20: Creating HTTP APIs with Router Modules

ASP.NET Core Web API controllers often use attributes, filters, route prefixes, and action results. FastAPI router modules give the same larger-scale organization.

router = APIRouter(
    prefix="/api/recipes",
    tags=["recipes"],
    responses={404: {"description": "Not found"}},
)


@router.patch("/{recipe_id}", response_model=RecipeRead)
def update_recipe(
    recipe_id: int,
    patch: RecipePatch,
    db: DbSession,
    user: CurrentUser,
) -> RecipeRead:
    return recipes_service.update_recipe(db, recipe_id, patch, user)

API module practices:

FastAPI makes it easy to write route functions that do everything. Resist that ease once the route stops being trivial.