Pydantic Models
Pydantic parses and validates JSON into typed Python models, raising errors for missing or wrong-type fields.
Pydantic parses and validates JSON into typed Python models, raising errors for missing or wrong-type fields.
from pydantic import BaseModel, EmailStr, field_validator
from typing import Optional
class User(BaseModel):
id: int
name: str
email: EmailStr
role: Optional[str] = "user"
@field_validator("name")
def name_not_empty(cls, v):
if not v.strip(): raise ValueError("Name cannot be blank")
return v
user = User.model_validate({"id": 1, "name": "Alice", "email": "alice@example.com"})
print(user.model_dump_json())
Pydantic is the standard for FastAPI — models auto-generate JSON schemas for OpenAPI docs.