Lesson 1 of 9 · 22m
Validation at the Boundary: Pydantic as a Contract
Where validation belongs, how Pydantic models differ from database models, and the migration mistakes that turn every client typo into a production incident.
FastAPI's killer feature is not type hints. It is a hard boundary where untrusted bytes become typed data — or become a clean rejection before they touch business logic. Treat Pydantic models as a contract with the outside world, not as a convenient way to avoid parsing JSON.
Validate the edge, not the universe
from pydantic import BaseModel, Field, EmailStr
class CreateUserRequest(BaseModel):
email: EmailStr
display_name: str = Field(min_length=1, max_length=80)
marketing_opt_in: bool = FalseBy the time the handler runs, the email is structurally valid, names are bounded, and defaults are explicit. That does not mean the user may register — uniqueness, permissions, and rate limits are business rules — but it does mean malformed input never gets that far.
Keep validation contextual. max_length=80 is a schema rule. 'this tenant may not create more users' is not.
Request models are not database rows
The expensive mistake is reusing one User model everywhere:
class UserCreate(BaseModel):
email: EmailStr
password: str = Field(min_length=12)
class UserOut(BaseModel):
id: int
email: EmailStrNever return a password hash because the ORM object happened to include it. Use separate input, output, and persistence shapes. It feels repetitive until the day the separation prevents a secret leak or lets an API field evolve independently from a table column.
A 422 is useful only when it is readable
FastAPI returns 422 for validation failures, but clients still need actionable messages. Prefer precise field constraints over giant validators that fail mysteriously. When you do write validators, name the business rule:
from pydantic import field_validator
class DeploymentWindow(BaseModel):
starts_at: datetime
ends_at: datetime
@field_validator("ends_at")
@classmethod
def ends_after_start(cls, value, info):
if "starts_at" in info.data and value <= info.data["starts_at"]:
raise ValueError("must be after starts_at")
return valueStrictness is a feature, not a chore
Pydantic coerces compatible values by design: strings that look like integers may become integers. In security-sensitive payloads, prefer strict types or narrower validators. Do not accept arbitrary object shapes because 'some client might send anything'; document what is valid and reject the rest.
Field notes
- Validate input once at the boundary; revalidating every layer hides which layer owns the contract.
- Never expose internal identifiers by accident. Output schemas are allowlists, not conveniences.
- PATCH models need optional fields with care: distinguish 'field absent' from 'explicitly null' using
model_fields_set. - Validation errors belong in logs at debug level. A typo is not an application error.
Was this lesson helpful?