Lesson 29 of 59API design in depth
OpenAPI, Generated Clients and Contract-First APIs
Make FastAPI's OpenAPI schema good enough to generate typed clients, catch breaking changes in CI, and decide between code-first and contract-first.
The frontend team hand-wrote TypeScript types for your API six months ago. Last sprint you renamed total to total_minor and nothing failed: your tests passed, their build passed, and the checkout page showed NaN in production for an hour. The fix is not more care. It is making the API description a real artefact: generated, committed, reviewed, diffed in CI, and turned into typed clients so the compiler catches drift for you. FastAPI already writes an OpenAPI document for you. This lesson is about making that document good enough to build on, wiring it into the pipeline, and knowing when to write the contract first instead.
What FastAPI generates
Every FastAPI app builds an OpenAPI 3.1 document from your routes, parameters and Pydantic models. Since FastAPI 0.99 it uses 3.1, which means the schemas inside are JSON Schema 2020-12, the same dialect Pydantic v2 produces. Three URLs come with it by default:
/openapi.json: the document itself. This is the contract./docs: Swagger UI, an interactive page that reads the document./redoc: ReDoc, a read-only reference page from the same document.
The document is built lazily the first time app.openapi() is called and then cached on app.openapi_schema. That matters in two places: you can export it without starting a server, and if you customise it you must do so before the first call.
import json
import sys
from app.main import app
json.dump(app.openapi(), sys.stdout, indent=2, sort_keys=True)
sys.stdout.write("\n")uv run python scripts/export_openapi.py > openapi.jsonsort_keys=True and a trailing newline make the file stable, so a diff shows only real changes. Commit openapi.json to the repository. From now on, every pull request that changes the API also changes this file, and reviewers see the contract change next to the code change.
Making the schema worth generating from
A generated client is only as good as the document. The defaults are fine for /docs and poor for codegen. These are the fixes that matter.
Operation ids. Each operation gets an operationId, and client generators turn it into a method name. FastAPI's default is the function name plus path plus method, such as create_order_orders_post, which becomes createOrderOrdersPost() in TypeScript. Set a function that builds cleaner ids:
from fastapi import FastAPI
from fastapi.routing import APIRoute
def operation_id(route: APIRoute) -> str:
# "orders-create_order" -> client method ordersCreateOrder()
return f"{route.tags[0]}-{route.name}" if route.tags else route.name
app = FastAPI(
title="Shop API",
version="2.3.0",
generate_unique_id_function=operation_id,
)The if route.tags guard is not decoration. The function runs for every route at import time, including untagged ones with include_in_schema=False such as a health check, and the version in the FastAPI docs that indexes route.tags[0] crashes the app on the first untagged route. Operation ids must be unique and are part of your contract: renaming a function changes a generated method name, which breaks client code.
Tags, summary and description. Put tags=["orders"] on each APIRouter. FastAPI takes the summary from summary= and the description from the docstring, and Markdown in the docstring renders in the docs.
Response types. A return annotation (-> OrderOut) or response_model=OrderOut produces the success schema, and FastAPI also filters the response through it. Without one, the success response is an untyped {} and generated clients get unknown. Use response_model= on the decorator when the function may return a Response object directly.
Errors. FastAPI documents the 422 validation error automatically and nothing else. Document the errors your route really returns, with a model, so clients get typed error bodies:
@router.post(
"",
status_code=201,
summary="Place an order",
responses={
404: {"model": ProblemDetail, "description": "Unknown SKU"},
409: {"model": ProblemDetail, "description": "Request still in progress"},
},
)
async def create_order(
body: Annotated[
OrderIn,
Body(openapi_examples={
"single": {"summary": "One kettle", "value": {"sku": "KET-001", "qty": 1}},
}),
],
) -> OrderOut:
"""Place an order for one SKU.
Send an `Idempotency-Key` header so retries are safe.
"""ProblemDetail is the RFC 9457 model from Error Responses Clients Can Rely On.
Examples. Field(examples=["KET-001"]) puts examples into the JSON Schema of a model, and openapi_examples= on Body(), Query() and friends adds named examples that Swagger UI shows in a dropdown. Mock servers and contract-testing tools use these, so realistic examples pay off twice.
Hiding things. include_in_schema=False removes a route (health checks, internal admin). It still serves requests, so it is not access control.
create_order to place_order without changing the path. You use FastAPI's default operation ids. Who is affected?Generated clients
Once the schema is good, stop writing client types by hand.
For a TypeScript frontend, the lightest option is openapi-typescript, which turns the schema into types, plus openapi-fetch, a tiny typed wrapper around fetch:
npx openapi-typescript ./openapi.json -o ./src/api/schema.d.tsimport createClient from "openapi-fetch";
import type { paths } from "./schema";
export const api = createClient<paths>({ baseUrl: "https://api.example.com" });
const { data, error } = await api.POST("/orders", {
body: { sku: "KET-001", qty: 1 },
headers: { "Idempotency-Key": crypto.randomUUID() },
});
// data is OrderOut | undefined; error is the typed 404/409/422 bodyPaths, bodies, query parameters and responses are all checked. Rename a field in Python, regenerate, and every place that reads the old name stops compiling. Hey API (@hey-api/openapi-ts) is the heavier alternative: it generates an SDK with one function per operation, and has plugins for TanStack Query and Zod. Pick by taste; both read the same file. For Python consumers, such as another service, openapi-python-client generate --path openapi.json produces a typed package built on httpx.
Where to generate: in a monorepo, generate inside the frontend build from the committed openapi.json. Across repositories, publish the schema as a build artefact (or a versioned package of generated types) on each release. Either way, CI regenerates and fails if the result differs from what is committed, so nobody ships a stale client.
CI exports the schema from the code and fails if it differs from the committed openapi.json. The file in git is always the truth.
Catching breaking changes in CI
Designing APIs That Last explains what counts as breaking and how to version. Here is the mechanism. oasdiff compares two OpenAPI documents and classifies every difference as error (breaking), warning or info. It can read a file at a git revision directly:
oasdiff breaking --fail-on ERR origin/main:openapi.json openapi.jsonThe idea underneath is that direction matters. The same edit to a schema can be safe in a request and breaking in a response, and the reverse. Run this toy checker to see it:
Press Run (⌘ Enter) to see what happens.A new required field breaks callers who send the body, but is a bonus for callers who read it. A new enum value is harmless as input but can break a client with an exhaustive switch when it appears in a response. The toy ignores one subtle case: removing an optional input field looks safe, but if your model uses extra="forbid", clients still sending it now get 422. Real tools know about cases like that; your job is to read their output and decide.
When a break is intentional, the check should not be silenced in a hurry. It should force a conversation: is this a new version, or can it be done with expand and contract instead?
What does this print?
old = {"status": ["pending", "paid"]}
new = {"status": ["pending", "paid", "refunded"]}
added = set(new["status"]) - set(old["status"])
breaks_request = len(set(old["status"]) - set(new["status"])) > 0
breaks_response = len(added) > 0
print(breaks_request, breaks_response)Contract-first versus code-first
Everything so far is code-first: you write FastAPI, and the schema falls out. The alternative is contract-first (also called design-first or spec-first): you write the OpenAPI YAML by hand, review it as a design, and then implement it.
Contract-first wins when:
- Several teams need to start at once. The frontend codes against a mock server generated from the YAML, such as Prism (
prism mock openapi.yaml), while the backend is still being written. - The API is public or partner-facing, and the design deserves review by people who do not read Python.
- One contract has several implementations or languages.
Code-first wins when one team owns both sides, the API changes often, and the Python models are the clearest description anyway. Most FastAPI teams are code-first, and that is fine if the generated schema is committed and diffed, because then you get the review step anyway.
In contract-first with FastAPI, generate the Pydantic models from the YAML so they cannot drift:
uvx --from datamodel-code-generator datamodel-codegen --input openapi.yaml --input-file-type openapi --output-model-type pydantic_v2.BaseModel --output app/schemas/generated.pyThen write the routes by hand using those models. The routes can still drift (a wrong path, a missing error response), so close the loop in CI: export the schema from the running code and run oasdiff breaking openapi.yaml exported.json. If the implementation breaks the designed contract, the build fails. Do not hand-edit generated files; regenerate them.
Testing the app against its own schema
The contract has two sides. Generated clients check that callers match the schema. You also need to check that the server matches it. You met Schemathesis in Testing with Real Databases, where it found that lax Pydantic accepted false as an integer. Two additions are worth knowing for CI.
First, its checks go beyond "no 500s": they include response schema conformance, undocumented status codes, invalid data the API wrongly accepts, and some auth checks such as ignored_auth. Second, it has a stateful phase that chains calls, such as creating an order and then fetching it by the returned id, which finds bugs single calls cannot. It uses OpenAPI links and its own inference to know which output feeds which input. Run it against the committed file plus a test server:
schemathesis run ./openapi.json --url http://localhost:8000 --checks allExpect the first run to fail in instructive ways, mostly undocumented error codes. Each fix makes your schema more honest, which makes every generated client better.
Docs in production
Interactive docs are an attack surface: they list every route and parameter. For a public API, publishing them is the point. For an internal or private one, turn them off in production or put them behind auth:
docs_enabled = settings.environment != "production"
app = FastAPI(
docs_url="/docs" if docs_enabled else None,
redoc_url="/redoc" if docs_enabled else None,
openapi_url="/openapi.json" if docs_enabled else None,
)Setting openapi_url=None disables the docs pages too, because they read it. You do not lose anything: CI exports the schema straight from app.openapi() without a server. Remember that hiding docs is not security. Every route still needs authorization, and include_in_schema=False only hides a route from the document.
Match each tool to the job it does in the pipeline.
Order the steps of a contract-first change to an endpoint.
- Tap the steps below in the right order.
- OpenAPI
- A standard, language-neutral description of an HTTP API: paths, parameters, bodies, responses and security. FastAPI generates version 3.1.
- operationId
- A unique name for one operation in the schema. Client generators use it as the method name, so changing it is a breaking change for generated clients.
- code-first
- Writing the implementation and generating the API description from it, as FastAPI does.
- contract-first
- Writing and reviewing the API description before the code, then generating models and mocks from it.
- generated client
- Types or SDK code produced from the schema, so the compiler catches mismatches between caller and API.
- mock server
- A fake API served from the schema and its examples, letting consumers build before the real backend exists.
- schema drift
- When the implementation, the published schema and the clients stop agreeing, usually silently.