How does FastAPI use Pydantic for validation?
FastAPI integrates Pydantic deeply: any function parameter annotated with a Pydantic `BaseModel` subclass is treated as the request body. FastAPI deserializes the incoming JSON, instantiates the model (running all validators), and injects the validated instance into the handler. If validation fails, FastAPI returns a structured 422 Unprocessable Entity response automatically — no manual error handling needed.
**Request body validation** is the core use case. Define a model:
```python class CreateUser(BaseModel): name: str age: int = Field(gt=0, lt=150) email: EmailStr ```
Declare it in the route: `async def create(user: CreateUser)`. FastAPI reads the JSON body, validates types, runs Field constraints (gt, lt, min_length, regex, etc.), and passes a fully typed object to the handler.
**Path and query parameters** use type annotations directly on function parameters — FastAPI infers whether they are path params (matching URL template), query params (everything else scalar), or body (BaseModel). Pydantic coerces string query params to declared types automatically.
**Response models** are declared via `response_model=UserOut` on the route decorator. FastAPI serializes the return value through the Pydantic model, filtering out fields not declared in `UserOut`. This prevents accidental data leakage — a route returning a `User` ORM object will not expose `hashed_password` if it is not in `UserOut`.
**Pydantic v2 changes** (FastAPI 0.100+): validators use `@model_validator` and `@field_validator` instead of v1's `@validator`. v2 is significantly faster (Rust core) and stricter about coercion by default.
**Dependency injection** works alongside Pydantic: `Depends()` lets you extract and validate common parameters (auth tokens, pagination) across routes without repeating logic.
The end result: the OpenAPI schema (available at `/docs`) is auto-generated from these Pydantic models, so documentation, validation, and serialization all stay in sync with the same source of truth — the type annotations.
Explains how BaseModel triggers body parsing and validation, and mentions the automatic 422 response.
Covers response_model filtering, Field constraints, the v1/v2 API change, and the OpenAPI schema generation benefit.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment