pythonintermediate

Data Validation with Pydantic Models

Define and validate data models with Pydantic for type-safe Python applications.

python
from pydantic import BaseModel, Field, field_validator
from datetime import datetime
from typing import Optional

class Address(BaseModel):
    street: str
    city: str
    zip_code: str = Field(pattern=r"^\d{5}(-\d{4})?$")

class User(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    email: str
    age: int = Field(ge=0, le=150)
    address: Optional[Address] = None
    created_at: datetime = Field(default_factory=datetime.now)

    @field_validator("email")
    @classmethod
    def validate_email(cls, v: str) -> str:
        if "@" not in v:
            raise ValueError("Invalid email address")
        return v.lower().strip()

# Validates and coerces automatically
user = User(
    name="Alice",
    email="ALICE@example.com",
    age="30",  # coerced to int
    address={"street": "123 Main", "city": "NYC", "zip_code": "10001"}
)
print(user.model_dump_json(indent=2))

Use Cases

  • API request validation
  • Config parsing
  • Data pipelines

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.