skip to content

In FastAPI, when do you include an APIRouter and when do you mount a sub-application with app.mount, and what does a mount not share?

level: middleimportance: must knowfreq 46%

answer

  1. same app or a separate app
  2. whose schema lists the route
  3. /internal/docs
  4. app-wide dependencies stop at the mount
  5. outer middleware still wraps it

basics

~20 s

Include an APIRouter for parts of one API, sharing the app's schema, docs, handlers and app-wide dependencies. Mount an independent ASGI app with app.mount() when it needs its own docs, handlers and dependencies; the main middleware still wraps it.

solid answer

~40 s

`include_router()` makes a router's operations part of the app: one OpenAPI schema, one `/docs`, the app's exception handlers, app-wide `dependencies` and `dependency_overrides`. `app.mount("/internal", sub)` hands every path under `/internal` to a separate ASGI app. A mounted FastAPI app keeps its own schema and serves its own docs at `/internal/docs`, because FastAPI passes the mount path as `root_path`; the main `/docs` does not list it. The main app's app-wide dependencies and exception handlers do not apply inside it, and its own lifespan is not run, but middleware added to the main app still wraps requests to it. So: routers for modules of one API, mounts for an independently documented API, a WSGI app wrapped with a2wsgi, or `StaticFiles`.

code

python · 26 lines
python
from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_served_by(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Served-By"] = "main"
    return response


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


internal = FastAPI(title="Internal API")


@internal.get("/ping")
async def ping(request: Request) -> dict[str, str]:
    return {"root_path": request.scope["root_path"]}


app.mount("/internal", internal)

go deeper

for a junior

Remember that include_router adds routes to the same app and docs, while app.mount attaches a separate app with its own docs at the mount path.

for a middle

Walk through what a mounted app does not share: schema, app-wide dependencies, exception handlers and lifespan, and why the main app's middleware still wraps it.

for a senior

Point out the security trap: moving an admin area from an included router to a mount silently drops app-wide auth dependencies, so the mounted app needs its own checks.

for a principal

Weigh one API with routers against several mounted apps: separate docs and error contracts give autonomy but multiply the auth and handler wiring a team must keep consistent.

## Two ways to compose an app FastAPI offers two composition tools that look similar in `main.py` and behave very differently. - **`app.include_router(router)`** takes an `APIRouter` and makes its **path operations** (decorated endpoint functions) part of the application. The router is not isolated from the app: its operations are matched by the app's router, validated by FastAPI, documented in the app's schema and handled by the app's exception handlers. - **`app.mount(path, other_app)`** attaches a complete, independent **ASGI application** (any object that speaks the ASGI server interface) at a path prefix. Every request under that prefix is passed to the other app, which handles it on its own terms. The other app can be another `FastAPI()` instance, `StaticFiles`, a WSGI app wrapped in a2wsgi's `WSGIMiddleware`, or any ASGI app. ## What each one shares with the main app | | Included `APIRouter` | Mounted sub-application | |---|---|---| | OpenAPI schema and `/docs` | the main app's single schema | its own; the main `/docs` does not list it | | App-wide `FastAPI(dependencies=...)` | applied | not applied | | Main app's exception handlers | applied | not applied; the sub-app uses its own | | Main app's middleware | wraps it | still wraps it, as the outer layer | | Its own lifespan | an `APIRouter(lifespan=...)` is merged into the app's | not run by the main app | | Matching order | by declaration with the other routes | by declaration; a mount at a broad path can shadow later routes | The middleware row surprises people. `app.mount()` adds a route to the main app's router, and the main app's middleware stack sits outside that router, so `@app.middleware("http")` functions and `add_middleware()` entries see requests to the mounted app too. The exception handler row surprises them the other way: an exception raised inside a mounted FastAPI app is handled by that app's own handlers, and if it has none for that class it becomes a `500` there, even when the main app registered a handler for exactly that exception. ## How the mounted app knows its own prefix When FastAPI mounts a sub-application, the sub-app receives the mount path as the ASGI `root_path`. That is why a mounted FastAPI app at `/internal` serves working docs at `/internal/docs`: its schema's `servers` entry points at `/internal`, so the docs UI sends "Try it out" requests to the right place. The sub-app can mount further apps of its own and the prefixes chain. Setting `root_path` by hand behind a reverse proxy is a different subject, covered with proxy deployment. ## Choosing between them Use **include_router** when the code is one API split into modules: users, items and admin areas that share authentication, error format and documentation. This is the default and covers most applications, because it keeps: - one schema, so generated clients and the docs UI see the whole API; - one set of exception handlers, so every endpoint returns the same error body; - one place for app-wide dependencies and `dependency_overrides`, so tests swap a dependency once; - one lifespan, so shared resources are opened and closed once. Use **mount** when the attached thing is genuinely independent: 1. a second API with its own docs, version or audience, such as an internal API that should not appear in the public schema; 2. an app built with a different stack, such as a legacy Flask or Django app wrapped with a2wsgi's `WSGIMiddleware`; 3. static files with `StaticFiles`, which is itself a small ASGI app (for a built frontend, `app.frontend()` is now the better tool). ## The security consequence Because app-wide dependencies stop at a mount, an authentication check passed to `FastAPI(dependencies=[...])` does **not** protect a mounted sub-application. A team that moves an admin area from an included router to a mounted app to give it separate docs can expose it without noticing, since the code path that enforced auth no longer runs. A mounted app must carry its own checks, for example its own `FastAPI(dependencies=[...])` or router dependencies, or be protected by middleware on the main app, which does still wrap it. Review a mount the way you would review a new service: what authenticates it, what handles its errors, and what its docs reveal. ## Related details - Mounted apps do not get their lifespan run by the parent app; how lifespans behave across mounted apps is covered with lifespan and state. - Route matching follows declaration order, so a mount at a short prefix declared early can catch requests meant for later routes. - A request for the bare mount path, such as `/internal` without a trailing slash, is redirected with `307` to `/internal/`.

  • In FastAPI, a custom exception handler registered on the main app does not fire for an error raised in a mounted sub-app. Why, and how do you fix it?
    A mounted FastAPI app runs its own exception middleware with its own handlers, so the sub-app answers the error itself, with its own handler or a `500`, and the main app's handler cannot replace that response. Register the handler on the sub-app as well, for example by sharing one function that adds the handlers to every app you create.
  • In FastAPI, why does a mounted sub-app's docs page still send requests to the right paths?
    FastAPI passes the mount path to the sub-app as the ASGI `root_path`. The sub-app uses it in its schema's `servers` entry, so the docs UI served at `/internal/docs` prefixes every request with `/internal`. Nested mounts chain the same way.
  • In FastAPI, if an internal admin API must be hidden from the public docs, is mounting the only option?
    No. An included router can be left out of the schema with `include_in_schema=False` on `include_router()` and still share the app's auth, handlers and dependencies. Mount it only when it should also have its own docs, its own error handling or a separate lifecycle, and then give it its own auth.

Included routers are departments of one company: one directory in the lobby, one set of house rules. A mounted app is a separate tenant subletting a floor: it keeps its own directory and its own rules, though its visitors still pass the building's front-door security, which is the main app's middleware.

  • A mounted sub-app's routes appear in the main app's /docs
  • App-wide dependencies on the main app also protect mounted apps
  • Mounted apps bypass the main app's middleware entirely
  • The main app's exception handlers catch errors from mounted apps
  • include_router and mount are interchangeable apart from syntax