How-to: API versioning
Separate endpoints into /v1, /v2 using FastAPI's APIRouter + prefix.
Basic structure
python
from fastapi import APIRouter, FastAPI
app = FastAPI()
v1_router = APIRouter(prefix="/v1", tags=["v1"])
v2_router = APIRouter(prefix="/v2", tags=["v2"])
@v1_router.get("/users")
def list_users_v1() -> list[UserResponseV1]:
...
@v2_router.get("/users")
def list_users_v2() -> list[UserResponseV2]:
...
app.include_router(v1_router)
app.include_router(v2_router)An APIRouter's prefix is prepended automatically to the paths inside the router. You do not write /v1 on the in-router paths (it would be duplicated).
Share the domain layer; absorb version differences in the HTTP layer
Keep logic shared across versions in the domain layer, and express the per-version differences in the Pydantic models.
python
# Domain layer (version-independent)
@dataclass(frozen=True, slots=True)
class User:
user_id: int
first_name: str
last_name: str
email: str
age: int
# v1: joined into full_name
class UserResponseV1(BaseModel):
user_id: int
full_name: str
email: str
@classmethod
def from_domain(cls, user: User) -> "UserResponseV1":
return cls(
user_id=user.user_id,
full_name=f"{user.first_name} {user.last_name}",
email=user.email,
)
# v2: split first_name/last_name + add age + email → contact_email
class UserResponseV2(BaseModel):
user_id: int
first_name: str
last_name: str
contact_email: str
age: int
@classmethod
def from_domain(cls, user: User) -> "UserResponseV2":
return cls(
user_id=user.user_id,
first_name=user.first_name,
last_name=user.last_name,
contact_email=user.email,
age=user.age,
)OpenAPI schema
Setting tags=["v1"] / tags=["v2"] on each APIRouter groups them per version in the Swagger UI. UserResponseV1 / UserResponseV2 are defined separately in the schema.
See also
- FT109:
docs/field-trials/2026-05-field-trial-109.md