Quick note on Pydantic
Pydantic is a Python library for data validation and settings management using Python type annotations.
It guarantees the types and shapes of data at runtime, making your code more robust and self-documenting.
Use cases:
API request/response validation (e.g., FastAPI)
Configuration management
User input parsing
Data cleaning from external sources (JSON, YAML, etc.)
pip install pydantic
Basic Model Usage
Create a BaseModel
subclass
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
is_active: bool = True # default value
Create an instance
# Create instance
user = User(id=1, name="Alice", email="alice@example.com")
print(user)
Pydantic will automatically:
Convert types (
"1"
to1
)Validate required fields
Use default values where applicable
Example
user = User(id="42", name="Bob", email="bob@example.com")
print(user.id) # 42 — automatically cast from string to int
Field Types and Constraints
You can add field constraints with Field()
:
from pydantic import Field
class Product(BaseModel):
name: str
price: float = Field(..., gt=0)
description: str = Field(default="N/A", max_length=100)
product = Product(name="Laptop", price=-999.99)
Pydantic will raise an error
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for Product
price
Input should be greater than 0 [type=greater_than, input_value=-999.99, input_type=float]
For further information visit https://errors.pydantic.dev/2.11/v/greater_than
Common Constraints
gt
,ge - Greater than, Greater or equal
lt
,le - Less than, Less or equal
max_length
- For stringsmin_items
- For listsregex
- Match a patterndefault_factory
- Create dynamic defaults
Nested Models
class Address(BaseModel):
city: str
country: str
class Employee(BaseModel):
name: str
address: Address
emp = Employee(name="Jane", address={"city": "Berlin", "country": "Germany"})
print(emp.address.city) # "Berlin"
Aliases and Field Mapping
Sometimes JSON keys don't match your Python naming:
class Book(BaseModel):
title: str = Field(..., alias='book_title')
book = Book(book_title="Deep Work")
print(book.title)
Custom Validators
from pydantic import validator
class CustomUser(BaseModel):
name: str
email: str
@validator("email")
def validate_email(cls, v):
if "@" not in v:
raise ValueError("Invalid email")
return v
custom_user = CustomUser(name="Alice", email="alice#example.com")
Pydantic will raise error
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for CustomUser
email
Value error, Invalid email [type=value_error, input_value='alice#example.com', input_type=str]
Parsing & Serialization
Parsing from JSON/dict
data = {"id": "100", "name": "Alice", "email": "alice@example.com"}
user = User.model_validate(data)
print(user)
Serialization to JSON
print(user.model_dump()) # as dict
print(user.model_dump_json()) # as JSON string
This was a quick note on common Pydantic use cases. Happy coding!!