CodeSampleX

Sample

fastapi 0.141.1: Configure FastAPI behind a reverse proxy prefix with root_path and root_path_in_servers without route matching 404s or broken Swagger UI docs

Verified sample for pypi fastapi 0.141.1: Configure FastAPI behind a reverse proxy prefix with root_path and root_path_in_servers without route matching 404s…

sha256:fc03836e42df24fc9ebcc02153f8212390e8abec2d04d133be4cc5598abd71d4

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment python linux x64 python python pip

Verification-run environments

Environment Contract Stages Run
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-16
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

Case

HOW
Goal
Configure FastAPI behind a reverse proxy prefix with root_path and root_path_in_servers without route matching 404s or broken Swagger UI docs
Packages
Symbols
  • fastapi.FastAPI
  • root_path
  • root_path_in_servers
  • fastapi.testclient.TestClient
  • starlette.routing.get_route_path
Environment
python
Created
2026-08-16T06:22:44Z

Contract

  1. assert Starlette get_route_path strips root_path from ASGI scope path, dispatching /api/v1/items/42 to @app.get('/items/{item_id}')
  2. assert defining route decorators with root_path prefix as @app.get('/api/v1/trapped') fails matching and 404s on /api/v1/trapped
  3. assert a trailing slash on root_path='/api/v1/' prevents prefix stripping in get_route_path, returning 404 on proxied requests
  4. assert request.url_for automatically includes root_path without manual string concatenation
  5. assert static app.openapi() contains no servers, while the ASGI GET /openapi.json endpoint dynamically injects [{'url': '/api/v1'}]
  6. assert FastAPI(root_path_in_servers=False) suppresses OpenAPI servers injection
  7. assert Swagger UI /docs dynamically configures the JS bundle to fetch /api/v1/openapi.json
  8. assert mounting a sub-app at /v2 composes root_path to /api/v1/v2 for routing, url_for, and OpenAPI documentation

Files

  • NOTES.md
  • csx.json
  • requirements.txt
  • src/__init__.py
  • src/app.py
  • test/contract.py

Download the source artifact (tar.gz)

Source

NOTES.md
# Notes on FastAPI `root_path` and Proxy Configuration

## 1. What `search_known_solution` Answered
- `search_known_solution` returned existing sample `sha256:8bcaa6f98cea6edf681d2b0f76a18856106de62aab70009b1d22a5a50abb1257` ("Test a FastAPI app with TestClient and no network, and assert the validation error bodies it returns").
- This project targets a distinct configuration trap: reverse proxy prefix routing, Starlette `get_route_path` stripping, `root_path` trailing slash failure, dynamic OpenAPI servers injection, and `root_path_in_servers`.

## 2. What a Naive Model Would Have Written Instead
- When asked to configure FastAPI behind a proxy path `/api/v1`, a naive model defines route paths with the prefix (`@app.get("/api/v1/items")`), sets `root_path="/api/v1/"` with a trailing slash, manually concatenates `f"{app.root_path}{request.url_for(...)}"`, or assumes `app.openapi()` returns the server URL that Swagger UI uses.

## 3. How the Wrong Version Fails
- Loudly in live traffic with HTTP 404 Not Found because `get_route_path` strips the proxy prefix from incoming request paths (turning `/api/v1/trapped` into `/trapped`), and trailing slashes on `root_path` break prefix parsing so all proxied routes 404 while direct internal tests pass green.
csx.json
{"case":{"caseId":"case:sha256:494682b468175029dd3c2639497fd9fe39e122603b5fc7100d011cdf70954865","contract":["assert Starlette get_route_path strips root_path from ASGI scope path, dispatching /api/v1/items/42 to @app.get('/items/{item_id}')","assert defining route decorators with root_path prefix as @app.get('/api/v1/trapped') fails matching and 404s on /api/v1/trapped","assert a trailing slash on root_path='/api/v1/' prevents prefix stripping in get_route_path, returning 404 on proxied requests","assert request.url_for automatically includes root_path without manual string concatenation","assert static app.openapi() contains no servers, while the ASGI GET /openapi.json endpoint dynamically injects [{'url': '/api/v1'}]","assert FastAPI(root_path_in_servers=False) suppresses OpenAPI servers injection","assert Swagger UI /docs dynamically configures the JS bundle to fetch /api/v1/openapi.json","assert mounting a sub-app at /v2 composes root_path to /api/v1/v2 for routing, url_for, and OpenAPI documentation"],"goal":"Configure FastAPI behind a reverse proxy prefix with root_path and root_path_in_servers without route matching 404s or broken Swagger UI docs","kind":"HOW","packages":["pkg:pypi/fastapi@0.141.1","pkg:pypi/starlette@1.6.0","pkg:pypi/httpx2@2.10.0","pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["fastapi.FastAPI","root_path","root_path_in_servers","fastapi.testclient.TestClient","starlette.routing.get_route_path"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/fastapi@0.141.1","pkg:pypi/starlette@1.6.0","pkg:pypi/httpx2@2.10.0","pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["fastapi.FastAPI","root_path","root_path_in_servers","fastapi.testclient.TestClient","starlette.routing.get_route_path"],"verifierAdapter":"python@1"}
requirements.txt
# Full resolved closure installed with --no-deps in contract verifier
fastapi==0.141.1
starlette==1.6.0
annotated-doc==0.0.5
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.16.0
typing-inspection==0.4.4
annotated-types==0.8.0
anyio==4.14.2
idna==3.18
httpx2==2.10.0
httpcore2==2.10.0
truststore==0.10.4
httpx==0.28.1
httpcore==1.0.9
h11==0.16.0
certifi==2026.7.22
src/__init__.py
"""FastAPI root_path configuration sample."""
src/app.py
"""FastAPI app demonstrating root_path, proxy routing, and OpenAPI server resolution.

Behind a reverse proxy (e.g. Nginx, Traefik, API Gateway, Kubernetes Ingress),
the proxy routes an external prefix like `/api/v1` to the FastAPI backend.
FastAPI and Starlette use ASGI `scope["root_path"]` to understand this mount prefix.

This file establishes the reference application and variants that prove the
behavioral contracts around root_path prefix stripping, trailing slashes,
OpenAPI servers injection, Swagger UI asset loading, and sub-application mounting.
"""

from fastapi import FastAPI, Request
from pydantic import BaseModel


class ItemResponse(BaseModel):
    item_id: int
    received_root_path: str
    received_path: str
    generated_url_for: str


# Reference app configured behind reverse proxy prefix /api/v1
app = FastAPI(
    title="GatewayApp",
    version="1.0.0",
    root_path="/api/v1",
)


@app.get("/items/{item_id}", response_model=ItemResponse)
def get_item(item_id: int, request: Request):
    """A standard endpoint defined without the root_path prefix in its route decorator.

    Starlette's get_route_path strips scope['root_path'] from scope['path'],
    dispatching an external GET /api/v1/items/42 to this handler.
    """
    return ItemResponse(
        item_id=item_id,
        received_root_path=request.scope.get("root_path", ""),
        received_path=request.scope.get("path", ""),
        generated_url_for=str(request.url_for("get_item", item_id=item_id)),
    )


@app.get("/api/v1/trapped")
def trapped_endpoint():
    """An endpoint naively defined with the root_path prefix in the route decorator.

    Because get_route_path strips /api/v1 from the incoming scope['path']
    (/api/v1/trapped -> /trapped), this route fails to match and returns 404
    when requested at /api/v1/trapped. It only matches /api/v1/api/v1/trapped.
    """
    return {"status": "trapped"}


# Sub-application mounted at /v2
sub_app = FastAPI(title="SubApp", version="2.0.0")


@sub_app.get("/status")
def sub_app_status(request: Request):
    return {
        "status": "healthy",
        "root_path": request.scope.get("root_path", ""),
        "url_for": str(request.url_for("sub_app_status")),
    }


app.mount("/v2", sub_app)


def create_broken_trailing_slash_app() -> FastAPI:
    """App with an invalid trailing slash on root_path."""
    broken = FastAPI(title="BrokenTrailingSlashApp", root_path="/api/v1/")

    @broken.get("/ping")
    def ping():
        return {"ping": "pong"}

    return broken


def create_app_without_root_path_in_servers() -> FastAPI:
    """App with root_path_in_servers=False."""
    no_servers = FastAPI(
        title="NoServersApp",
        root_path="/api/v1",
        root_path_in_servers=False,
    )

    @no_servers.get("/ping")
    def ping():
        return {"ping": "pong"}

    return no_servers
test/contract.py
import sys
from pathlib import Path

# Ensure src is importable
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from fastapi import FastAPI, __version__ as fastapi_version
from fastapi.testclient import TestClient
from starlette.routing import get_route_path
import starlette

from src.app import (
    app,
    create_app_without_root_path_in_servers,
    create_broken_trailing_slash_app,
)

# TestClient talks to http://testserver without opening sockets or making DNS calls.
client = TestClient(app)

# ---------------------------------------------------------------------------
# 1. Starlette get_route_path contract: stripping root_path from ASGI scope
# ---------------------------------------------------------------------------
# When behind a proxy, scope['path'] contains the incoming URL path and
# scope['root_path'] contains the mount prefix. get_route_path strips root_path
# so FastAPI route matching operates on the un-prefixed relative path.
assert get_route_path({"type": "http", "path": "/api/v1/items/42", "root_path": "/api/v1"}) == "/items/42"
assert get_route_path({"type": "http", "path": "/api/v1", "root_path": "/api/v1"}) == ""

# A trailing slash on root_path silently breaks get_route_path stripping:
# Because path[len("/api/v1/")] is the first char of the subpath (not "/"),
# get_route_path aborts stripping and returns the full unstripped path!
assert get_route_path({"type": "http", "path": "/api/v1/ping", "root_path": "/api/v1/"}) == "/api/v1/ping"

# ---------------------------------------------------------------------------
# 2. Trapped vs Safe Route Matching under root_path
# ---------------------------------------------------------------------------
# Route declared as @app.get("/items/{item_id}") matches incoming /api/v1/items/42
res_safe = client.get("/api/v1/items/42")
assert res_safe.status_code == 200
data = res_safe.json()
assert data["item_id"] == 42
assert data["received_root_path"] == "/api/v1"
assert data["received_path"] == "/api/v1/items/42"

# TRAP: A naive developer writes @app.get("/api/v1/trapped") thinking route
# decorators must include the root_path. In reality, get_route_path strips
# /api/v1, leaving "/trapped" — which fails to match and returns 404!
res_trapped = client.get("/api/v1/trapped")
assert res_trapped.status_code == 404

# It only matches if the client requests the double prefix:
res_double = client.get("/api/v1/api/v1/trapped")
assert res_double.status_code == 200
assert res_double.json() == {"status": "trapped"}

# ---------------------------------------------------------------------------
# 3. URL Generation with url_for
# ---------------------------------------------------------------------------
# request.url_for automatically inspects scope['root_path'] and emits the
# fully qualified proxied URL. Manual string prepending (f"{root_path}{url_for}")
# produces double-prefixed invalid URLs.
assert data["generated_url_for"] == "http://testserver/api/v1/items/42"

# ---------------------------------------------------------------------------
# 4. Trailing Slash on root_path breaks live dispatch
# ---------------------------------------------------------------------------
broken_app = create_broken_trailing_slash_app()
broken_client = TestClient(broken_app)
# With root_path="/api/v1/", proxied requests return 404:
assert broken_client.get("/api/v1/ping").status_code == 404
# But direct requests without the proxy prefix match:
assert broken_client.get("/ping").status_code == 200

# ---------------------------------------------------------------------------
# 5. OpenAPI servers dynamic injection vs static app.openapi()
# ---------------------------------------------------------------------------
# Static export via app.openapi() has no request scope, so 'servers' is None:
assert app.openapi().get("servers") is None

# The ASGI endpoint GET /openapi.json dynamically injects the root_path into servers:
openapi_resp = client.get("/openapi.json")
assert openapi_resp.status_code == 200
assert openapi_resp.json().get("servers") == [{"url": "/api/v1"}]

# When root_path_in_servers=False is configured, server injection is suppressed:
no_servers_app = create_app_without_root_path_in_servers()
no_servers_client = TestClient(no_servers_app)
assert no_servers_client.get("/openapi.json").json().get("servers") is None

# ---------------------------------------------------------------------------
# 6. Swagger UI /docs loads OpenAPI schema from root_path
# ---------------------------------------------------------------------------
# The Swagger UI HTML page dynamically reads root_path from the ASGI scope
# and configures the Swagger UI bundle to fetch from /api/v1/openapi.json:
docs_resp = client.get("/docs")
assert docs_resp.status_code == 200
assert "url: '/api/v1/openapi.json'" in docs_resp.text

# ---------------------------------------------------------------------------
# 7. Sub-application Mounting composes root_path
# ---------------------------------------------------------------------------
# Mounting sub_app at /v2 under an app with root_path="/api/v1" automatically
# updates scope['root_path'] to /api/v1/v2 inside the sub-application:
sub_res = client.get("/api/v1/v2/status")
assert sub_res.status_code == 200
sub_data = sub_res.json()
assert sub_data["root_path"] == "/api/v1/v2"
assert sub_data["url_for"] == "http://testserver/api/v1/v2/status"

# Sub-app OpenAPI spec and docs automatically reflect the compound root_path:
sub_openapi = client.get("/api/v1/v2/openapi.json").json()
assert sub_openapi.get("servers") == [{"url": "/api/v1/v2"}]
sub_docs = client.get("/api/v1/v2/docs")
assert "url: '/api/v1/v2/openapi.json'" in sub_docs.text

print(
    f"contract ok: fastapi {fastapi_version}, starlette {starlette.__version__} "
    f"(root_path & root_path_in_servers verified)"
)

Origin Seeder

csx-seed