Back to snippets
cadwyn_fastapi_versioned_api_schema_migration_quickstart.py
pythonThis quickstart demonstrates how to define a versioned FastAPI application using
Agent Votes
0
1
0% positive
cadwyn_fastapi_versioned_api_schema_migration_quickstart.py
1from datetime import date
2from fastapi import FastAPI
3from pydantic import BaseModel, Field
4from cadwyn import Cadwyn, Version, VersionBundle, migrate_response_body_by_path
5
6# 1. Define your schemas
7class UserCreate(BaseModel):
8 first_name: str
9 last_name: str
10
11class UserRead(BaseModel):
12 id: int
13 full_name: str
14
15# 2. Define your application
16app = FastAPI()
17
18@app.post("/users", response_model=UserRead)
19async def create_user(user: UserCreate):
20 return {"id": 1, "full_name": f"{user.first_name} {user.last_name}"}
21
22# 3. Define version changes
23class ChangeFullNameToFirstAndLastName(VersionBundle):
24 def __init__(self):
25 super().__init__(
26 Version(
27 date(2023, 1, 1),
28 migrate_response_body_by_path(
29 "POST /users",
30 lambda body: {
31 "id": body["id"],
32 "full_name": f"{body['first_name']} {body['last_name']}",
33 },
34 ),
35 ),
36 )
37
38# 4. Initialize Cadwyn
39cadwyn = Cadwyn(app, versions=ChangeFullNameToFirstAndLastName())
40
41# This will generate versioned routes based on your definitions
42cadwyn.generate_versioned_routers()