FastAPI and Pydantic V2

FastAPI 0.100+, released in July 2023, adopts Pydantic V2 by default. Request and response models benefit from the Rust core for up to 50x faster validation. Migration is generally transparent for simple cases.

Code Adaptation

python
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict

app = FastAPI()

# Pydantic V2 in FastAPI
class Item(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str
    price: float
    in_stock: bool = True

@app.post('/items/')
async def create_item(item: Item) -> Item:
    return item

# model_validate replaces parse_obj
item = Item.model_validate({'name': 'Widget', 'price': 9.99})
# model_dump replaces dict()
print(item.model_dump())  # {'name': 'Widget', ...}

Sources