← Back to FastAPI, page 3

fastapi-0044 · Hard senior

What does app.mount() do in FastAPI, and when do you use sub-applications, static files or mounted WSGI apps?

app.mount("/prefix", other_app) delegates every request under that path prefix to another ASGI application, which has its own routes, middleware, exception handlers and OpenAPI docs. It is used for StaticFiles, for versioned or independent sub-APIs (with separate docs), and for WSGIMiddleware around Flask or Django. Mounted apps are invisible to the parent's OpenAPI schema and do not share its dependencies, middleware or lifespan.

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

  1. 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.
  2. Sub-APIs: admin_api = FastAPI(title="Admin API") mounted at /admin-api gets its own /docs at /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.
  3. Legacy apps: from a2wsgi import WSGIMiddleware (the old fastapi.middleware.wsgi is deprecated) wraps a Flask or Django WSGI app so it can live under /legacy during 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 in request.scope["root_path"] (here /admin-api) so generated URLs and docs stay correct. request.url.path still shows the full path. Behind a proxy that strips a prefix, set FastAPI(root_path="/api") so docs find openapi.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