Chapter 11: Documenting APIs with OpenAPI
FastAPI generates OpenAPI from routes, type hints, Pydantic models, status codes, tags, summaries, descriptions, and security dependencies.
@router.post(
"",
response_model=RecipeRead,
status_code=201,
summary="Create a recipe",
responses={
409: {"description": "A recipe with this title already exists"},
},
)
def create_recipe(command: RecipeCreate, db: DbSession) -> RecipeRead:
...
Good API documentation is not accidental:
- Use descriptive route tags.
- Use dedicated response models.
- Document non-2xx responses.
- Keep examples realistic.
- Do not expose internal fields.
- Prefer generated OpenAPI, then customize when needed.
OpenAPI is also a contract. If client teams depend on your schema, test it or snapshot it.