Comprehensive Pydantic learning project with hands-on examples and assignments.
01-foundation/ # Basic Pydantic models
02-fields-validation/ # Field validation & constraints
03-model-behavior/ # Validators & computed fields
04-nested-models/ # Complex nested structures
05-serialization/ # Data serialization/deserialization
fastapi/ # FastAPI integration
Basic BaseModel usage, type annotations, data validation
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
is_active: bool
Field constraints, optional fields, descriptions
from pydantic import BaseModel, Field
class Employee(BaseModel):
name: str = Field(..., min_length=3, max_length=50)
salary: float = Field(..., ge=10000)
Custom validators, computed fields
@field_validator('username')
def username_length(cls, v):
if len(v) < 4:
raise ValueError("Username must be at least 4 characters")
return v
@computed_field
@property
def total_price(self) -> float:
return self.price * self.quantity
Embedding models, self-referencing
class Address(BaseModel):
street: str
city: str
class User(BaseModel):
name: str
address: Address # Nested model
Data conversion, JSON encoding
model.model_dump() # → dict
model.model_dump_json() # → JSON string
Model.model_validate(data) # Create from dict
Request/Response models, dependency injection
@app.post('/signup')
def signup(user: UserSignup):
return {'message': f'User {user.username} signed up'}
pip install -e .
python 01-foundation/examples/first_model.py
field: str = Field(min_length=3, max_length=50)
number: int = Field(ge=0, le=100)
@field_validator('field_name')
@model_validator(mode='after')
# Optional with default
field: Optional[str] = None
# Collections
items: List[str]
mapping: Dict[str, int]
# Custom validation
@field_validator('email')
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email')
return v
- Start with basic models, add complexity gradually
- Use Field constraints for data integrity
- Test with invalid data to understand validation
- Leverage Python's type system fully
- Read Pydantic's detailed validation errors