skip to content

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%

answer

  1. the browser makes a second request
  2. schema URL written into the HTML
  3. root_path plus openapi_url
  4. servers entry for Try it out

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.

solid answer

~40 s

The docs page loads in two steps: the browser gets the HTML from `/api/v1/docs`, then fetches the schema from the URL FastAPI wrote into that HTML. Without `root_path` that URL is `/openapi.json`, which resolves to `https://example.com/openapi.json`; the proxy only routes `/api/v1`, so the fetch fails and the page cannot list any operation. Starting the server with `--root-path /api/v1` makes FastAPI render `root_path + openapi_url`, so the page fetches `/api/v1/openapi.json`. It also inserts `{"url": "/api/v1"}` at the front of the schema's `servers`, so "Try it out" sends requests through the prefix. Moving `openapi_url` under `/api/v1` does not help, because the proxy strips the prefix before the app sees the request.

code

python · 23 lines
python
import re

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()


@app.get("/items/")
def list_items():
    return []


def docs_schema_url(root_path: str) -> tuple[str, object]:
    # Uvicorn --root-path puts root_path in the ASGI scope; TestClient can do the same.
    client = TestClient(app, root_path=root_path)
    html = client.get(root_path + "/docs").text
    schema = client.get(root_path + "/openapi.json").json()
    return re.search(r"url: '([^']+)'", html).group(1), schema.get("servers")


print(docs_schema_url(""))  # ('/openapi.json', None)
print(docs_schema_url("/api/v1"))  # ('/api/v1/openapi.json', [{'url': '/api/v1'}])

go deeper

for a junior

Remember that the docs page and the schema are two requests, and the page's schema URL needs the proxy's prefix.

for a middle

Explain that FastAPI writes root_path plus openapi_url into the page and adds a servers entry, and what root_path_in_servers=False removes.

for a senior

Diagnose from the network panel: name the failing URL, prove the schema answers under the prefix, and reject fixes that move routes inside a stripping proxy.

for a principal

Decide whether public docs are served through the proxy at all and make the prefix part of each service's deployment contract, so docs and Try it out stay right per environment.

## The symptom An API is published at `https://example.com/api/v1` by a reverse proxy that **strips** `/api/v1` and terminates TLS. Every endpoint works: `https://example.com/api/v1/items/` reaches the route declared as `/items/`. Opening `https://example.com/api/v1/docs` loads the page frame, but the page reports that it could not load the API definition and shows no operations. ## Why it happens The interactive docs are two separate requests: 1. The browser requests the HTML page. FastAPI's `/docs` route returns Swagger UI's page with the schema URL written into it; `/redoc` does the same for ReDoc. 2. JavaScript in that page fetches the **OpenAPI schema** from the written URL and renders it. FastAPI computes the URL at request time as `root_path + openapi_url`, with `openapi_url` defaulting to `/openapi.json`. With no `root_path`, the page tells the browser to fetch `/openapi.json`. The browser resolves that against the page's origin, giving `https://example.com/openapi.json`, outside the prefix the proxy routes to this app. That request returns an error from the proxy or from whatever else owns the root, and the page has nothing to render. ## How root_path fixes it Starting the server with `fastapi run --root-path /api/v1` (or Uvicorn's `--root-path`, or `FastAPI(root_path="/api/v1")`) puts `/api/v1` in the ASGI scope's `root_path`. FastAPI then changes three things: - the docs page asks for `/api/v1/openapi.json`, which the proxy strips back to `/openapi.json` and forwards to the app; - the OAuth2 redirect URL used by Swagger UI's authorize dialog gets the same prefix; - the `/openapi.json` response gains a `servers` entry `{"url": "/api/v1"}`, so the requests "Try it out" builds go to `/api/v1/items/` instead of `/items/`. ## Servers and root_path_in_servers | Configuration | `servers` in the schema | |---|---| | no `root_path`, no `servers` | omitted, the equivalent of a single server at `/` | | `root_path="/api/v1"` | `[{"url": "/api/v1"}]` | | `root_path` plus `servers=[staging, production]` | `/api/v1` first, then staging and production | | `root_path` with `root_path_in_servers=False` | only what you passed in `servers`, if anything | FastAPI skips the insert when a server with the same URL is already listed. `root_path_in_servers=False` removes only the automatic entry: the docs page still fetches `/api/v1/openapi.json`, but "Try it out" calls lose the prefix unless your own `servers` list supplies it. ## Why the API works while the docs do not The asymmetry confuses people at first. A request for an endpoint is made by a client that already knows the public URL, so the prefix is present, the proxy strips it, and the route matches. The docs page is different: its second request is made by the browser from a URL **the app wrote**, and the app only knows what it was told. Every URL the app writes into a response, rather than receives in a request, needs `root_path` to be right. That includes: - the schema URL in the Swagger UI and ReDoc pages; - the OAuth2 redirect page the Swagger UI authorize dialog returns to; - the `servers` entry that "Try it out" prepends to every path. The same logic is why FastAPI's own security examples declare `OAuth2PasswordBearer(tokenUrl="token")` with a **relative** URL; its release notes say the change keeps them working behind a reverse proxy. An absolute `"/token"` points at the domain root and misses the prefix. ## Mounted sub-applications A FastAPI sub-application mounted with `app.mount("/v2", sub)` gets its own docs. Mounting appends the mount path to `root_path`, so behind the proxy the sub-app's page fetches `/api/v1/v2/openapi.json` and its schema lists `/api/v1/v2` as its server, without extra settings. How mounting itself works belongs to the routers and mounted apps lesson. ## Fixes that do not work - **Moving `openapi_url` to `/api/v1/openapi.json`.** The route now lives at that path inside the app, but the proxy strips the prefix, so the app receives `/openapi.json` and finds nothing there. - **Adding `/api/v1` to every route.** The proxy keeps removing it, so the routes stop matching. - **Judging by the docs on the server's own port.** With `--root-path` set, that page fetches `/api/v1/openapi.json` from the server, which expects the proxy to have removed the prefix, so this view breaks while the public one works. Use the proxy's URL. ## Diagnosing it 1. In the browser's network panel, find the schema request and read its URL: `/openapi.json` with no prefix points to a missing `root_path`. 2. Request `https://example.com/api/v1/openapi.json` yourself; if it returns the schema, routing is fine and only the page's URL is wrong. 3. Check the `servers` list in that schema to confirm "Try it out" will use the prefix.

  • The app passes servers for a staging and a production host. Behind the proxy with root_path set, what does the schema's servers list contain?
    FastAPI inserts `{"url": "/api/v1"}` at the front, then keeps the staging and production entries in order, so the docs UI defaults to the server the page was loaded through. If the list already contains `/api/v1`, nothing is inserted. Pass `root_path_in_servers=False` to keep only your own list.
  • With root_path_in_servers=False, does the docs page still load behind the stripping proxy?
    Yes. The schema URL in the page is built from `root_path` independently, so the page still fetches `/api/v1/openapi.json`. What changes is "Try it out": with no prefixed server in the schema, its requests go to unprefixed paths at the domain root and fail unless your own `servers` list provides the right base URL.
  • Why does the docs page work on the server's own port before --root-path is set and break there after?
    Without `root_path` the page asks the server for `/openapi.json`, which exists. With `--root-path /api/v1`, the page asks for `/api/v1/openapi.json`, a path only the proxy can translate; the server prepends the prefix again and finds no route. The proxy's URL is the one meant to work.

  • Fixes the docs by moving openapi_url to /api/v1/openapi.json
  • Thinks the schema is embedded in the /docs HTML response
  • Believes root_path_in_servers=False stops the docs page loading
  • Judges the fix by the docs page on the server's own port
  • Blames CORS for the missing schema behind a same-origin proxy