Pydantic: Data Validation Using Python Type Hints
Pydantic is the most downloaded Python validation library. Define data models with type hints, Pydantic validates at runtime. Used by FastAPI, LangChain, Airflow, and thousands of production apps.
Why Pydantic
- Define models with standard Python type hints
- Automatic validation and coercion
- JSON Schema generation
- Serialization/deserialization
- 50x faster than V1 (written in Rust)
The Free API
from pydantic import BaseModel, Field, EmailStr
from datetime import datetime
class User(BaseModel):
name: str = Field(min_length=2, max_length=50)
email: EmailStr
age: int = Field(ge=0, le=150)
created_at: datetime = Field(default_factory=datetime.now)
tags: list[str] = []
# Valid
user = User(name="Alice", email="alice@example.com", age=30)
print(user.model_dump()) # Dict
print(user.model_dump_json()) # JSON string
# Invalid — raises ValidationError
try:
User(name="A", email="not-email", age=-1)
except Exception as e:
print(e) # Detailed error messages
Nested Models
class Address(BaseModel):
street: str
city: str
country: str = "US"
class Company(BaseModel):
name: str
address: Address
employees: list[User]
# Automatic nested validation
company = Company(
name="Acme",
address={"street": "123 Main", "city": "NYC"},
employees=[{"name": "Bob", "email": "bob@acme.com", "age": 25}]
)
Settings Management
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
api_key: str
debug: bool = False
max_connections: int = 10
class Config:
env_file = ".env"
# Reads from environment variables / .env file
settings = Settings()
print(settings.database_url) # From DATABASE_URL env var
JSON Schema
print(User.model_json_schema())
# Outputs full JSON Schema — use for OpenAPI docs, form generation
Real-World Use Case
An API team had 50 endpoints with manual input validation — scattered if/else checks, inconsistent error messages. Pydantic models: one source of truth for validation, auto-generated docs, consistent errors. Bug reports from bad input dropped 90%.
Quick Start
pip install pydantic
python -c "from pydantic import BaseModel; print(Ready!)"
Resources
Need validated data pipelines? Check out my tools on Apify or email spinov001@gmail.com for custom solutions.
Top comments (0)