← Back to Frameworks

FastAPI — Pydantic

FrameworksMidfastapi

The Question

How does FastAPI use Pydantic for validation?

What a Strong Answer Covers

  • BaseModel
  • "Field constraints
  • "422

Senior-Level Answer

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.

What Separates a 2/3 from a 3/3

2/3 — Passing but Incomplete

Explains how BaseModel triggers body parsing and validation, and mentions the automatic 422 response.

3/3 — Strong Answer

Covers response_model filtering, Field constraints, the v1/v2 API change, and the OpenAPI schema generation benefit.

Common Mistakes

  • Not using response_model and accidentally leaking sensitive fields
  • Confusing body params (BaseModel) with query params (scalar annotation) — FastAPI distinguishes them by type
  • Using mutable defaults in Pydantic models — Field(default_factory=list) is required for mutable defaults
  • Not knowing that Pydantic v2 is stricter about string-to-int coercion than v1

Follow-Up Questions

  • How does FastAPI decide whether a parameter is a path param, query param, or body? — Path params match the URL template; BaseModel subclasses become the body; all other scalars are query params.
  • How do you prevent a field from appearing in API responses? — Exclude it from the response_model, or use Field(exclude=True), or use separate request/response models.
  • How do you validate that two fields are consistent with each other? — Use @model_validator(mode='after') to run cross-field logic after individual field validation.
  • What happens when a Pydantic validator raises a ValueError? — FastAPI catches it and includes the error detail in the 422 response body under the field's path.

Related Questions

  • FastAPI — Async vs Sync
  • Django — Signals
  • Django — select_related vs prefetch_related
  • SQLAlchemy — Session
  • Django — Middleware

Can You Explain This Cold?

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
GrindQuestionsAITechnical interview assessment
TermsPrivacyAbout