Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 50 ยท Structuring larger apps

Mounting sub-applications and static directories

Use app.mount in FastAPI to attach static directories, separate FastAPI sub-apps with their own docs, and WSGI apps, and learn how root_path works behind a proxy.

An APIRouter splits one application into files. Sometimes you want something stronger: a completely separate application that lives under a path of your main app. It has its own routes, its own middleware, its own exception handlers and, if it is a FastAPI app, its own /docs. The tool for that is app.mount().

You already met one use of it, serving a directory of files with StaticFiles in Jinja2 templates and static files. Here you will learn what a mount really is, build a FastAPI sub-application, and understand root_path, the setting that confuses almost everybody the first time they deploy behind a proxy.

What a mount is

app.mount("/prefix", some_asgi_app) tells the router: "every request whose path starts with /prefix belongs to some_asgi_app". The mounted app is any ASGI application: a Starlette app, another FastAPI app, StaticFiles, or a WSGI app wrapped in WSGIMiddleware.

Two rules explain almost all mount behaviour:

  1. The prefix is stripped. The sub-app sees /items, not /api/items. Its own routes do not know where they are mounted.
  2. Mounts are outside the parent's route table. The parent's OpenAPI document, dependencies and middleware-by-router do not include the mounted app's routes. (Application-level middleware on the parent still wraps everything.)

Router vs mount

include_router Same app, same docs, shared dependencies.
mount A separate app with its own docs and rules.
1 / 2

A FastAPI sub-application

A sub-application is just another FastAPI() object. Mount it and it keeps its own interactive docs at <prefix>/docs and its own schema at <prefix>/openapi.json.

Python Mount a FastAPI app under /admin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The main document lists only /hello; the mounted app's /users and /boom appear in the admin document, whose paths are written without the /admin prefix. Swagger UI for the admin app knows to call the right URL because FastAPI tells the sub-app its mount path (this is root_path, explained below).

Mounted apps are isolated, so a handler registered on the parent does not apply to them. A custom @app.exception_handler(...) or a dependency on the main app will not be used for /admin/*; register them on the sub-app too. This isolation is the main reason to choose a mount: the admin area can have different middleware, CORS rules or authentication from the public API.

Mounted paths do not take part in route matching order the way ordinary routes do. A mount at /admin catches everything below it, including /admin/anything that the sub-app does not define (it answers 404 itself). Mount static directories and sub-apps after your normal routes, and never mount two apps on overlapping prefixes unless you intend the first one to win.

Versioned sub-apps

Mounting is one way to run /v1 and /v2 side by side, each with independent docs and schemas. The trade-offs, and the lighter router-based alternative, are in API versioning.

Static directories

StaticFiles is an ASGI app that serves files, so it mounts like any other:

Python
from fastapi.staticfiles import StaticFiles

app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/", StaticFiles(directory="web", html=True), name="site")  # must come last

Options worth knowing:

  • html=True serves index.html for directory requests, which turns the mount into a tiny static website host (handy for serving a built single-page app next to the API).
  • check_dir=False skips the "directory must exist" check at startup.
  • follow_symlink=True allows symbolic links that point outside the directory (off by default for safety).
  • Mounting at "/" swallows everything that no earlier route matched. Always add it last.

StaticFiles does conditional requests (ETag, Last-Modified, 304 Not Modified) and range requests for you. The live runner here cannot serve files (it has no worker threads for disk reads), so these snippets are read-only. They work on any real server.

Mounting a WSGI app

Flask and Django are WSGI frameworks. If you are migrating step by step, you can host the old app inside the new one:

Python
from fastapi.middleware.wsgi import WSGIMiddleware
from flask import Flask

flask_app = Flask(__name__)

@flask_app.route("/")
def legacy_home():
    return "Hello from Flask!"

app.mount("/legacy", WSGIMiddleware(flask_app))

The WSGI code runs in a thread pool, so it does not block the event loop. Treat this as a migration bridge, not as a permanent design. For the Flask side of the story, see the Flask tutorial. (In recent FastAPI versions WSGIMiddleware is also importable from a2wsgi, which is the maintained implementation; the Starlette copy is deprecated.)

root_path: when the app lives under a prefix

Here is the situation behind root_path. Your app runs on a server, but a reverse proxy exposes it under /api/v1: the browser asks for https://example.com/api/v1/items, the proxy strips /api/v1 and forwards /items to uvicorn. The app's routes are written without the prefix, which is fine, but the app must still know the public prefix to produce correct links, and above all the Swagger page: it has to ask for /api/v1/openapi.json, not /openapi.json.

root_path is exactly that "public prefix the proxy removed". There are three ways to set it:

Terminal
uvicorn main:app --root-path /api/v1          # command line
Python
app = FastAPI(root_path="/api/v1")             # in code (an escape hatch)

Many proxies also pass an X-Forwarded-Prefix header, and uvicorn's --proxy-headers flag turns it into the root path for you.

You can see the effect without any proxy by creating the app with a root_path and reading what the docs and the request report.

Python root_path and the OpenAPI servers list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Routes still match /where (the prefix is not part of the route), but url_for and the OpenAPI servers entry include /api/v1, so generated links and the Swagger "Try it out" button hit the public address. Without root_path, the docs page would work locally but call the wrong URL in production, a classic "works on my machine" bug. Notes about how this ties to proxies are in the deployment lesson.

A sub-application mounted with app.mount("/admin", admin) automatically gets root_path="/admin" (appended to the parent's), which is how its docs know their own prefix.

Common mistakes

  • Expecting the parent's dependencies, tags or CORS configuration to apply to a mounted app. They do not; configure the sub-app itself.
  • Mounting at "/" early in the file, which hides routes defined later.
  • Forgetting that the mounted app's paths in its OpenAPI file are relative to the mount.
  • Setting root_path in code and passing --root-path and a proxy header, which doubles the prefix. Choose one source.
  • Using a mount when a router would do. If you simply want a /users section with shared docs, use APIRouter, as described in Routers and project layout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A sub-app is mounted at /admin and defines @sub.get("/users"). Which URL reaches it, and what path does the sub-app see?

    The mount prefix is stripped before the sub-application routes the request.
  2. 2. Where do the routes of a mounted FastAPI sub-app appear in the documentation?

    Each FastAPI app has its own OpenAPI schema. The parent does not merge a mounted app's routes.
  3. 3. What does root_path describe?

    A proxy may strip a prefix before forwarding. root_path tells the app about it so links and the docs use the public URL.
  4. 4. Where should app.mount("/", StaticFiles(...)) be placed?

    A mount at / matches every path, so routes defined after it would never be reached.

Summary

  • app.mount(prefix, asgi_app) attaches a separate ASGI application; the prefix is stripped before the sub-app routes the request.
  • A mounted FastAPI app has its own routes, middleware, exception handlers and OpenAPI docs, and the parent's configuration does not apply to it.
  • StaticFiles (with html=True for a static site) and WSGIMiddleware (for Flask/Django) are common mounts.
  • Put catch-all mounts such as "/" after all other routes.
  • root_path is the public prefix removed by a proxy; set it through --root-path, forwarded headers, or FastAPI(root_path=...) so docs and generated URLs are correct.

Next: run two generations of an API at once in API versioning.