Tech With Galvan
Back to Articles
TechFeb 21, 2027 • 6 min read

Pydantic Deep Dive: Data Validation for Python

Pydantic v2 deep dive — models, validators, serialization, settings, and FastAPI integration. The complete guide to Python data validation.

Galvan
Galvan

Founder & Creator

Introduction

Type hints are for static checking (mypy). Pydantic uses the same hints for runtime validation — parse, validate, and serialize data. It’s the backbone of FastAPI, and in 2026 it’s the standard for data validation in Python.

This post covers Pydantic v2: models, validators, serialization, settings, and FastAPI integration.

Basic model

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int = 0   # default

# Valid
user = User(id=1, name="Galvan", email="[email protected]", age=30)
print(user)   # id=1 name='Galvan' email='[email protected]' age=30

# Invalid — raises ValidationError
try:
    User(id="abc", name="Galvan", email="[email protected]")
except Exception as e:
    print(e)

Pydantic validates on construction. Wrong types raise ValidationError with detailed field-level errors.

Type coercion

class User(BaseModel):
    id: int
    name: str

# Pydantic coerces compatible types
user = User(id="42", name="Galvan")
print(user.id)   # 42 (int, not string)
print(type(user.id))   # <class 'int'>

Strings that look like ints are converted. This is usually what you want for API inputs.

Optional and defaults

from typing import Optional
from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: Optional[str] = None
    tags: list[str] = []
    is_active: bool = True

Field constraints

from pydantic import BaseModel, Field

class User(BaseModel):
    id: int = Field(gt=0, description="User ID (positive)")
    name: str = Field(min_length=1, max_length=100)
    age: int = Field(ge=0, le=150)
    email: str = Field(pattern=r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
    score: float = Field(default=0.0, ge=0.0, le=1.0)

Constraints: gt (greater than), ge (>=), lt, le, min_length, max_length, pattern (regex), default, default_factory.

Validators

Field validator

from pydantic import BaseModel, field_validator

class User(BaseModel):
    name: str
    age: int

    @field_validator("name")
    @classmethod
    def name_must_not_be_empty(cls, v):
        if not v.strip():
            raise ValueError("name cannot be empty")
        return v.strip().title()

    @field_validator("age")
    @classmethod
    def age_must_be_positive(cls, v):
        if v < 0:
            raise ValueError("age must be non-negative")
        return v

Model validator (cross-field)

from pydantic import BaseModel, model_validator

class PasswordChange(BaseModel):
    password: str
    confirm: str

    @model_validator(mode="after")
    def passwords_match(self):
        if self.password != self.confirm:
            raise ValueError("passwords do not match")
        return self

mode="before" runs before field validation; mode="after" runs after.

Serialization

user = User(id=1, name="Galvan", email="[email protected]")

# To dict
user.model_dump()                    # {'id': 1, 'name': 'Galvan', ...}
user.model_dump(exclude={"email"})   # exclude fields
user.model_dump(include={"id", "name"})
user.model_dump(by_alias=True)

# To JSON
user.model_dump_json()               # '{"id":1,"name":"Galvan",...}'
user.model_dump_json(indent=2)       # pretty

# From dict/JSON
User.model_validate({"id": 1, "name": "Galvan", "email": "[email protected]"})
User.model_validate_json('{"id": 1, "name": "Galvan", "email": "[email protected]"}')

Nested models

class Address(BaseModel):
    street: str
    city: str
    zip_code: str

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

user = User(name="Galvan", address={"street": "123 Main", "city": "Vadodara", "zip_code": "390001"})
print(user.address.city)   # Vadodara

Nested dicts are auto-converted to nested models.

Computed fields

from pydantic import BaseModel, computed_field

class User(BaseModel):
    first_name: str
    last_name: str

    @computed_field
    @property
    def full_name(self) -> str:
        return f"{self.first_name} {self.last_name}"

user = User(first_name="Galvan", last_name="Moto")
print(user.full_name)        # "Galvan Moto"
print(user.model_dump())     # includes full_name

Settings management (pydantic-settings)

pip install pydantic-settings
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    api_key: str
    debug: bool = False

    class Config:
        env_file = ".env"

settings = Settings()   # reads from .env or environment
print(settings.database_url)

Perfect for app configuration — type-safe, with defaults and validation.

FastAPI integration

FastAPI uses Pydantic for request/response validation and auto-docs:

from fastapi import FastAPI
from pydantic import BaseModel

class UserIn(BaseModel):
    name: str
    email: str
    age: int = Field(ge=0)

class UserOut(BaseModel):
    id: int
    name: str
    email: str

app = FastAPI()

@app.post("/users", response_model=UserOut)
def create_user(user: UserIn):
    # user is validated automatically
    # response is serialized to UserOut shape
    return UserOut(id=1, name=user.name, email=user.email)

The same model validates input, generates OpenAPI docs, and shapes the response.

Pydantic vs dataclasses vs TypedDict

dataclass TypedDict Pydantic
Runtime validation No No Yes
Type coercion No No Yes
Serialization Manual Manual Built-in
Performance Fast Fast Slower (validation)
Use case Internal data Dict shapes API boundaries, config

Rule: Pydantic for API boundaries and config; dataclasses for internal data; TypedDict for dict shapes.

Common mistakes

  • Using Pydantic for everything — it’s slower than dataclasses. Use dataclasses for internal data structures.
  • Mutating validated data — Pydantic models are mutable by default. Use model_config = ConfigDict(frozen=True) for immutability.
  • Ignoring validation errors — ValidationError has detailed info. Catch it and return helpful messages.
  • Not using Field constraints — constraints catch bad data early.
  • Mixing v1 and v2 syntax — v2 uses model_dump(), model_validate(), @field_validator. v1 uses dict(), parse_obj(), @validator. Don’t mix.

Key Concepts

  • BaseModel = base class for validated models
  • Field() = constraints, defaults, metadata
  • @field_validator = validate individual fields
  • @model_validator = cross-field validation
  • model_dump() / model_validate() = serialize/parse
  • BaseSettings = type-safe config from env vars

What to Try Next

FAQ

Pydantic v1 vs v2 — which to use?

v2 is the current standard (2023+). It’s 5-50x faster, uses Rust core, and has a cleaner API. New projects should use v2. v1 is in maintenance mode.

Is Pydantic slow?

v2 is written in Rust and is very fast. For most use cases, validation overhead is negligible (<1ms). For high-throughput systems, use model_validate with strict=True for faster parsing.

Pydantic vs marshmallow?

marshmallow is older and more flexible (custom serialization). Pydantic is faster, uses type hints, and integrates with FastAPI. For new projects, Pydantic. For complex serialization logic, marshmallow still has an edge.