Full answer
include_router and mount solve different problems.
include_router: adds routes to the same app. One OpenAPI schema, shared middleware, shared dependencies and exception handlers.mount: hands over a path prefix to a completely separate ASGI app.
Common uses
- Static files:
app.mount("/static", StaticFiles(directory="static"), name="static"). Served directly by Starlette without going through FastAPI's route machinery. In production, a CDN or the proxy usually serves them. - Sub-APIs:
admin_api = FastAPI(title="Admin API")mounted at/admin-apigets its own/docsat/admin-api/docs, its own middleware (stricter auth) and its own exception handlers. Useful when two audiences need separate documentation, or when a team owns a self-contained module. - Legacy apps:
from a2wsgi import WSGIMiddleware(the oldfastapi.middleware.wsgiis deprecated) wraps a Flask or Django WSGI app so it can live under/legacyduring a gradual migration. WSGI code runs in a thread pool.
Behaviours to know
- Prefix handling: the mounted app routes on the path after the prefix (
/users), while Starlette records the prefix inrequest.scope["root_path"](here/admin-api) so generated URLs and docs stay correct.request.url.pathstill shows the full path. Behind a proxy that strips a prefix, setFastAPI(root_path="/api")so docs findopenapi.json. - The parent's OpenAPI does not include mounted routes. Each mounted FastAPI app documents itself.
- Middleware on the parent wraps mounted apps too (it is outside), but dependencies and exception handlers registered on the parent do not apply inside the mounted app.
- Lifespan events of mounted apps do not run; only the main app's lifespan does. Start shared resources in the parent.
- Mount order matters: a mount at
/swallows everything declared after it, so put catch-all mounts (for example a single-page app) last.
python
import tempfile
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.testclient import TestClient
static_dir = Path(tempfile.mkdtemp())
(static_dir / "logo.txt").write_text("CAMPUS LOGO")
app = FastAPI(title="Campus API")
admin_api = FastAPI(title="Admin API")
@app.get("/students")
def students():
return ["Asha", "Ravi"]
@admin_api.get("/users")
def users(request: Request):
return {"path_seen_by_subapp": request.url.path, "root_path": request.scope["root_path"]}
def legacy_wsgi_app(environ, start_response): # a tiny WSGI app standing in for Flask
body = f"legacy page at {environ['PATH_INFO']}".encode()
start_response("200 OK", [("Content-Type", "text/plain"), ("Content-Length", str(len(body)))])
return [body]
from a2wsgi import WSGIMiddleware
app.mount("/admin-api", admin_api)
app.mount("/static", StaticFiles(directory=static_dir), name="static")
app.mount("/legacy", WSGIMiddleware(legacy_wsgi_app))
c = TestClient(app)
print(c.get("/students").json())
print(c.get("/admin-api/users").json())
print(c.get("/static/logo.txt").text)
print(c.get("/legacy/old/report").text)
print("parent schema paths:", sorted(c.get("/openapi.json").json()["paths"]))
print("sub-app schema paths:", sorted(c.get("/admin-api/openapi.json").json()["paths"]))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install a2wsgi`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): ['Asha', 'Ravi'] {'path_seen_by_subapp': '/admin-api/users', 'root_path': '/admin-api'} CAMPUS LOGO legacy page at /old/report parent schema paths: ['/students'] sub-app schema paths: ['/users']
Key points
- include_router merges routes; mount delegates a prefix to another ASGI app
- Mounted apps have their own docs, middleware and handlers
- WSGI apps mount through WSGIMiddleware (a2wsgi)
- Parent middleware wraps mounts; parent dependencies do not
- Mounted lifespan does not run; put catch-all mounts last
Common mistakes
- Expecting mounted routes to appear in the parent's OpenAPI schema
- Expecting parent dependencies or exception handlers to apply inside a mounted app
- Mounting a catch-all app at / before other routes
- Relying on a mounted app's lifespan to start resources
- Using the deprecated fastapi.middleware.wsgi.WSGIMiddleware instead of a2wsgi
Follow-ups
- How do you serve the API under /api behind a proxy that strips the prefix?
- How would you migrate a Flask app into FastAPI gradually?
- When is a second FastAPI app better than a second router?
Tips
- Contrast mount with include_router first
- List what is and is not shared with the parent
- Mention root_path behind proxies