skip to content

Reverse Proxy Setup

Behind a proxy that strips /api/v1, root_path keeps docs and URLs right, and forwarded headers must be trusted only from the proxy. Interviewers ask why the docs page cannot load its schema.

on this pageshow

explore

questions

5

In a FastAPI app that a reverse proxy serves under /api/v1, what does root_path tell the app, and where can you set it?

level: juniorimportance: should knowfreq 30%

answer

  1. a prefix the app never sees
  2. lives in the ASGI scope
  3. server option or app constructor
  4. routes stay written without it

basics

~20 s

root_path is the public path prefix a proxy adds in front of the app. Routes stay declared without it; FastAPI uses it for the docs page, the schema's servers entry and generated URLs. Set it with --root-path or FastAPI(root_path=...).

solid answer

~40 s

When a proxy publishes the app at `/api/v1` and strips that prefix before forwarding, the app still receives `/app`, so routes stay declared as `/app`. `root_path` tells the app the prefix it cannot see: it travels in the ASGI scope, and FastAPI reads it to point the `/docs` page at `/api/v1/openapi.json`, to add a `servers` entry of `/api/v1` to the schema, and Starlette uses it when building URLs with `url_for`. You set it with `fastapi run --root-path /api/v1` (the same option Uvicorn has), or with `FastAPI(root_path="/api/v1")` when you cannot pass a server option. Uvicorn does not start listening under the prefix; it expects the proxy to call `/app`.

code

python · 8 lines
python
from fastapi import FastAPI, Request

app = FastAPI()


@app.get("/app")
def read_main(request: Request):
    return {"message": "Hello World", "root_path": request.scope.get("root_path")}

go deeper

for a junior

Recall that root_path names a prefix the proxy removed, that routes stay written without it, and the two places to set it: the --root-path option and FastAPI(root_path=...).

for a middle

Explain what reads root_path at request time: the docs page building the schema URL, the servers entry in the schema, url_for, and Starlette stripping it before route matching.

for a senior

Show you can check the deployed value from request.scope and know why the server option is preferred over the constructor: it also prefixes the ASGI path, so redirects and request.url stay public.

for a principal

Frame root_path as a contract with whoever owns the proxy: the strip-or-keep decision and the prefix have to be written down in one place, or each service ends up guessing.

## The setup A **reverse proxy** sits in front of the application server and forwards requests to it. A common arrangement publishes an API at `https://example.com/api/v1` and **strips** the `/api/v1` prefix before forwarding, so a request for `https://example.com/api/v1/app` arrives at the application server as `/app`. The FastAPI code is written as if the prefix did not exist: - the path operation is declared as `@app.get("/app")`; - the application server (Uvicorn, started by `fastapi run`) listens on its own address and receives `/app`; - only the outside world uses `/api/v1/app`. Routing works without any extra setting. What breaks is everything that has to produce a **public** URL: the interactive docs page, the OpenAPI schema's idea of where the API lives, and links built from the request. ## How the prefix travels through one request Follow a request for `https://example.com/api/v1/app` with the server started as `fastapi run main.py --root-path /api/v1`: 1. The browser sends `GET /api/v1/app` to the proxy. 2. The proxy removes `/api/v1` and forwards `GET /app` to Uvicorn. 3. Uvicorn builds the ASGI scope with `root_path` set to `/api/v1` and puts the prefix back in front of `path`, as the ASGI specification describes the field. 4. Starlette removes the leading `root_path` again before matching, so the route declared as `/app` is found. 5. Anything that builds a URL from the scope, such as `url_for`, the docs page or a redirect, now produces `/api/v1/...`, the address the browser can actually reach. The app's code never mentions `/api/v1`; only the start command does. That is the point: the same code can run behind a proxy at any prefix, or directly with no prefix at all. ## What root_path is `root_path` is a field of the **ASGI scope**, the dictionary the server hands the app for every request. The ASGI specification defines it for exactly this case: the path prefix under which the application is mounted, as clients see it. FastAPI and Starlette read it per request: - the `/docs` (Swagger UI) and `/redoc` pages are rendered with the schema URL `root_path + openapi_url`, so the browser fetches `/api/v1/openapi.json`; - the `/openapi.json` endpoint adds, unless `root_path_in_servers=False`, a `servers` entry with the URL `/api/v1` at the front of the list, so "Try it out" calls go through the prefix; - `request.url_for(...)` builds links that include the prefix; - Starlette removes a leading `root_path` from the path before matching routes, which is also how mounted sub-applications see their own paths. ## Where to set it | Where | How | When to use it | |---|---|---| | `fastapi run` | `fastapi run main.py --root-path /api/v1` | the usual production start | | Uvicorn directly | `uvicorn main:app --root-path /api/v1` | when Uvicorn is started without the FastAPI CLI | | The app | `FastAPI(root_path="/api/v1")` | when you cannot pass a server option | The server option is the closer fit to the ASGI specification: Uvicorn puts the prefix in `root_path` **and** in front of the scope's `path`, so every URL Starlette builds from the request carries it. The constructor parameter only sets `scope["root_path"]` when the app is called. Docs, the `servers` entry and `url_for` come out right either way. ## What it does not change 1. **Routes.** You do not add `/api/v1` to decorators; the proxy removes it before the app sees the request. 2. **The listening address.** Uvicorn does not listen under the prefix; it only puts it in the scope it hands to the app. Called directly, the server still answers at `http://127.0.0.1:8000/app`, and the proxy is expected to call that path. 3. **The proxy.** `root_path` does not strip anything for the proxy. If the proxy forwards the prefix unchanged, the server's `--root-path` would add it a second time, so that topology is configured differently. ## Checking it A path operation can read the value from the scope, which is the quickest way to confirm what the server passed: ```python @app.get("/app") def read_main(request: Request): return {"root_path": request.scope.get("root_path")} ``` Started with `--root-path /api/v1`, this returns `{"root_path": "/api/v1"}` whether you call the app through the proxy or directly. ## Common mistakes - Writing every route as `/api/v1/...` while the proxy strips the prefix: every request then misses its route. - Treating `root_path` like an `APIRouter` prefix: a router prefix changes the declared paths and the schema's `paths`, while `root_path` leaves both alone and only says where the app sits publicly. - Moving `docs_url` or `openapi_url` under `/api/v1` to fix the docs page: the stripping proxy forwards `/docs`, so the moved routes are never reached.

  • Is FastAPI(root_path="/api/v1") exactly the same as starting the server with --root-path /api/v1?
    Almost. Both make the docs page, the `servers` entry and `url_for` include `/api/v1`. The server option also prefixes the ASGI `path` itself, as the specification expects, so `request.url` and the trailing-slash redirect carry the prefix. Behind a stripping proxy with only the constructor parameter, URLs built from the request's path miss it. Prefer the server option and keep the constructor for platforms where you cannot pass one.
  • If you start fastapi run with --root-path /api/v1, can you open http://127.0.0.1:8000/api/v1/app directly?
    No. Uvicorn does not listen under the prefix; it hands `root_path` to the app and expects requests for `/app`. A direct request for `/app` works and reports `root_path` as `/api/v1`. Requesting `/api/v1/app` directly gets the prefix added a second time and answers 404, because only the proxy is supposed to add it.

  • Adds /api/v1 to every route decorator even though the proxy strips it
  • Thinks --root-path makes Uvicorn listen under the /api/v1 path
  • Expects root_path to change the paths listed in the OpenAPI schema
  • Moves docs_url under /api/v1 to fix the docs behind a stripping proxy
open as a page

Behind a TLS-terminating proxy, why does a FastAPI app run with fastapi run redirect /items to an http:// URL, and what fixes it?

level: middleimportance: should knowfreq 35%

basics

~10 s

The proxy reaches Uvicorn over plain HTTP, so the request's scheme is http unless Uvicorn trusts the proxy's X-Forwarded-Proto. It trusts only 127.0.0.1 and ::1 by default; list the proxy's address in --forwarded-allow-ips.

open as a page

Behind a proxy that strips /api/v1, why does a FastAPI app's /docs page fail to load its schema, and how does root_path fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The /docs page is HTML that tells the browser to fetch /openapi.json, which at the domain root misses the /api/v1 prefix the proxy routes. With root_path set, FastAPI writes /api/v1/openapi.json into the page and adds a /api/v1 servers entry.

open as a page

A FastAPI app run with --forwarded-allow-ips="*" rate-limits on request.client.host; how can a client evade the limit, and what should the setting be?

level: seniorimportance: should knowfreq 35%

basics

~20 s

With "*", Uvicorn takes the leftmost X-Forwarded-For entry, which a client can forge and an appending proxy passes along. Set --forwarded-allow-ips to the proxy's address or network so Uvicorn picks the nearest untrusted hop instead.

open as a page

When a reverse proxy forwards /api/v1/items to a FastAPI app unchanged, why does fastapi run --root-path /api/v1 answer 404, and what works instead?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

Uvicorn's --root-path prepends the prefix to a path that already carries it, and Starlette strips it only once, so /items/ never matches. Declare the prefix on the routes with an APIRouter prefix, or set FastAPI(root_path=...) instead of the server option.

open as a page