Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 50 ยท Structuring larger apps

API versioning

Version a FastAPI API with URL prefixes and routers, a custom version header, or mounted sub-apps, mark old endpoints deprecated, and announce sunset dates to clients.

Sooner or later you need to change an endpoint in a way that breaks existing clients: rename a field, remove one, change a type. Mobile apps you cannot update, partners with their own release cycle and old scripts keep calling the old shape. API versioning lets the old and new shapes exist at the same time, so clients migrate when they are ready.

This lesson compares the three common strategies, shows the router-based one in full (the one most FastAPI projects pick), and covers how to retire an old version politely.

First: do you need a new version?

Many changes are backward compatible and need no version at all:

  • adding a new endpoint,
  • adding an optional request field or a new response field (well-written clients ignore fields they do not know),
  • adding an optional query parameter.

These are breaking changes:

  • removing or renaming a field, endpoint or parameter,
  • changing a field's type or meaning (price from cents to dollars),
  • making an optional field required, or tightening validation,
  • changing status codes or error formats that clients rely on.

If you can make a change additively, do that. A version bump is a promise to keep two code paths alive, which has a real cost.

Three ways to say "version 2"

In the URL /v1/users and /v2/users
In a header X-API-Version: 2
Separate apps Mount v1 and v2 apart.
1 / 2

Strategy 1: the version in the URL

Put the version in the path: /v1/users, /v2/users. It is explicit, easy to see in logs, trivial to try in a browser, and caches and gateways can route on it. In FastAPI you give each version its own APIRouter and attach both to the app with a prefix:

Python
app.include_router(v1_router, prefix="/v1")
app.include_router(v2_router, prefix="/v2")

The two routers can share most of their logic through plain functions (services) while each version has its own request and response models. That is the key to keeping duplication small: the version differs at the edges (models, routes), not in the core.

Python Two versions side by side with routers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both versions read the same record, but each shapes the answer for its clients. In the generated docs, deprecated=True draws the v1 endpoint struck through, and the tags group each version in Swagger UI. The folder layout usually mirrors this: app/api/v1/ and app/api/v2/, as in Routers and project layout. A small trick keeps main.py tidy: build one api_router per version that includes all of that version's feature routers, then include it once with its prefix.

Strategy 2: the version in a header

Some teams keep URLs stable (/users/1) and choose the version with a header, either a custom one (X-API-Version: 2) or a media type (Accept: application/vnd.example.v2+json). The URL stays "clean", but the version is invisible in logs and the browser address bar, and caches must Vary on the header.

One way to implement this is a dependency that reads the header and a handler that dispatches on it:

Python Choosing a version with a header dependency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A missing header falls back to the default so existing clients keep working, an unknown version is rejected with 406 Not Acceptable, and the Vary header warns shared caches that the answer depends on the version header. This works, but the two code paths now live in one function, and the OpenAPI document shows a single /price endpoint. For anything bigger than a few endpoints, URL versions with routers are easier to document, test and delete.

Strategy 3: separate mounted apps

The strongest isolation is to build each version as its own FastAPI() and mount it, as you learned in Mounting sub-applications:

Python
app = FastAPI()
app.mount("/v1", v1_app)
app.mount("/v2", v2_app)

Each version then gets its own OpenAPI document (/v1/docs, /v2/docs), its own middleware and its own exception handlers. That is useful when versions differ a lot (for example, different authentication). The price is more configuration and no shared documentation page, so choose it only when the isolation is worth it.

Retiring a version politely

Deleting an old version without warning breaks people. A respectful process looks like this:

  1. Announce the plan and a date in your changelog and docs.
  2. Mark endpoints deprecated=True so they show up struck-through in /docs.
  3. Signal in responses. Standard headers help automated clients notice: Deprecation (the version is deprecated) and Sunset (the date it stops working, an HTTP date), plus a Link header pointing to the migration guide.
  4. Measure. Log which clients still call the old version (user agent, API key) so you can contact them.
  5. Remove on the announced date, ideally answering 410 Gone for a while rather than a bare 404.

A middleware or a router-level dependency can add the headers to everything under /v1:

Python Deprecation and Sunset headers for v1

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The dependency is attached to the whole v1 router, so every endpoint in that version announces its end of life, and v2 stays untouched. (See router and global dependencies for the mechanism.)

Practical advice

  • Start with /v1 from day one. Adding it later is itself a breaking change.
  • Version the contract, not the code. Keep the core logic shared and only the schemas and routes duplicated.
  • Test each version with its own test module, so a change to v2 cannot silently alter v1 (testing lesson).
  • Keep the number small. Support at most two or three versions and delete the oldest on schedule.
  • Document changes. A changelog per version is worth more than any clever tooling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which change is backward compatible and normally needs no new version?

    Clients that do not know the new field ignore it. The other changes break existing callers.
  2. 2. How do you serve /v1/... and /v2/... from one app with the router approach?

    include_router(router, prefix=...) mounts the same app's routes under different version prefixes.
  3. 3. Why add Vary: X-API-Version when the version comes from a header?

    Without Vary, a shared cache could return the v1 answer to a client asking for v2.
  4. 4. Which pair of headers helps clients notice an approaching end of an API version?

    Deprecation marks the version as deprecated and Sunset gives the date it stops working.

Summary

  • Add fields and endpoints compatibly when you can; version only for breaking changes.
  • URL versioning with one APIRouter per version is the simplest, most visible approach and the usual FastAPI choice.
  • Header versioning keeps URLs stable but hides the version; add a default, validate values and send Vary.
  • Mounted sub-apps give full isolation (own docs, middleware, handlers) at the price of more setup.
  • Mark old endpoints deprecated=True, send Deprecation/Sunset headers, measure usage and remove on schedule.

Next: shape JSON precisely with jsonable_encoder and serialization control.