Understanding Pydantic Models
Key Concepts
Pydantic is a data validation and settings management library for Python. It allows you to define data models with type annotations and automatically validates the data against these models. Here are the key concepts you need to understand:
1. BaseModel
The BaseModel
class is the foundation of Pydantic models. It allows you to define a schema for your data, including fields with specific types and constraints. By inheriting from BaseModel
, you can create custom models that enforce type checking and validation.
2. Type Annotations
Pydantic leverages Python's type annotations to define the expected types for each field in your model. This not only makes your code more readable but also enables automatic validation. For example, you can specify that a field should be a string, integer, or a more complex type like a list or dictionary.
3. Field Validation
Pydantic provides built-in validation for various types of fields. You can specify constraints such as minimum and maximum values, regular expressions for strings, and more. This ensures that the data conforms to the expected format before it is processed.
4. Nested Models
Pydantic models can be nested within each other, allowing you to create complex data structures. This is useful when you need to represent hierarchical data, such as a list of items where each item has its own set of attributes.
Examples
Example 1: Basic Pydantic Model
Here is a simple example of a Pydantic model that defines a user profile:
from pydantic import BaseModel class UserProfile(BaseModel): username: str age: int email: str is_active: bool = True
Example 2: Type Annotations and Field Validation
In this example, we use type annotations and field validation to ensure that the data meets specific criteria:
from pydantic import BaseModel, Field class Product(BaseModel): name: str = Field(..., min_length=3, max_length=50) price: float = Field(..., gt=0) description: str = Field(None, max_length=200)
Example 3: Nested Models
Here, we define a nested model to represent a user with multiple addresses:
from pydantic import BaseModel from typing import List class Address(BaseModel): street: str city: str zip_code: str class User(BaseModel): name: str addresses: List[Address]
By understanding these key concepts and examples, you can effectively use Pydantic models to validate and manage data in your FastAPI applications.