skip to content

In FastAPI, how do you split an application into modules with APIRouter and include_router, and what do prefix, tags, dependencies and responses do?

level: juniorimportance: must knowfreq 62%

answer

  1. a mini app per module
  2. one schema, one /docs
  3. settings at creation or at include
  4. leading slash, no trailing slash
  5. dependencies run, values discarded

basics

~20 s

Each module declares its path operations on an APIRouter, and the main app adds it with app.include_router(). A prefix, tags, dependencies and responses set on the router or at include time apply to every operation in it, inside one OpenAPI schema.

solid answer

~40 s

An `APIRouter` takes the same decorators and options as `FastAPI`, so a `users`, `items` or `admin` module declares its own path operations on a router, and `main.py` calls `app.include_router()` for each. The shared settings can sit on `APIRouter(prefix=..., tags=..., dependencies=..., responses=...)`, next to the code, or be passed to `include_router()` when you cannot edit the router. `prefix` is joined to every path and must start with `/` and not end with one; `tags` group the operations in `/docs`; `dependencies` run on every request to those operations without passing a value to the endpoint, which is how a whole admin router is put behind an auth check; `responses` adds documented responses. Everything lands in the one app: one schema, one `/docs`, the app's exception handlers and app-wide dependencies.

code

python · 52 lines
python
import os
import secrets
from typing import Annotated

from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException

ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "")


async def require_admin(x_admin_token: Annotated[str | None, Header()] = None) -> None:
    if (
        not ADMIN_TOKEN
        or x_admin_token is None
        or not secrets.compare_digest(x_admin_token, ADMIN_TOKEN)
    ):
        raise HTTPException(status_code=401, detail="Admin token required")


users = APIRouter(prefix="/users", tags=["users"])
items = APIRouter(
    prefix="/items",
    tags=["items"],
    responses={404: {"description": "Item not found"}},
)
admin = APIRouter()


@users.get("/")
async def list_users() -> list[str]:
    return ["alice", "bob"]


@items.get("/{item_id}")
async def read_item(item_id: int) -> dict[str, int]:
    return {"item_id": item_id}


@admin.get("/stats")
async def read_stats() -> dict[str, int]:
    return {"users": 2}


app = FastAPI()
app.include_router(users)
app.include_router(items)
app.include_router(
    admin,
    prefix="/admin",
    tags=["admin"],
    dependencies=[Depends(require_admin)],
    responses={401: {"description": "Missing or wrong admin token"}},
)

go deeper

for a junior

Recall that APIRouter is a mini FastAPI you include with app.include_router(), and that prefix, tags, dependencies and responses apply to every operation in it.

for a middle

Explain where each setting can live, on APIRouter() or on include_router(), how they combine, and why router dependencies run for effect without passing a value.

for a senior

Show how you put a whole admin area behind one dependency so a new endpoint cannot skip the check, and how a missing header becomes a 401 rather than a 422.

for a principal

Talk about the module convention you would set for a team: settings on the router by default, include-time settings only for shared routers, and auth applied at the router boundary.

## What an APIRouter is FastAPI's `APIRouter` is a container for **path operations** (the functions you decorate with `@router.get`, `@router.post` and so on) that is not an application by itself. The tutorial calls it a "mini `FastAPI`": it accepts the same decorators and the same per-operation options, but it serves nothing until an app includes it. The usual layout gives each area of an API its own module, for example `app/routers/users.py`, `app/routers/items.py` and `app/internal/admin.py`, each exposing a variable `router`, and a short `app/main.py` that creates the `FastAPI()` instance and calls `app.include_router(users.router)` for each one. Including is not mounting. The operations of an included router become operations of the app: they appear in the app's single OpenAPI schema at `/openapi.json`, in its `/docs` and `/redoc` pages, and they run under the app's exception handlers, its app-wide `dependencies` and its `dependency_overrides`. ## Where the shared settings go The four options this question names can be set on the router or at include time, the decorator can add more for a single operation, and FastAPI combines them. | Set on | Typical use | |---|---| | `APIRouter(prefix=..., tags=..., dependencies=..., responses=...)` | your own module: the settings live next to the code they describe | | `app.include_router(router, prefix=..., tags=..., dependencies=..., responses=...)` | a router you cannot or should not edit, such as one shared between projects, or one included twice under different prefixes | | the path operation decorator | settings for one operation only, added to the router's | Passing options to `include_router()` leaves the original router object unmodified, so another project can include the same router with a different prefix or a different authentication dependency. ## What each option does - **`prefix`** is prepended to every path in the router: `prefix="/items"` plus `@router.get("/{item_id}")` serves `/items/{item_id}`. It must start with `/` and must not end with `/`; FastAPI raises an `AssertionError` with the message "A path prefix must not end with '/', as the routes will start with '/'" when you get that wrong. - **`tags`** are added to every operation's tags. They group operations in the docs UI and in the schema; tags set at include time, on the router and on the decorator are combined. - **`dependencies`** is a list of `Depends(...)` that FastAPI solves on every request to every operation in the router. Their return values are **not** passed to the endpoint, so they are for checks and side effects, typically raising `HTTPException(status_code=401)` when a token is missing. They run together with the app-wide dependencies, the decorator's dependencies and the endpoint's own parameters. - **`responses`** adds entries to the documented responses of every operation, for example a `404` or a `401` description. It changes the schema, not the runtime behaviour. ## Nesting and reuse A router can include another router with `router.include_router(other)`, and the prefixes chain: an `/api` router that includes an `/items` router serves `/api/items/...`. The same router can also be included more than once, for example under `/api/v1` and `/api/latest`, and each inclusion appears in the schema under its own paths. Two practical points follow from the module layout: 1. Put shared dependencies, such as the token check, in their own module (`app/dependencies.py`) and import them into each router module and into `main.py`. 2. Keep authentication on the router or the include call, not repeated in every endpoint, so that a new admin endpoint cannot be added without the check. ## Common mistakes - **Name collisions on import.** `from .routers.items import router` followed by `from .routers.users import router` leaves only the users router; import the modules and use `items.router` and `users.router`. - **A trailing slash in the prefix.** It fails at include time with an `AssertionError`, not at request time. - **Expecting a value from a router dependency.** Values from `dependencies=[...]` are discarded; declare a parameter when the endpoint needs the result. - **Expecting separate docs.** An included router is documented inside the app's schema; a separately documented app is a mount. ## Securing a group of operations The admin router in the example below has no auth of its own; the app adds it at include time with `dependencies=[Depends(require_admin)]`, a prefix of `/admin`, the tag `admin` and a documented `401`. Every request to an `/admin/...` path now runs `require_admin` first, and a request without the right header gets the `401` before the endpoint runs. The dependency reads the header as optional and compares it with `secrets.compare_digest`, so a missing header is a `401` rather than a validation `422`, and the comparison resists timing analysis. The same pattern covers an internal router that must only answer requests with a valid session. What this does not give you is isolation. An included router shares the app's schema, handlers and middleware. When you need a separately documented application with its own exception handlers, that is `app.mount()`, a different tool.

  • In FastAPI, when would you pass prefix and dependencies to include_router() rather than to APIRouter()?
    When the router is not yours to edit, such as one shared across projects, or when the same router is included twice with different settings, for example under `/api/v1` and `/api/latest`. `include_router()` leaves the original router unmodified, so each app decides its own prefix and its own auth dependency. For your own modules, setting them on `APIRouter()` keeps them next to the code.
  • In FastAPI, can a router-level dependency hand the current user to the endpoint?
    No. A dependency listed in `dependencies=[...]`, on the router, on `include_router()` or on the decorator, is solved for its effect only and its return value is discarded. If the endpoint needs the user object, declare the dependency as a parameter, for example `user: Annotated[User, Depends(get_current_user)]`; FastAPI caches it per request, so listing it in both places still calls it once.
  • In FastAPI, what happens when you nest routers, such as an items router included inside an api router?
    The prefixes chain and the settings accumulate: an `/api` router that includes an `/items` router serves `/api/items/...`, with the tags and dependencies of both inclusions applied. The outer router is then included in the app as usual, and every operation appears in the one schema under its full path.

  • An APIRouter gets its own /docs page and its own OpenAPI schema
  • A prefix like /items/ with a trailing slash is fine
  • Router dependencies pass their return value into each endpoint
  • Router dependencies run once when the router is included
  • Including a router copies it into an independent sub-application
  • Auth must be repeated on every admin endpoint