Your API already has real clients using it, but you need to rename a field in the response — edit it directly and the old clients break immediately. The standard fix is versioning: split the routes into /api/v1 and /api/v2 with APIRouter, keep v1 exactly as it is, and put every breaking change into v2 only. This takes 5 minutes and applies whenever your API is public and you don’t control every client.
The Problem
Suppose the /users endpoint returns {“id”: 1, “name”: “Linh”}. Now you want to split name into first_name and last_name, and add email. If you edit it directly, every old client reading the name field gets null or an error — a mobile app that hasn’t updated yet breaks. The problem is that a single URL serves both old and new clients, so every change is a breaking change.
from fastapi import FastAPIapp = FastAPI()@app.get("/users")def list_users(): return [{"id": 1, "name": "Linh"}]
The Solution
FastAPI solves this neatly with APIRouter: each version is its own router, mounted on the app with a different prefix. The business logic is written once in a shared module; the two routers differ only in how they present the response:
# app/services/users.py — shared logic, written oncedef get_users(): return [{"id": 1, "first_name": "Linh", "last_name": "Hà", "email": "linh@example.com"}]# app/api/v1/users.py — old shape, unchanged for old clientsfrom fastapi import APIRouterfrom app.services.users import get_usersrouter = APIRouter()@router.get("/users")def list_users(): return [ {"id": u["id"], "name": f'{u["first_name"]} {u["last_name"]}'} for u in get_users() ]# app/api/v2/users.py — new shapefrom fastapi import APIRouterfrom app.services.users import get_usersrouter = APIRouter()@router.get("/users")def list_users(): return get_users()
# main.pyfrom fastapi import FastAPIfrom app.api.v1 import users as users_v1from app.api.v2 import users as users_v2app = FastAPI()app.include_router(users_v1.router, prefix="/api/v1", tags=["v1"])app.include_router(users_v2.router, prefix="/api/v2", tags=["v2"])
Now /api/v1/users still returns exactly the old shape, while /api/v2/users returns the new one. Old clients change nothing, new clients use v2. The key point: a version only changes the API surface (field names, response shape), it doesn’t duplicate business logic — get_users() exists in one copy, and both routers call it. When you need v3, just create a v3 router and one more include_router line, and tags=["v1"] groups endpoints by version in Swagger UI.
Apply It to Your Project
Apply this rule to your project: once a version is released, never edit its response — only add new fields (backward compatible) or create a new version. Document which versions are still supported, and watch the logs to know when no requests hit v1 anymore before removing it. This also lets you deprecate gradually: announce v1’s end-of-support date instead of cutting it off suddenly and killing old clients.
Related Posts
- FastAPI: chia API thành nhiều module bằng APIRouter, khỏi dồn hết vào main.py
- FastAPI: Redirect After POST with RedirectResponse — Stop F5 From Resubmitting Your Form in 5 Minutes
- FastAPI: Customize Your OpenAPI Docs — Change the Title, Tag Endpoints, and Hide Internal Routes in 5 Minutes
FAQ
Should the version go in the URL or in a header?
In the URL (/api/v1/…) — it’s the most common approach: easy to test in a browser, easy to cache, easy to read in logs. A version in a header (Accept: application/vnd.api.v1+json) keeps the URL cleaner but is harder to try by hand and harder to debug. For most projects, the version in the URL is enough.
When do I need to create a new version?
Only for a breaking change: renaming or deleting a field, changing a data type, changing what a field means, changing a status code. Adding a new field to the response or a new endpoint doesn’t need one — old clients safely ignore unfamiliar fields.
Do I have to duplicate all the code for each version?
No. Only the thin route layer is duplicated: two routers call the same service, the same models, the same query functions. If v2 differs from v1 in only a few endpoints, rewrite just those endpoints and import the rest from v1.
How long should I keep v1 before removing it?
Keep it until the logs show no client has called v1 for a long enough stretch (for example 3–6 months), and after you’ve announced the deprecation. Remove it too early and old clients die; keep it forever and it’s technical debt — watch the weekly v1 request count to decide.
💬 Have you tried this in your own project? If you hit an error or have a shorter way to do it, leave a comment below — I read them all and will add the best ideas to the post.
