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:
- One router per feature or bounded context.
- Keep request and response models near the API module or in
schemas/. - Keep persistence models separate.
- Use dependencies for auth, database, and contextual concerns.
- Use service functions for workflows that combine validation, persistence, and side effects.
FastAPI makes it easy to write route functions that do everything. Resist that ease once the route stops being trivial.