3 Hours

6. Data Validation with Pydantic

Data Validation

Pydantic is the data validation library that powers FastAPI. It uses Python type hints to validate, serialize, and document your data models. When you define a Pydantic model, you get automatic validation, JSON schema generation, and complex data parsing for free. To test these examples, save to a .py file and run python filename.py.

What is Pydantic?

Pydantic V2 Validation & Type Coercion Funnel Raw unvalidated payloads pass through Rust-powered pydantic-core for strict validation RAW JSON PAYLOAD {"price": "19.99", "email": "a@b.com"} String representations pydantic-core (RUST) • Coerces "19.99" → float • Validates EmailStr format • Runs @field_validator 50x Faster than V1 TYPED MODEL INSTANCE item.price = 19.99 item.email = 'a@b.com' ✓ 100% Type Safe

Pydantic is a data validation library that leverages Python type hints. Instead of writing dozens of if statements to check types, ranges, and formats, you define a model class with type-annotated fields. Pydantic handles all validation automatically.

Python 3
from pydantic import BaseModel
from datetime import datetime
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: str
    created_at: Optional[datetime] = None

# Valid data creates an instance
user = User(id=1, name="Alice", email="alice@example.com")
print(user.name)
print(user.model_dump())

# Invalid data raises a ValidationError
try:
    user = User(id="not an int", name="Bob", email="bob@test.com")
except Exception as e:
    print(f"Error: {e}")
Local Testing: Run this code. The first user works. The second raises a validation error because id should be an integer.

Field Validation with Field()

The Field() function adds constraints to model fields like minimum and maximum values, string lengths, and regex patterns.

Python 3
from pydantic import BaseModel, Field, EmailStr
from typing import Optional

class Product(BaseModel):
    name: str = Field(..., min_length=3, max_length=50)
    price: float = Field(..., gt=0, le=10000)
    stock: int = Field(default=0, ge=0)
    sku: str = Field(..., regex="^[A-Z]{3}-[0-9]{4}$")
    email: EmailStr
    tags: Optional[list[str]] = Field(default=[])

# Valid product
product = Product(
    name="Laptop",
    price=999.99,
    sku="LAP-1234",
    email="seller@example.com"
)
print("Product created:", product.name)

# Invalid product would raise ValidationError

Custom Validators with @field_validator

For complex validation logic, use the @field_validator decorator. This runs after basic type validation and can transform or validate data.

Python 3
from pydantic import BaseModel, field_validator

class Order(BaseModel):
    items: list[str]
    total: float
    discount_code: str = None

    @field_validator("total")
    def validate_total(cls, v: float) -> float:
        if v <= 0:
            raise ValueError("Total must be greater than 0")
        return round(v, 2)

    @field_validator("discount_code")
    def validate_discount(cls, v: str) -> str:
        if v is not None and len(v) != 8:
            raise ValueError("Discount code must be 8 characters")
        return v.upper() if v else v

# Valid order
order = Order(items=["item1"], total=99.99)
print("Order created:", order.total)

# Invalid order would raise ValidationError

Validation Order

Pydantic validates in this order: 1. Type validation (int, str, etc.) 2. Field constraints (min, max, regex) 3. Custom field validators 4. Model validators. You cannot change this order.

Model Validators (@model_validator)

Use @model_validator when validation depends on multiple fields. For example, ensuring an end date comes after a start date.

Python 3
from pydantic import BaseModel, model_validator
from datetime import date

class DateRange(BaseModel):
    start_date: date
    end_date: date

    @model_validator(mode='after')
    def check_dates(self):
        if self.end_date <= self.start_date:
            raise ValueError('end_date must be after start_date')
        return self

class Registration(BaseModel):
    password: str
    confirm_password: str

    @model_validator(mode='after')
    def passwords_match(self):
        if self.password != self.confirm_password:
            raise ValueError('Passwords do not match')
        return self

# This would raise validation error
# reg = Registration(password="secret123", confirm_password="different")

Optional Fields and Defaults

Fields with default values are optional. You can set defaults as values or as functions using default_factory.

Python 3
from pydantic import BaseModel, Field
from uuid import uuid4
from datetime import datetime

class Item(BaseModel):
    id: str = Field(default_factory=lambda: str(uuid4()))
    name: str
    created_at: datetime = Field(default_factory=datetime.now)
    tags: list[str] = []
    is_active: bool = True

# All these fields are optional because they have defaults
item = Item(name="Laptop")
print(f"ID: {item.id}")
print(f"Created: {item.created_at}")
print(f"Tags: {item.tags}")
Never use mutable defaults like [] directly! Using tags: list[str] = [] is actually safe in Pydantic because it creates a new list for each instance. But in standard Python classes, this is dangerous.

Nested Models

Pydantic models can contain other Pydantic models, allowing you to represent complex, nested data structures.

Python 3
class Address(BaseModel):
    street: str
    city: str
    zipcode: str

class User(BaseModel):
    name: str
    email: str
    address: Address

class Order(BaseModel):
    order_id: int
    user: User
    items: list[dict]

# Valid data with nesting
order = Order(
    order_id=1,
    user={
        "name": "Alice",
        "email": "alice@test.com",
        "address": {
            "street": "123 Main St",
            "city": "New York",
            "zipcode": "10001"
        }
    },
    items=[]
)
print(f"Order {order.order_id} for {order.user.name}")

Knowledge Check

Ready to test your understanding of 6. Data Validation with Pydantic?

Back