skip to content

In FastAPI, how do you turn off Swagger UI, ReDoc and the OpenAPI JSON in production, and what does that not protect?

level: middleimportance: should knowfreq 38%

answer

  1. three URL arguments on the app
  2. one switch removes all three
  3. a setting decides per environment
  4. every route still answers

basics

~20 s

Pass openapi_url=None to FastAPI(), usually from a setting: it removes /openapi.json and both docs UIs, which depend on it. docs_url=None and redoc_url=None hide only the UIs. Every endpoint still answers, so hiding docs is not access control.

solid answer

~40 s

`FastAPI()` takes `docs_url` (default `/docs`), `redoc_url` (default `/redoc`) and `openapi_url` (default `/openapi.json`). `docs_url=None` and `redoc_url=None` remove the two UIs but still serve the schema, which lists every path and model. `openapi_url=None` removes the schema route, and FastAPI then registers neither UI because both load it, so all three answer 404. The usual pattern reads `openapi_url` from a settings class so an environment variable decides, and an empty string also disables it. What this does not do is protect anything: every path operation still answers, and FastAPI's own docs liken relying on it to security through obscurity. If staff need docs in production, serve the schema and a Swagger UI page from your own routes behind a security dependency.

code

python · 15 lines
python
from fastapi import FastAPI
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    openapi_url: str = "/openapi.json"


settings = Settings()  # OPENAPI_URL= (empty) in production disables it
app = FastAPI(openapi_url=settings.openapi_url)


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

go deeper

for a junior

Remember the three arguments, docs_url, redoc_url and openapi_url, and that None turns each off.

for a middle

Explain why openapi_url=None also removes both UIs, how a settings class makes it environment-driven, and that the routes themselves keep answering.

for a senior

Show the defender's view: what the schema reveals, why obscurity protects nothing, and how to serve docs to staff behind a real security dependency.

for a principal

Set the team's policy on publishing the schema per environment, weighing partner and client-generation needs against what the description reveals, and keep it from replacing real authorization reviews.

## The three switches A `FastAPI` app registers up to three extra routes when it is created. Which ones exist is decided by three constructor arguments: | Argument | Default | Effect of `None` | |---|---|---| | `docs_url` | `"/docs"` | no Swagger UI page and no `/docs/oauth2-redirect` helper; the schema is still served | | `redoc_url` | `"/redoc"` | no ReDoc page; the schema is still served | | `openapi_url` | `"/openapi.json"` | no schema route, and neither UI is registered | The last row is the important one. FastAPI registers each UI only when both its own URL and `openapi_url` are set, because both pages work by fetching the schema in the browser. So `openapi_url=None` is a single switch that removes all three, and each of those paths then answers `404` with `{"detail": "Not Found"}`. ## Driving it from settings You rarely want to change code per environment. The pattern from FastAPI's docs reads the value from a Pydantic settings class: ```python class Settings(BaseSettings): openapi_url: str = "/openapi.json" settings = Settings() app = FastAPI(openapi_url=settings.openapi_url) ``` - Starting the process with `OPENAPI_URL=` (an empty string) disables the schema and both UIs, because FastAPI only registers them when the value is truthy. - The same image runs in every environment; only the environment variable differs. - `docs_url` and `redoc_url` can be read the same way if you want the schema without the HTML viewers. - If the policy is "no public schema", make the safe value the default: declare `openapi_url: str | None = None` in the settings class and set the URL explicitly in development. A variable that fails to load then hides the docs instead of publishing them. ## What hiding does not do FastAPI's documentation is explicit that hiding the docs "shouldn't be the way to protect your API". Concretely: - **Every path operation still answers.** The routes are registered whether or not the schema is. Anyone who learns a path, from a frontend bundle, a log line, an old copy of the schema or plain guessing, can call it. - **`docs_url=None` alone publishes the full description.** The JSON at `/openapi.json` still lists every path, parameter, model and security scheme; anyone can load it into a viewer of their own. - **`include_in_schema=False` hides one operation, not its route.** It is the right tool for internal endpoints such as a health check you do not want in client code, but it is not a guard. - **An unguessable docs URL is not authentication.** URLs leak through history, referrers, logs and screenshots. The protections that matter are the ordinary ones: request and response models that bound what is accepted and returned, authorization in dependencies on every sensitive operation, and the security classes for credentials. ## Keeping docs for staff only If people inside the team need the docs in production, keep the generated schema but put it behind the same kind of check as any other route: 1. Create the app with `openapi_url=None`, so the public routes disappear. 2. Add a route of your own, with `include_in_schema=False` and `dependencies=[Depends(...)]` on a security dependency, that returns `app.openapi()`. The method still builds the schema from the routes; `openapi_url` only decides whether FastAPI serves it. 3. Add a second guarded route that returns `get_swagger_ui_html(openapi_url=..., title=...)` from `fastapi.openapi.docs`, pointing at the route from step 2. By default that page loads Swagger UI's JavaScript and CSS from a public CDN; if the docs must work offline or under a strict content policy, serve those files yourself and pass their URLs to `get_swagger_ui_html`. ## Verifying the switch A configuration flag that nobody checks tends to drift, so test it like any other behaviour: 1. Build the app with production settings and request `/openapi.json`, `/docs` and `/redoc`; each should answer `404`. 2. In the same test, call one real path operation to prove the API itself still answers. 3. After a deploy, repeat the three requests against the live service, because the deployed environment, not the test, decides what the setting resolves to. ## Common mistakes - Hiding only the UIs and assuming the schema went with them. - Disabling the schema in the environment where the frontend's client is generated, breaking that build; a script that imports the app and writes `app.openapi()` to a file avoids depending on any running environment. - Treating a docs toggle as the security review for an API that has none.

  • In FastAPI, if docs_url=None and redoc_url=None are set but openapi_url is left alone, what can a visitor still fetch?
    The full schema at `/openapi.json`: every path, parameter, request and response model and security scheme. Only the two HTML viewers are gone, and anyone can load that JSON into a viewer of their own. If the goal is to stop publishing the API description, `openapi_url=None` is the switch that matters.
  • In FastAPI, how can a build step still get the schema for client generation when production serves none?
    Import the application in a short script and write `app.openapi()` to a file. The method builds the schema from the registered routes whatever `openapi_url` says, because that argument only controls whether FastAPI serves the schema over HTTP.
  • Why is a security dependency on custom FastAPI docs routes better than an unguessable docs path?
    A dependency is checked on every request, so only callers with valid credentials get the schema or the page. A secret path is checked by nothing: once it leaks through browser history, a referrer, a log or a screenshot, anyone can open it, and you cannot revoke it without changing the URL for everyone.

  • Setting docs_url=None stops FastAPI from serving the OpenAPI schema.
  • Hiding the docs in production secures the API's endpoints.
  • include_in_schema=False blocks requests to that path operation.
  • You must delete the docs routes from app.routes at startup to disable them.
  • An unguessable docs URL is as good as authentication.