Pydantic
Validation and settings management driven by type hints — the boundary guard for Python data.
What it is
Pydantic is a Python library for data validation and settings management using Python type annotations. It enforces type hints at runtime and provides user-friendly errors when data is invalid.
Pydantic uses Python type hints to define data models. It validates input data automatically and can serialize/deserialize data to JSON or Python objects. Pydantic models are immutable by default and support nested models, default values, and custom validation.
- Best known for
- V2's Rust core, which made validation several times faster
- Licence
- MIT
- Watch for
- V1 and V2 APIs differ meaningfully; check which one an example targets
When to use it
The question documentation cannot answer for you — because it cannot recommend something else.
Reach for it when
- Validating data arriving from outside your program: APIs, config files, environment variables
- You want one class to serve as the type, the validator and the serialiser
- Using FastAPI, which is built on it
Look elsewhere when
- You only need a simple internal container with no validation — `dataclass` is lighter
- Validating enormous volumes in a hot loop, where the per-object cost adds up
Installation
pip install pydanticGetting started
The smallest useful thing you can do with it, and what each part means.
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
user = User(id=1, name='Alice')
print(user)from pydantic import BaseModel
class Item(BaseModel):
price: float
item = Item(price='19.99')
print(item.price)Advanced usage
Where the library earns its place over a simpler alternative.
from pydantic import BaseModel
class Address(BaseModel):
city: str
zip: str
class User(BaseModel):
name: str
address: Address
user = User(name='Bob', address={'city': 'NYC', 'zip': '10001'})
print(user)from pydantic import BaseModel, validator
class Product(BaseModel):
name: str
price: float
@validator('price')
def price_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Price must be positive')
return v
product = Product(name='Book', price=10.0)user.json()User.parse_obj({'id': 2, 'name': 'Charlie'})Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- ValidationError
- Occurs when input data does not conform to the model types or constraints. Review the error messages to correct invalid fields.
Best practices
- Use Pydantic models for API request/response validation.
- Leverage type hints to enforce consistent data structures.
- Use nested models to represent complex JSON or hierarchical data.
- Add custom validators for business-specific constraints.
- Use `.dict()` and `.json()` for serialization and data exchange.
Alternatives
Comparable options, and the reason you would pick one over the other.
Background
Why it exists, and what it was reacting to.
Pydantic was created by Samuel Colvin in 2018 to simplify the validation of complex data structures. It has become widely used in FastAPI and other modern Python projects where robust input validation and structured data are critical.
