3. Building Web APIs with FastAPI & Pydantic
Request & Response Validation with Pydantic BaseModel
Validate incoming JSON payloads, enforce field constraints with Field(), write custom validators, and separate input vs public output schemas using Pydantic v2.
- Define strict request and response models with Pydantic BaseModel and Field()
- Separate Create/Update input schemas from Public output schemas to never leak secrets
- Enforce custom cross-field or format rules with @field_validator
Never trust raw JSON sent by clients! Someone will send "price": -50, "title": "", or try injecting an unexpected "is_admin": true field.
Pydantic v2 sits at the boundary of FastAPI to parse, validate, normalize, and document every JSON request body and response automatically.
1. Architecture: Pydantic as the API Data Boundary
Think of Pydantic schemas (DTOs — Data Transfer Objects) as security gates on both sides of your route handler:
Untrusted JSON ──▶ Input Schema (CourseCreate) ──▶ Validated Python Object ──▶ Repository / DB
│
Safe Public JSON ◀── Output Schema (response_model=UserPublic) ◀── Raw DB Row ────────┘- Inbound Gate: Rejects invalid payloads before your endpoint or SQL runs, returning a structured
422 Unprocessable Entityerror array. - Outbound Gate: Filters database rows through
response_model=...so sensitive columns (password_hash, internal flags) are stripped before leaving the server.
2. Input Validation with BaseModel, Field() & Validators
Use Field(...) for declarative constraints (min_length, gt, le, pattern), @field_validator for normalizing/checking single fields, and @model_validator(mode="after") for cross-field rules:
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
class CourseCreate(BaseModel):
model_config = ConfigDict(extra="forbid") # Reject unknown fields like "is_admin"!
slug: str = Field(min_length=3, max_length=60, pattern=r"^[a-z0-9-]+$")
title: str = Field(min_length=3, max_length=120)
hours: int = Field(gt=0, le=200)
discount_hours: int = Field(default=0, ge=0)
@field_validator("title")
@classmethod
def strip_title(cls, value: str) -> str:
cleaned = value.strip()
if not cleaned:
raise ValueError("Title cannot be blank")
return cleaned
@model_validator(mode="after")
def check_discount_range(self):
if self.discount_hours >= self.hours:
raise ValueError("discount_hours must be less than total hours")
return self400 Bad Request vs 422 Unprocessable Entity in FastAPI
400 Bad Request: The raw HTTP body isn't valid JSON at all (e.g., broken syntax{title:) or violates a runtime business rule your route checks manually.422 Unprocessable Entity: The body is syntactically valid JSON, but fails Pydantic schema rules (wrong type, missing required field,hours: -5, or customValueErrorin a validator).
- By default, Pydantic ignores extra JSON keys—if you naively pass
payload.model_dump()into a generic DBUPDATEhelper withoutextra="forbid", or trust client-suppliedid/rolefields, attackers can escalate privileges (mass assignment). - Pydantic v2 coerces compatible inputs by default (e.g.
"42"becomesint42). If a field must reject strings like"42", useStrictIntorConfigDict(strict=True).
3. Never Use One Schema for Everything (Input vs Output Schemas)
A classic security mistake is returning the same model you used to create or store a user—accidentally leaking password_hash, internal tokens, or private flags!
Always separate schemas by lifecycle role (Create, Update, Public):
UserCreate: acceptsname,email,password(plain text over HTTPS).UserUpdate: all fields optional (name: str | None = None) forPATCH.UserPublic(response_model=UserPublic): outputsid,name,email(neverpasswordorpassword_hash!).
class UserCreate(BaseModel):
model_config = ConfigDict(str_strip_whitespace=True)
name: str = Field(min_length=2)
email: str
password: str = Field(min_length=8)
class UserUpdate(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
name: str | None = Field(default=None, min_length=2)
email: str | None = None
class UserPublic(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
name: str
email: strNotice ConfigDict(str_strip_whitespace=True): Pydantic v2 automatically strips leading/trailing spaces from every string field on that model without writing repetitive @field_validator boilerplate! For PATCH routes, UserUpdate pairs with payload.model_dump(exclude_unset=True) so omitted fields stay untouched.
Adding model_config = ConfigDict(from_attributes=True) lets a Pydantic v2 response model read attributes directly from a @dataclass or SQLAlchemy ORM object (UserPublic.model_validate(user_obj)) instead of requiring a plain dict!
Try It Yourself in the Playground
Test the core validation pattern (stripping, range constraints, rejecting unknown keys, and stripping secret fields before returning JSON) live in Python:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: What happens in FastAPI if a route has @app.post("/users", response_model=UserPublic) and your function returns a dictionary containing "password_hash": "secret123" alongside id, name, and email?
Quick Checkpoints
What HTTP status code does FastAPI return automatically when incoming JSON fails Pydantic BaseModel validation?
Why should you define separate UserCreate and UserPublic Pydantic models?