Pydantic & Data Validation
Validate and serialize Python data with Pydantic - type-safe models, nested validation, custom validators, settings management, and FastAPI integration.
skill: Pydantic & Data Validation category: Backend tags: [Pydantic, Python, Data Validation, Type Safety, FastAPI] readingTime: 5
Pydantic validates data at the boundary of your system - API inputs, config files, external API responses - so business logic sees clean, typed data. Catching malformed data at the boundary is cheaper than handling it deep in business logic.
Workflow
- Define models with types and validationPydantic BaseModel parses and validates data on instantiation - wrong types raise ValidationError with field-level error messages.
- Write custom validatorsField constraints (min_length, ge) cover simple rules; custom validators encode domain logic like uniqueness or cross-field constraints.
- Use nested models and serializationNested Pydantic models validate complex structures recursively. model_dump() serializes to dict for JSON responses.
- Manage settings with BaseSettingsBaseSettings reads from environment variables automatically - typed config with validation at startup, not at runtime.
- Integrate with FastAPIFastAPI uses Pydantic for request/response validation and OpenAPI schema generation - no glue code needed.
Output Format
Pydantic models: Field constraints, custom validators, nested models, BaseSettings for config, FastAPI integration.
class MyModel(BaseModel):
field: type = Field(..., constraint)
@field_validator('field')
@classmethod
def validate_field(cls, v): ...
model_dump() / model_dump(mode='json')Examples
Input
Output
Edge Cases & Gotchas
- Strict vs lax mode - By default Pydantic coerces "1" → 1 for int fields. Use model_config = {"strict": True} to reject type mismatches instead of coercing.
- Extra fields - Unknown fields are ignored by default. Use model_config = {"extra": "forbid"} to raise on unexpected fields - useful for strict API contracts.
- Recursive models - Pydantic supports self-referential models (tree structures) via model_rebuild() - required after circular imports.
- Pydantic v1 vs v2 - Pydantic v2 (released 2023) has breaking API changes - @validator → @field_validator, .dict() → .model_dump(). Check the migration guide before upgrading.
When to Break These Rules
- Use attrs or dataclasses for simple data containers without validation - Pydantic adds startup overhead not justified for internal data classes.
- Use marshmallow for complex serialization with custom field rendering logic - Pydantic is better for validation, marshmallow for flexible output formatting.
Reference Files
https://docs.pydantic.dev/latest/https://docs.pydantic.dev/latest/concepts/pydantic_settings/