Pydantic Highlights Summary
Every highlight bullet from the 10 pages in this section, gathered on one page and grouped by the page it came from.
- Pydantic's job is to parse untrusted data into typed objects at the edge, not to enforce business rules everywhere
- A BaseModel's validation logic is compiled once, at class definition time, into a pydantic-core schema
- model_dump serializes data, model_json_schema describes shape - they never look at the same thing
- Validation runs once at construction; mutating an instance afterward is unchecked unless you opt in
- BaseModel subclasses run validation on instantiation using pydantic-core
- ValidationError locations enable proper API 422 response handling
- Use default_factory for mutable defaults, Optional for optional fields
- model_dump json mode converts datetimes, exclude_unset omits missing fields
- Nested models validate recursively using list syntax for collections
- ConfigDict forbids extra keys, strips whitespace, and enables ORM mode
- Use Field constraints like pattern and ge for input validation at API boundaries
- Pattern constraints restrict formats to letters numbers and hyphens like SKU fields
- Aliases accept multiple JSON key names without changing Python field names
- Validation aliases enable different naming conventions between API requests and Python
- Field constraints automatically generate OpenAPI schema with validation documentation
- Use greater than or equal bounds to enforce minimum numeric values like qty zero or higher
- field_validator strips and normalizes string input using classmethod decorator
- Use field_validator for cross-field validation and normalization checks
- computed_field decorator derives values like area from width times height
- Include derived values in model dumps using computed_field decorator
- Validators run in defined order before and after field processing
- Keep validators pure and fast for consistent model validation
- Use model_dump with exclude_none and by_alias for cleaner API responses
- field_serializer decorator transforms field output types before serialization
- Serialization happens independently from validation in Pydantic models
- Custom serializers control how fields are converted to output formats
- model_dump_json directly produces UTF-8 JSON bytes without extra steps
- Apply serialization to API responses, event payloads, and caching layers
- Subclass BaseSettings to define typed configuration fields
- Environment variables populate settings automatically on instantiation
- Use env_prefix to load only prefixed environment variable names
- Load configuration files with env_file pointing to dotenv location
- Implement 12-factor app pattern with typed environment-based config
- Never commit dotenv files containing real credentials to version control
- Use forward references as strings to defer resolution of recursive model definitions
- Call model_rebuild() to resolve string annotations after the full class is defined
- Limit recursion depth on user input to prevent stack overflow from deep structures
- Discriminated unions provide type-safe variants within recursive model trees
- String annotations defer type resolution enabling self-referential class hierarchies
- Model trees enable config documents, category trees, and AST-like payload structures
- Pydantic v2 uses pydantic-core, a Rust extension, for faster validation
- Use model.model_validate() with strict=True for performance-critical paths
- model.model_validate_json() bypasses Python dict conversion for faster parsing
- Apply strict mode for JSON ingestion and bulk ETL validation workflows
- Reuse model instances to avoid repeated initialization overhead
- Dataclasses are lightweight stdlib for internal data structures
- Pydantic provides validation and automatic JSON schema generation
- attrs is powerful but offers less built-in API schema support
- Use Pydantic frozen models for immutable validated API boundaries
- ConfigDict frozen=True makes Pydantic model instances immutable
- Choose dataclasses for internal DTOs, Pydantic for API validation
- Validate at the boundary and trust types inside domain
- Reject unknown fields in external payloads using forbid
- Split input, internal, and output models for architecture
- Avoid mutable defaults, use default_factory for field setup
- Cap string and list sizes to prevent resource exhaustion
- Never log complete payloads with secrets or sensitive data
Revisado por Chris St. John·Última actualización: 31 jul 2026