Full answer
Why it matters: the OpenAPI document is the contract for docs, SDK generators and tests. Default operation IDs look like read_students_students__get, which produce ugly generated client methods.
Tools:
- Tags:
tags=["students"]groups endpoints. Describe tags once withFastAPI(openapi_tags=[{"name": "students", "description": "Student records"}]). summary,description, and the function docstring (rendered as Markdown) fill the docs.response_descriptiondocuments the success body.- Stable operation IDs: set
operation_id="list_students"per route, or a global generator:FastAPI(generate_unique_id_function=lambda r: f"{r.tags[0]}-{r.name}"). Generated clients then exposeStudentsService.listStudents()instead of a long auto name. - Examples:
Field(examples=["BCA-17"]),model_config = ConfigDict(json_schema_extra={"examples": [...]}), andBody(examples=[...]),Query(examples=[...])for parameters. They show up in/docsand in generated mock servers. - Extra responses:
responses={404: {"model": Problem}, 409: {"description": "Duplicate"}}. deprecated=Truestrikes the route in docs.include_in_schema=Falsehides internal routes (health, admin).openapi_extra={...}merges arbitrary keys into one operation (for examplex-codegenhints).- Global change: override the function, cache the result and add servers, security schemes or
info.x-logo:
def custom_openapi():
if app.openapi_schema: return app.openapi_schema
schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
schema["servers"] = [{"url": "https://api.schoolabe.example"}]
app.openapi_schema = schema
return schema
app.openapi = custom_openapi- Disable docs in production if the API is private:
FastAPI(docs_url=None, redoc_url=None, openapi_url=None).
Pin the schema in CI (snapshot tests) so accidental contract changes are caught.
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.routing import APIRoute
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict, Field
def unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}_{route.name}" if route.tags else route.name
app = FastAPI(
title="Campus API",
version="1.4.0",
openapi_tags=[{"name": "students", "description": "Student records"}],
generate_unique_id_function=unique_id,
)
class Student(BaseModel):
model_config = ConfigDict(json_schema_extra={"examples": [{"roll_no": "BCA-17", "name": "Asha Rao"}]})
roll_no: str = Field(examples=["BCA-17"], description="Unique roll number")
name: str
class Problem(BaseModel):
title: str
status: int
@app.get("/students", tags=["students"], summary="List students", responses={404: {"model": Problem}})
def list_students() -> list[Student]:
"""Return every student.\n\nSupports **Markdown** in the description."""
return []
@app.post("/students", tags=["students"], operation_id="enrol_student", status_code=201)
def create_student(student: Student) -> Student:
return student
@app.get("/old", tags=["students"], deprecated=True)
def old():
return {}
@app.get("/healthz", include_in_schema=False)
def healthz():
return {"ok": True}
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
schema = get_openapi(title=app.title, version=app.version, routes=app.routes, tags=app.openapi_tags)
schema["servers"] = [{"url": "https://api.schoolabe.example"}]
app.openapi_schema = schema
return schema
app.openapi = custom_openapi
schema = TestClient(app).get("/openapi.json").json()
print(sorted(schema["paths"]))
print({f"{m} {p}": op["operationId"] for p, item in schema["paths"].items() for m, op in item.items()})
print(schema["paths"]["/old"]["get"]["deprecated"], schema["servers"], schema["tags"][0]["name"])
print(schema["components"]["schemas"]["Student"]["examples"], sorted(schema["paths"]["/students"]["get"]["responses"]))
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): ['/old', '/students'] {'get /students': 'students_list_students', 'post /students': 'enrol_student', 'get /old': 'students_old'} True [{'url': 'https://api.schoolabe.example'}] students [{'name': 'Asha Rao', 'roll_no': 'BCA-17'}] ['200', '404']
Key points
- Tags, summaries and docstrings organise the docs
- Stable operation IDs give clean generated client method names
- Examples via Field, Body and json_schema_extra
- include_in_schema=False and deprecated=True control visibility
- Override app.openapi() for servers and security schemes
Common mistakes
- Shipping default operation IDs and getting unreadable generated clients
- Exposing internal routes in the public schema
- Documenting 404 and 409 responses with models but never returning those shapes
- Changing the schema accidentally without a snapshot test
- Leaving docs enabled on private production APIs
Follow-ups
- How do generated clients use operationId?
- How do you add a security scheme globally?
- How do you version the OpenAPI document?
Tips
- Show an operation ID strategy
- List 4 customisation parameters
- Mention snapshot tests