Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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

Two clients call the same URL. The old phone app sends no header and goes through door 1, getting author as text. The new web app sends API-Version: 2 and goes through door 2, getting authors as a list. API-Version: 3 gets a 400. old phone appno header new web appAPI-Version: 2 door 1 door 2 GET /api/books/10 BookResponse"author": "... & ..." BookResponseV2"authors": [.., ..] API-Version: 3 → 400
Same URL, two shapes. Old clients keep working; new clients opt in.

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

RequestAnswer
no header200, version 1: "author": "Terry Pratchett & Neil Gaiman"
API-Version: 2200, version 2: "authors": ["Terry Pratchett", "Neil Gaiman"]
API-Version: 3400 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 13 of 26

Previous
Paging, Sorting and Filtering a REST API in FastAPI
Next post
Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat

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.

On this page

  • Rename a field and apps break
  • Keep both shapes, pick by version
  • No header means version 1
  • The header asks for version 2
  • A small function reads the header
  • The route asks for the version
  • Version 2 is just another model
  • Ask for version 3 and get 400
  • Header, URL or query parameter?
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.