Pydantic

Language: Python

CLI/Utils

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.

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.

Installation

pip: pip install pydantic
conda: conda install -c conda-forge pydantic

Usage

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.

Defining a simple model

from pydantic import BaseModel

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

user = User(id=1, name='Alice')
print(user)

Defines a basic User model with two fields. Pydantic validates types automatically.

Validation and type coercion

from pydantic import BaseModel

class Item(BaseModel):
    price: float

item = Item(price='19.99')
print(item.price)

Pydantic automatically converts compatible types (str → float) during validation.

Nested models

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)

Demonstrates nested data models and automatic validation of nested dictionaries.

Custom validation

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)

Shows how to create custom validators to enforce business rules on fields.

Exporting to JSON

user.json()

Serialize the Pydantic model instance to a JSON string.

Parsing raw data

User.parse_obj({'id': 2, 'name': 'Charlie'})

Parse a Python dictionary into a validated Pydantic model.

Error Handling

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.