Lesson 25 of 59API design in depth
Evolving an API Without Breaking Clients
Run v1 and v2 side by side in FastAPI, deprecate in code with real headers, add ETags for caching and safe concurrent edits, and keep wire formats stable.
You can now build an API with a database, caching and background work behind it. This unit is about designing that API so clients can rely on it for years. Your orders API has a web app, two mobile apps and forty partner integrations. Product wants total (a float in euros) replaced with total_cents and a currency field, and the support team keeps losing edits when two agents update the same order. You cannot ship a new mobile build for every partner, and you cannot make forty companies deploy on your schedule. This lesson is the FastAPI side of the job: how the code is laid out so two versions can live together cheaply, how deprecation shows up in responses, and how ETags fix lost edits. The theory (what counts as breaking, which versioning strategy to pick, expand and contract) is in Designing APIs That Last in the Design & Architecture course. Here you build it.
How a Pydantic edit becomes a breaking change
In FastAPI, the response model is the contract. Every edit to a schema class changes what clients receive, and many of those edits look harmless in a code review.
| Code change | What a client sees |
|---|---|
Rename the attribute total to amount | The JSON key changes. Old clients read nothing |
total: float becomes total: Decimal | Pydantic v2 serialises Decimal as a string, so 19.99 becomes "19.99" |
status: Literal["paid", "open"] gains "refunded" | Generated clients with a strict enum fail to parse the response |
Add extra="forbid" to an existing request model | Requests that sent harmless extra fields now get 422 |
limit: int = 50 becomes limit: int = 20 | Same request, fewer results, no error anywhere |
Turn on alias_generator=to_camel | Every key changes case in one commit |
id: int becomes id: str | Typed clients fail. JavaScript clients compare 42 === "42" and get false |
response_model_exclude_none=True on a route | Keys that used to be null are now missing, which crashes code that checks "key" in body |
Two habits catch most of these before they ship. First, keep the OpenAPI document in the repository: a test calls app.openapi(), writes it to openapi.json, and fails if the file changed without being committed. The diff then shows up in the pull request, where a reviewer can see that a field changed type. Second, run a breaking-change checker such as oasdiff against main in CI, as described in Designing APIs That Last.
import json
from pathlib import Path
from app.main import app
SNAPSHOT = Path(__file__).parent / "openapi.json"
def test_openapi_matches_snapshot():
current = json.dumps(app.openapi(), indent=2, sort_keys=True)
if not SNAPSHOT.exists():
SNAPSHOT.write_text(current)
assert current == SNAPSHOT.read_text(), "API contract changed: review, then update openapi.json"price: float to price: Decimal in a response model to fix rounding. Nothing else changes. What do existing clients receive?One service, thin routers per version
The expensive way to version is to copy the whole app into a v2 folder. Within months the two copies drift: a bug fixed in v2 is still live in v1. The cheap way keeps one service layer and one database model, and gives each version only what actually differs: its schemas and a thin router that maps between them.
- app/
- main.pybuilds the app, includes both routers
- services/
- orders.pybusiness logic, version-free
- models.pySQLAlchemy models, version-free
- api/
- v1/
- routes.pythin: call service, map to v1 schema
- schemas.pyOrderV1: id, total (float euros)
- v2/
- routes.pythin: call service, map to v2 schema
- schemas.pyOrderV2: id, total_cents, currency
- tests/
- test_v1_contract.pyv1 must keep passing until sunset
- test_v2_contract.py
from typing import Annotated
from fastapi import APIRouter, Depends
from app.api.deprecation import mark_deprecated
from app.api.v1.schemas import OrderV1
from app.services.orders import OrderService, get_order_service
router = APIRouter(prefix="/v1", tags=["v1"], deprecated=True, dependencies=[Depends(mark_deprecated)])
@router.get("/orders/{order_id}")
def read_order(order_id: str, svc: Annotated[OrderService, Depends(get_order_service)]) -> OrderV1:
order = svc.get(order_id)
return OrderV1(id=order.id, total=order.total_cents / 100)from fastapi import FastAPI
from app.api.v1.routes import router as v1_router
from app.api.v2.routes import router as v2_router
app = FastAPI(title="Orders API")
app.include_router(v1_router)
app.include_router(v2_router)The v1 route is now an adapter: it calls the same service as v2 and translates the result into the old shape. New features land in the service and v2. v1 only changes for security fixes. deprecated=True on the router marks every v1 operation as deprecated in the OpenAPI document, so Swagger UI strikes them through and generated clients emit warnings.
New clients use v2. The schema matches the database closely: total_cents and currency.
Separate docs with mounted sub-apps
include_router puts both versions in one OpenAPI document. If partners should see only v2, give each version its own FastAPI instance and mount it. Each sub-app serves its own /v2/docs and /v2/openapi.json, with its own title and version number.
v2_app = FastAPI(title="Orders API", version="2.0.0")
v2_app.include_router(v2_router) # router without its own /v2 prefix
app = FastAPI(docs_url=None, openapi_url=None) # the root serves no docs
app.mount("/v2", v2_app)Mounting has a cost people find out in production: exception handlers registered on the parent app do not apply inside a mounted app. A domain error that the parent turns into a tidy 404 becomes a plain-text 500 inside /v2. Middleware added to the parent does still wrap the mounted app, because it sits outside it. Register handlers on every sub-app (a small install_handlers(app) function helps), and add a test per version that a domain error produces the right status.
Test every live version
Every version you still serve needs its own contract tests, and they must keep passing until the sunset date. The v1 tests are the most valuable tests in the repository, because nobody on the team uses v1 any more, so nobody would notice it breaking. Write them against literal JSON, not against your schema classes: assert that GET /v1/orders/ord_42 returns {"id": "ord_42", "total": 19.99} exactly. A test that builds its expected value from OrderV1 still passes after someone renames a field in OrderV1, because both sides change together. When a service change forces you to edit a v1 test, stop: that is a breaking change for v1 clients, and it needs the same process as any other.
Header and date versions in FastAPI
A URL version is easiest to route. If you want Stripe-style dated versions instead, the version becomes a dependency: read a header, fall back to the version the account was pinned to when it signed up, and validate it against a known list.
from typing import Annotated
from fastapi import Depends, Header, HTTPException
KNOWN_VERSIONS = ("2026-03-01", "2026-08-15")
LATEST = KNOWN_VERSIONS[-1]
def api_version(
account: Annotated[Account, Depends(current_account)],
acme_version: Annotated[str | None, Header()] = None, # reads the Acme-Version header
) -> str:
version = acme_version or account.pinned_version or LATEST
if version not in KNOWN_VERSIONS:
raise HTTPException(400, f"Unknown Acme-Version {version!r}")
return versionRoutes always build the latest shape, then a response step walks back through the version changes newer than the pin, exactly like the transformation layer in Designing APIs That Last. Two practical rules: store the pin on the account, not only in the header, so a client that forgets the header does not jump to the newest behaviour; and log the resolved version on every request, which is what lets you see who still depends on an old one.
Deprecation in code
Headers only help if they are on every response from a deprecated endpoint. The dependency approach from the router above adds them through the injected Response:
from fastapi import Request, Response
V1_DEPRECATED_AT = "@1788220800" # 2026-09-01T00:00:00Z as a Unix timestamp (RFC 9745)
V1_SUNSET = "Fri, 01 Jan 2027 00:00:00 GMT" # HTTP date (RFC 8594)
MIGRATION_GUIDE = '<https://api.example.com/docs/v1-to-v2>; rel="deprecation"'
def mark_deprecated(request: Request, response: Response) -> None:
response.headers["Deprecation"] = V1_DEPRECATED_AT
response.headers["Sunset"] = V1_SUNSET
response.headers["Link"] = MIGRATION_GUIDE
logger.info("deprecated_call", extra={"path": request.url.path, "client_id": request.state.client_id})There is a gap. When the route raises HTTPException or a domain error, the exception handler builds a new response, and headers set on the injected Response are lost. A client whose integration is mostly 404s never sees the warning. If that matters, move the headers into a small middleware that checks request.url.path.startswith("/v1/") and sets them on whatever response comes back.
The log line is the part that retires the version. Aggregate deprecated_call by client_id every week, and you get the list of partners to email. When the sunset date arrives, a brownout (v1 returns 410 Gone for an announced hour) reaches the ones who did not read the email, while there is still time to fix things.
Order the steps for moving partners from total (v1) to total_cents (v2) in this codebase.
- Tap the steps below in the right order.
Conditional requests: ETags, 304 and 412
An ETag is a response header that names the exact state of a resource. Clients send it back in one of two headers, and each solves a different problem:
If-None-Matchon aGET: "only send the body if it changed". A match returns304 Not Modifiedwith no body, which saves bandwidth for clients that poll.If-Matchon aPUTorPATCH: "only apply my change if it is still the version I read". A mismatch returns412 Precondition Failed, so the second support agent does not silently overwrite the first. This is optimistic concurrency without database locks.
The cheapest ETag comes from a version integer column that every write increments. One HTTP detail decides how you format it. RFC 9110 says If-None-Match uses weak comparison, but If-Match uses strong comparison, and a weak tag (W/"7") never matches strongly. If you generate weak tags, If-Match can never succeed. Use a strong tag, and because v1 and v2 serialise the same row differently, put the representation in it: "v2-7".
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Response, status
def etag_for(order: Order) -> str:
return f'"v2-{order.version}"'
@router.get("/orders/{order_id}")
def read_order(
order: Annotated[Order, Depends(load_order)],
response: Response,
if_none_match: Annotated[str | None, Header()] = None,
) -> OrderV2:
tag = etag_for(order)
if if_none_match == tag:
return Response(status_code=status.HTTP_304_NOT_MODIFIED, headers={"ETag": tag})
response.headers["ETag"] = tag
return OrderV2.model_validate(order, from_attributes=True)
@router.patch("/orders/{order_id}")
def update_order(
body: OrderPatch,
order: Annotated[Order, Depends(load_order)],
svc: Annotated[OrderService, Depends(get_order_service)],
response: Response,
if_match: Annotated[str | None, Header()] = None,
) -> OrderV2:
if if_match is None:
raise HTTPException(status.HTTP_428_PRECONDITION_REQUIRED, "Send If-Match with the ETag you read")
if if_match != etag_for(order):
raise HTTPException(status.HTTP_412_PRECONDITION_FAILED, "The order changed since you read it")
updated = svc.update(order, expected_version=order.version, **body.model_dump(exclude_unset=True))
response.headers["ETag"] = etag_for(updated)
return OrderV2.model_validate(updated, from_attributes=True)The header check alone has a race: two requests can both pass it before either writes. Close it in the database by making the update conditional, UPDATE orders SET ..., version = version + 1 WHERE id = :id AND version = :expected, and treating zero affected rows as a 412. SQLAlchemy can do this for you with version_id_col in the mapper, which raises StaleDataError on a mismatch. A full If-None-Match also accepts a list of tags and *; parse it if clients will send more than one.
Run the whole exchange. Two agents read, one saves, the other is stopped:
Press Run (⌘ Enter) to see what happens.Using the code above after it has run, agent B reloads and retries with the tag from the reload. What does this print?
_, fresh, _ = get("ord_42")
print(patch("ord_42", {"note": "call back"}, if_match=fresh)[:2])Wire formats you set once
Some choices are cheap on day one and a breaking change on day two hundred. Pydantic gives you a switch for each.
Field case. Python wants snake_case; many JavaScript teams want camelCase. Pick once. For camelCase, set it on a shared base class so every schema agrees:
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel
class ApiModel(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, validate_by_name=True, validate_by_alias=True)FastAPI serialises response models by alias, so clients see createdAt while your code uses created_at. validate_by_name=True (Pydantic 2.11 and later; older code uses populate_by_name=True) lets your own code and tests construct models with Python names too.
Time. Use AwareDatetime in schemas, so a timestamp without a timezone is rejected at the boundary instead of being guessed. Store UTC and serialise ISO 8601 with Z.
Money. Integer minor units (total_cents: int plus currency: str) or a Decimal, which Pydantic sends as a string. Never a float.
Ids. Strings, ideally prefixed (ord_42), even if the database key is an integer. Prefixes make logs readable and let you change the underlying key type later.
Match each requirement to the FastAPI or Pydantic tool that implements it.
Long-running operations: 202 and a status resource
An export of a year of orders takes four minutes. A request that waits that long will be cut by a load balancer timeout. Return 202 Accepted at once with a Location header pointing to an operation the client can poll, and do the work in a queue (Task Queues with Celery covers the worker side).
@router.post("/exports", status_code=status.HTTP_202_ACCEPTED)
def start_export(body: ExportRequest, response: Response, svc: Annotated[ExportService, Depends(get_export_service)]) -> Operation:
op = svc.enqueue(body) # writes an operations row, sends a task
response.headers["Location"] = f"/v2/operations/{op.id}"
response.headers["Retry-After"] = "5"
return op # {"id": "op_9", "status": "running", "result_url": null}
@router.get("/operations/{op_id}")
def read_operation(op_id: str, svc: Annotated[ExportService, Depends(get_export_service)]) -> Operation:
return svc.get_operation(op_id) # later: {"status": "done", "result_url": "..."}The operation is a normal resource with its own schema, so it versions like everything else, and the work can move from a thread to a queue to a separate service without the client noticing.
FastAPI() instance and mounted it at /v2. The parent app has @app.exception_handler(NotFound). A v2 route raises NotFound. What does the client get?- adapter route
- An old-version route that calls the shared service and maps the result into the old schema, so only the mapping is version-specific.
- mounted sub-app
- A separate FastAPI instance attached with
app.mount, with its own docs and its own exception handlers. - ETag
- A response header naming the exact state of a resource, sent back in
If-None-MatchorIf-Match. - 412 Precondition Failed
- The
If-Matchtag no longer matches, so the write is refused instead of overwriting newer data. - 428 Precondition Required
- The server requires a conditional request and the client sent no
If-Match. - Sunset header
- RFC 8594 header giving the date after which a resource or version will stop working.
- brownout
- A short, announced window where a deprecated version is switched off, so late clients notice before the real removal.