Runtime Validation, Fields & Custom Validators
Type Hints, Enforced
Pydantic validates data using standard Python type hints — but unlike normal Python (where type hints are only checked statically by tools like mypy), Pydantic actively enforces and coerces them at runtime when a model is instantiated. A field typed int receiving "42" gets coerced to the integer 42 in default (non-strict) mode.
Models & Validation Errors
from pydantic import BaseModel, Field
class UserCreate(BaseModel):
email: str
age: int = Field(gt=0, description="User age in years")
try:
UserCreate(email="a@b.com", age=-1)
except ValidationError as e:
print(e) # clear, structured error: age must be > 0Invalid data raises ValidationError describing exactly which fields failed and why. Field() attaches constraints (gt, max_length) and metadata beyond the bare type hint — metadata that FastAPI also uses to enrich generated OpenAPI docs.
Custom Validators & Aliases
class Order(BaseModel):
user_id: int = Field(alias="userId")
@field_validator("user_id")
@classmethod
def positive_id(cls, v):
if v <= 0:
raise ValueError("user_id must be positive")
return v@field_validator expresses custom business-rule logic beyond simple type/constraint checks. alias bridges naming convention mismatches — accepting camelCase JSON keys (userId) from a frontend while keeping snake_case Python attributes internally.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free