← Back to FastAPI, page 1

fastapi-0007 · Easy fresher

How does FastAPI generate API documentation, and how can you customise or turn off /docs?

FastAPI builds an OpenAPI schema from routes, parameters, Pydantic models, response models and metadata, served at /openapi.json. Swagger UI at /docs and ReDoc at /redoc render it. You customise it with app metadata (title, version, description), route summary, description, tags and examples, and you can move or disable the docs with docs_url, redoc_url and openapi_url, for example in production.

Full answer

OpenAPI is a standard, machine-readable description of an HTTP API: paths, methods, parameters, request and response schemas, and security schemes. FastAPI creates it automatically on first request to /openapi.json by walking every route.

Where the information comes from:

  • Path, query, header and cookie parameters, with types and constraints from Path(), Query() and so on.
  • Request body and response schemas from Pydantic models (JSON Schema).
  • Status codes from status_code and responses=.
  • Security from dependencies such as OAuth2PasswordBearer (adds the Authorize button).
  • Docstrings become descriptions; summary=, description=, tags= and deprecated=True on decorators.
  • Field(examples=[...]) or model_config = {"json_schema_extra": {"examples": [...]}} add examples.

Two UIs render the schema: Swagger UI at /docs (you can try requests) and ReDoc at /redoc (reading-friendly).

Customising:

python
app = FastAPI(title="Library API", version="2.3.0",
              openapi_tags=[{"name": "books", "description": "Catalogue"}],
              docs_url="/internal/docs", redoc_url=None)
  • openapi_url=None disables the schema and both UIs, a common choice for public production APIs that should not advertise every endpoint. Hiding docs is not security; endpoints still need authentication.
  • include_in_schema=False hides a single route.

The schema is useful beyond docs: generate typed clients (TypeScript, Kotlin) with tools such as openapi-generator, run contract tests, and diff the schema in CI to catch breaking changes before release.

python
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field

app = FastAPI(title="Library API", version="2.3.0", docs_url="/internal/docs", redoc_url=None,
              openapi_tags=[{"name": "books", "description": "Catalogue operations"}])


class Book(BaseModel):
    title: str = Field(examples=["Malgudi Days"])
    copies: int = Field(ge=0, examples=[3])


@app.post("/books", tags=["books"], summary="Add a book", status_code=201)
def add_book(book: Book) -> Book:
    """Adds a book to the catalogue. Copies must be zero or more."""
    return book


@app.get("/healthz", include_in_schema=False)
def health():
    return {"ok": True}


c = TestClient(app)
schema = c.get("/openapi.json").json()
op = schema["paths"]["/books"]["post"]
print(schema["info"], list(schema["paths"]))
print(op["summary"], "|", op["description"], "|", op["tags"])
print(schema["components"]["schemas"]["Book"]["properties"]["copies"])
print(c.get("/internal/docs").status_code, c.get("/redoc").status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'title': 'Library API', 'version': '2.3.0'} ['/books'] Add a book | Adds a book to the catalogue. Copies must be zero or more. | ['books'] {'type': 'integer', 'minimum': 0.0, 'title': 'Copies', 'examples': [3]} 200 404

Key points

  • OpenAPI schema built from routes, types and models
  • Swagger UI at /docs, ReDoc at /redoc
  • Metadata via summary, description, tags, examples
  • docs_url, redoc_url, openapi_url move or disable docs
  • Use the schema for client generation and breaking-change checks

Common mistakes

  • Treating hidden docs as a security measure
  • Leaving models without descriptions or examples, so docs are hard to use
  • Breaking the schema with an unnoticed field rename
  • Hand-writing client code instead of generating it from the schema

Follow-ups

  • How would you detect breaking API changes in CI?
  • How do you add an Authorize button for JWT to /docs?
  • How would you version the documentation for v1 and v2?

Tips

  • List where each part of the schema comes from
  • Mention disabling docs in production and why that is not security
  • Show you know the schema is useful for codegen and contract tests