OpenAPI and automatic documentation

Difficulty: Beginner

Question

How does FastAPI generate API documentation automatically? How can you customize it?

Answer

FastAPI generates an OpenAPI schema from your route definitions, Pydantic models, and type hints. It serves:

  • Swagger UI at /docs - interactive, allows making real API calls
  • ReDoc at /redoc - clean, readable documentation
  • Raw JSON schema at /openapi.json

Customization options:

  • title, description, version in FastAPI() constructor
  • tags parameter on routes for grouping
  • summary and description on routes for documentation text
  • response_model adds response schemas
  • openapi_tags for tag-level metadata
  • Disable docs with docs_url=None, redoc_url=None

Code examples

Customizing OpenAPI docs

from fastapi import FastAPI

app = FastAPI(
    title="My API",
    description="This is a demo API with full OpenAPI docs.",
    version="1.0.0",
    docs_url="/swagger",       # change Swagger URL
    redoc_url="/docs",         # change ReDoc URL
    openapi_tags=[
        {"name": "items", "description": "Operations with items"},
        {"name": "users", "description": "User management"},
    ]
)

@app.get(
    "/items/{id}",
    tags=["items"],
    summary="Get an item by ID",
    description="Retrieve a single item. Returns 404 if not found.",
    response_description="The requested item"
)
def get_item(id: int):
    return {"id": id}

Key points

  • Docstrings on path operation functions are used as the OpenAPI description
  • Use `include_in_schema=False` to hide an endpoint from docs
  • JWT auth shows up as the 'Authorize' button in Swagger UI when using OAuth2PasswordBearer

Common follow-up questions

  • How do you add custom headers or authentication to the Swagger UI?
  • How do you generate a client SDK from FastAPI's OpenAPI schema?

Interview tips

  • Auto-documentation is a major selling point of FastAPI - be enthusiastic about it

Concepts covered

OpenAPI, Swagger UI, ReDoc, schema generation

More FastAPI Interview questions