Pydantic is a data validation library that uses Python type hints to check and convert data. FastAPI integrates it through your type annotations. A BaseModel used as a parameter type becomes the request body, and one used as the response_model shapes the output. FastAPI then uses Pydantic for these jobs:
It validates incoming request data and answers bad data with a 422.
It serializes Python objects in responses to JSON.
It generates the JSON Schema behind the API docs.
It returns detailed validation error messages.
from pydantic import BaseModel, field_validator
from typing import Optional
class User(BaseModel):
name: str
email: str
age: Optional[int] = None
@field_validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v
A field validator adds a rule that type hints cannot express, like the email check above. Since FastAPI now requires Pydantic v2, use @field_validator instead of the older @validator.
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.