Difficulty: Beginner
How does FastAPI generate API documentation automatically? How can you customize it?
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`
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}
OpenAPI, Swagger UI, ReDoc, schema generation