API Versioning in FastAPI with an API-Version Header
Good Omens has two authors, so the JSON should list both. Changing the shape would break every app that reads it. Keep version 1, add version 2 behind an API-Version header, and answer 400 for a version that doesn't exist.
What you will learn
- Explain why renaming or reshaping a field is a breaking change
- Read an API-Version header with a small dependency that defaults to version 1
- Return a second Pydantic model for version 2 from the same URL
- Answer an unknown version with 400 Problem Details
Before you start
- Pydantic request and response models
- FastAPI dependencies with Depends
Book 10 in our library is Good Omens, by Terry Pratchett and Neil Gaiman. Right now the API sends the author as one piece of text. It would be more honest to send a list of two names. That sounds like a small change, but it can break every app that already reads our books.
Rename a field and apps break
Here's the answer for book 10 today:
{"id":10,"title":"Good Omens","author":"Terry Pratchett & Neil Gaiman","pages":412}
A phone app reads author and shows it under the title. Now we change the field to authors, holding a list. The phone app still looks for author, finds nothing, and its screen breaks. Renaming a field, changing its type or removing it is a breaking change. Adding a new optional field usually isn't. And you can't make every user update their app on the same day.
Keep both shapes, pick by version
The server keeps both shapes behind two doors. Version 1 answers the old way, with author as one text. Version 2 answers the new way, with authors as a list. The old phone app sends nothing special and keeps working. The new web app adds one header, API-Version: 2, and gets the list.
No header means version 1
GET /api/books/10 HTTP/1.1
HTTP/1.1 200
Content-Type: application/json
{"id":10,"title":"Good Omens", "author":"Terry Pratchett & Neil Gaiman", "pages":412}
No API-Version header was sent, and that's fine: version 1 is the default.
The header asks for version 2
GET /api/books/10 HTTP/1.1
API-Version: 2
HTTP/1.1 200
Content-Type: application/json
{"id":10,"title":"Good Omens", "authors":["Terry Pratchett","Neil Gaiman"], "pages":412}
The same URL, a different shape. In version 1, author is one text; in version 2, authors is a list of two names.
A small function reads the header
Some frameworks have versioning built in. FastAPI doesn't, so the project adds one small dependency, versioning.py:
from fastapi import Header
from library.errors import UnknownVersion
def get_version(
api_version: str = Header("1", alias="API-Version", json_schema_extra={"enum": ["1", "2"]}),
) -> str:
"""The client names the version in a header; no header means version 1."""
if api_version not in ("1", "2"):
raise UnknownVersion(api_version)
return api_version
Header("1", alias="API-Version") reads the header called API-Version, and if the client sends nothing, the value is "1". The alias matters: without it, FastAPI would derive the header name from the parameter name (api_version becomes api-version). The json_schema_extra enum makes Swagger UI show a drop-down with 1 and 2. Then a check: only "1" and "2" are allowed, and anything else raises UnknownVersion:
class UnknownVersion(ApiError):
def __init__(self, version: str):
super().__init__(400, "Unknown API version", f"API-Version {version} is not supported, use 1 or 2")
The route asks for the version
@router.get(
"/{book_id}",
response_model=BookResponse | BookResponseV2,
summary="One book (API-Version 1: author is text, 2: authors is a list)",
operation_id="one",
)
def get_book(
book_id: int,
version: str = Depends(get_version),
service: BookService = Depends(get_service),
):
book = service.get(book_id)
if version == "2":
return BookResponseV2.from_book(book)
return BookResponse.model_validate(book)
version: str = Depends(get_version) tells FastAPI: before you run this route, run get_version and hand me what it returns. If the version is "2", the route returns the new model; otherwise it returns the old shape exactly as before. response_model=BookResponse | BookResponseV2 lets the OpenAPI contract show both shapes, and the summary says which version gives which. Any other route can ask for the version the same way with one parameter.
Version 2 is just another model
class BookResponseV2(BaseModel):
"""Version 2: authors is a list, so "Terry Pratchett & Neil Gaiman" becomes two names."""
id: int
title: str
authors: list[str]
pages: int
@classmethod
def from_book(cls, book):
return cls(id=book.id, title=book.title, authors=book.author.split(" & "), pages=book.pages)
The database still keeps one text, "Terry Pratchett & Neil Gaiman". from_book splits it at " & ", so one text becomes a list of two names. A book with a single author, like Dune, simply gets a list of one. Nothing in the database or in version 1 changed; BookResponse stays exactly as it was.
Ask for version 3 and get 400
GET /api/books/10 HTTP/1.1
API-Version: 3
HTTP/1.1 400
Content-Type: application/problem+json
{"detail":"API-Version 3 is not supported, use 1 or 2", "instance":"/api/books/10","status":400, "title":"Unknown API version"}
Only versions 1 and 2 exist, so the client gets a clear 400 in the same Problem Details shape as every other error, with a sentence telling it which versions to use.
Header, URL or query parameter?
A header is one common way to carry the version; the other two you'll meet are a path prefix (/api/v2/books/10) and a query parameter (?version=2). The header keeps one URL per resource, which is why this course uses it. Path versions are easier to try in a browser. Whatever you choose, the rules in this lecture stay the same: keep the old version working, let clients opt in, default sensibly, and refuse unknown versions clearly.
Common mistakes
- Changing the shape in place. Every existing client breaks on the same day.
- No default. If a missing header were an error, every old client would break anyway.
- Silently falling back for unknown versions. A client asking for 3 should hear "no", not get version 1 and misread it.
- Copying the whole database model for v2. Usually only the response model changes; map from the same stored data.
Quick recap
| Request | Answer |
|---|---|
| no header | 200, version 1: "author": "Terry Pratchett & Neil Gaiman" |
API-Version: 2 | 200, version 2: "authors": ["Terry Pratchett", "Neil Gaiman"] |
API-Version: 3 | 400 Problem Details, "Unknown API version" |
When a shape must change, add a version and keep the old one. The client names the version in a header, no header means version 1, and one small function with Depends decides the version for every route that asks for it. For the models themselves, see Pydantic request and response models; for Depends, see path, query, body, response model and Depends.
Try it yourself
Run the project and send the three version requests in requests.http. Then make version 2 also apply to the list endpoint, GET /api/books, so its content holds BookResponseV2 items when the header says 2.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
