Pydantic

Pydantic is a Python library used for data validation and settings management. It uses Python type annotations to define data structures and automatically validates input data to ensure it conforms to the expected types. It’s especially useful for working with APIs, databases, or any situation where you need to validate or serialize/deserialize data.

Here are some key features of Pydantic:

1. Data Validation

  • Automatically validates data types based on type annotations.
  • If the data doesn’t match the expected type, it raises a validation error.

2. Type Annotations

  • Pydantic relies heavily on Python’s type hints (introduced in Python 3.5) to define the expected structure of the data.
  • It supports a wide variety of types (strings, integers, floats, lists, dictionaries, etc.).

3. Modeling Data

  • Pydantic allows you to define classes (models) to represent data structures. These models can be used to parse, validate, and serialize data.

from pydantic import BaseModel

# Define a model (data structure)
class User(BaseModel):
name: str
age: int
email: str

# Create an instance of the model with valid data
user = User(name=”John Doe”, age=30, email=”john.doe@example.com”)

# Accessing data
print(user.name) # Output: John Doe

# Invalid data will raise an error
try:
user = User(name=”Jane”, age=”invalid_age”, email=”jane.doe@example.com”)
except ValueError as e:
print(e)

Data Serialization

  • Pydantic models can be converted to dictionaries and JSON, which is useful when working with APIs or databases.

# Convert model to dict
user_dict = user.dict()
print(user_dict) # {‘name’: ‘John Doe’, ‘age’: 30, ’email’: ‘john.doe@example.com’}

# Convert model to JSON
user_json = user.json()
print(user_json) # {“name”: “John Doe”, “age”: 30, “email”: “john.doe@example.com”}

5. Field Validation

  • You can define custom validation logic for fields by using @validator.

from pydantic import BaseModel, validator

class User(BaseModel):
name: str
email: str

@validator(’email’)
def validate_email(cls, value):
if ‘@’ not in value:
raise ValueError(‘Invalid email address’)
return value

# This will raise a validation error
try:
user = User(name=”John”, email=”invalid-email”)
except ValueError as e:
print(e)

6. Nested Models

  • You can also use Pydantic for nested models (i.e., models that contain other models as fields).

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

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

# Creating an instance with a nested model
address = Address(street=”123 Main St”, city=”Anytown”, zip_code=”12345″)
user = User(name=”John Doe”, address=address)

print(user.address.city) # Output: Anytown

7. Environment Variable Parsing

  • Pydantic makes it easy to load settings from environment variables.

from pydantic import BaseSettings

class Settings(BaseSettings):
app_name: str
admin_email: str

class Config:
env_file = “.env”

settings = Settings()
print(settings.app_name) # Output based on the .env file or environment variables

Common Use Cases:

  • APIs: Validate and serialize incoming and outgoing data (e.g., JSON payloads).
  • Configuration Management: Define configuration settings that come from environment variables or configuration files.
  • Database Models: Often used with ORMs (like SQLAlchemy) to validate data before insertion.

Why Use Pydantic?

  • Ease of use with Python’s type annotations.
  • Automatic data validation helps reduce errors.
  • Fast: Pydantic is highly optimized for speed.
  • Integration: Works well with web frameworks like FastAPI, Flask, and others.
Skip to toolbar