What is APIRouter and how do you structure large FastAPI applications?medium

Type
conceptual
Topic
router
Frequency
common
Tags
FastAPI, APIRouter, app structure, modular
Answer

APIRouter lets you split a FastAPI app into modules — each domain gets its own router with its own prefix and tags. Routers are mounted into the main app with app.include_router(). Router-level dependencies apply to all routes within without repeating them on each individual route.

Explanation

For anything beyond a few routes, a single file becomes unmaintainable. Each APIRouter is an independent mini-app that gets mounted into the main app. prefix adds a shared URL prefix so you don't repeat /documents in every path. tags group routes in the auto-generated OpenAPI docs. dependencies=[Depends(get_current_user)] on the router protects every route in that group. include_router can add an additional prefix on top of the router's own prefix when mounting.

Follow-upHow would you structure an API with documents, users, and search as separate concerns?
Follow-upHow does a router-level dependency differ from a route-level dependency?
Follow-upWhat does the tags parameter on APIRouter control?