← Back to FastAPI, page 5

fastapi-0082 · Medium mid

How do you version a FastAPI API with routers and prefixes, and how do you deprecate old versions with Deprecation and Sunset headers?

The most common scheme is a URL prefix per major version (/v1, /v2), each in its own APIRouter, sharing services and with version-specific request and response schemas. Alternatives are a header or media type. Deprecate old versions by marking routes deprecated=True (visible in docs) and sending Deprecation and Sunset headers (and a Link to migration docs) so clients can detect retirement dates. Only create a new version for breaking changes.

Full answer

Structure:

app/ api/ v1/routes.py # router_v1 = APIRouter(prefix="/v1", tags=["v1"]) v2/routes.py # router_v2 = APIRouter(prefix="/v2", tags=["v2"]) services/ # business logic shared by both schemas/v1.py, schemas/v2.py

Each router maps requests to the same service layer, converting to and from version-specific schemas. This keeps old behaviour stable without copying business logic.

When to bump a version: removing or renaming fields, changing types or meanings, tightening validation, changing error formats or status codes. Adding optional fields or new endpoints is backward compatible (clients must ignore unknown fields: document that).

Schemes:

  • URL path (/v2/students): visible, cacheable, easy to route at a gateway, simple to test with curl. Most common.
  • Header (X-API-Version: 2) or media type (Accept: application/vnd.schoolabe.v2+json): cleaner URLs, but harder for caches and casual testing.
  • Date-based versions (Stripe style) pin each client to the behaviour at its integration date: powerful but needs infrastructure.

Deprecation process:

  1. Announce the plan with dates; mark routes deprecated=True so /docs strikes them through.
  2. Send headers on every response of the old version: Deprecation: true (or a date), Sunset: Wed, 01 Jul 2027 00:00:00 GMT (RFC 8594) and Link: <https://docs...>; rel="deprecation". A router-level dependency or middleware can add them.
  3. Track usage per version and per client; contact heavy users.
  4. After the sunset date return 410 Gone with a problem document pointing to the new version, then delete.

Keep live versions to two or three, and test all of them in CI.

python
from fastapi import APIRouter, Depends, FastAPI, Response
from fastapi.testclient import TestClient
from pydantic import BaseModel

SERVICE_DB = [{"first": "Asha", "last": "Rao", "roll_no": "BCA-17"}]       # shared business data


def deprecation_headers(response: Response):
    response.headers["Deprecation"] = "true"
    response.headers["Sunset"] = "Thu, 01 Jul 2027 00:00:00 GMT"
    response.headers["Link"] = '<https://docs.schoolabe.example/migrate-v2>; rel="deprecation"'


class StudentV1(BaseModel):
    name: str
    roll_no: str


class StudentV2(BaseModel):
    first_name: str
    last_name: str
    roll_no: str


v1 = APIRouter(prefix="/v1", tags=["v1"], dependencies=[Depends(deprecation_headers)], deprecated=True)
v2 = APIRouter(prefix="/v2", tags=["v2"])


@v1.get("/students", response_model=list[StudentV1])
def students_v1():
    return [{"name": f"{s['first']} {s['last']}", "roll_no": s["roll_no"]} for s in SERVICE_DB]


@v2.get("/students", response_model=list[StudentV2])
def students_v2():
    return [{"first_name": s["first"], "last_name": s["last"], "roll_no": s["roll_no"]} for s in SERVICE_DB]


app = FastAPI()
app.include_router(v1)
app.include_router(v2)

c = TestClient(app)
r1, r2 = c.get("/v1/students"), c.get("/v2/students")
print(r1.json(), r1.headers.get("deprecation"), r1.headers.get("sunset"))
print(r2.json(), r2.headers.get("deprecation"))
schema = c.get("/openapi.json").json()["paths"]
print({p: item["get"].get("deprecated", False) for p, item in schema.items()})

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): [{'name': 'Asha Rao', 'roll_no': 'BCA-17'}] true Thu, 01 Jul 2027 00:00:00 GMT [{'first_name': 'Asha', 'last_name': 'Rao', 'roll_no': 'BCA-17'}] None {'/v1/students': True, '/v2/students': False}

Key points

  • Router per major version, shared service layer
  • Version only for breaking changes
  • deprecated=True plus Deprecation and Sunset headers
  • Track version usage before retiring
  • After sunset return 410 Gone with migration info

Common mistakes

  • Creating a new version for every small change
  • Copying business logic into each version
  • Removing a version without notice or usage data
  • Not telling clients to ignore unknown fields
  • Leaving old versions untested

Follow-ups

  • How would you route versions at an API gateway?
  • How does date-based versioning work?
  • How do you handle breaking changes in error formats?

Tips

  • Explain router per version
  • Name the deprecation headers
  • State when to bump a version