← Back to FastAPI, page 5

fastapi-0081 · Medium mid

How do you customise the OpenAPI schema in FastAPI: operation IDs, tag metadata, examples, hidden routes and a custom openapi() function?

FastAPI builds the schema from your code, and you shape it with parameters: tags and openapi_tags for grouping and descriptions, summary and description (or docstrings), operation_id or generate_unique_id_function for stable client method names, responses for extra status codes, examples through Field(examples=...) or json_schema_extra, deprecated=True, include_in_schema=False, and an overridden app.openapi() for global changes such as servers or security schemes.

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 with FastAPI(openapi_tags=[{"name": "students", "description": "Student records"}]).
  • summary, description, and the function docstring (rendered as Markdown) fill the docs. response_description documents 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 expose StudentsService.listStudents() instead of a long auto name.
  • Examples: Field(examples=["BCA-17"]), model_config = ConfigDict(json_schema_extra={"examples": [...]}), and Body(examples=[...]), Query(examples=[...]) for parameters. They show up in /docs and in generated mock servers.
  • Extra responses: responses={404: {"model": Problem}, 409: {"description": "Duplicate"}}.
  • deprecated=True strikes the route in docs. include_in_schema=False hides internal routes (health, admin).
  • openapi_extra={...} merges arbitrary keys into one operation (for example x-codegen hints).
  • Global change: override the function, cache the result and add servers, security schemes or info.x-logo:
python
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.

python
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