Pydantic is the data validation layer in FastAPI. It validates incoming data, converts compatible values into the expected Python types, and serializes data for API responses.
BaseModel is the foundation of Pydantic models. It defines the expected structure and types of your data.
from pydantic import BaseModelclass Product(BaseModel):name: strprice: float
When data is passed to this model, Pydantic validates it and converts compatible values when possible.
Use Field() to define constraints such as minimum length, numeric ranges, and default values.
from pydantic import BaseModel, Fieldclass Product(BaseModel):name: str = Field(min_length=1)price: float = Field(gt=0)
min_length=1: The name must contain at least one character.gt=0: The price must be greater than zero.Use Field() for common validation rules without writing custom validation logic.
Use field_validator when a field requires custom validation logic.
from pydantic import BaseModel, field_validatorclass Product(BaseModel):sku: str@field_validator("sku")@classmethoddef validate_sku(cls, value: str) -> str:if not value.startswith("MON-"):raise ValueError("Invalid SKU")return value
The SKU must start with MON-. Otherwise, Pydantic raises a validation error.
Use model_validator when validation depends on multiple fields.
from datetime import datefrom pydantic import BaseModel, model_validatorclass Promotion(BaseModel):start_date: dateend_date: date@model_validator(mode="after")def validate_dates(self):if self.end_date < self.start_date:raise ValueError("Invalid dates")return self
With mode="after", validation runs after the fields have been validated. The validator can access both dates through self.
Pydantic v2 provides two useful methods for working with data.
model_validate() validates external data and creates a Pydantic model instance.
data = {"name": "Monstera", "price": 500000}product = Product.model_validate(data)
For ORM objects, configure the model with ConfigDict(from_attributes=True) to allow validation from object attributes.
model_dump() converts a Pydantic model into a Python dictionary.
data = product.model_dump()
Result:
{"name": "Monstera","price": 500000.0}
The price is represented as a float because the model declares price: float.
| Feature | Purpose |
|---|---|
BaseModel | Define data structure and types |
Field() | Apply built-in validation constraints |
field_validator | Validate an individual field with custom logic |
model_validator | Validate relationships between fields |
model_validate() | Validate input and create a model instance |
model_dump() | Convert a model into a Python dictionary |
Understanding these features helps you build FastAPI applications with reliable input validation, consistent data structures, and predictable API responses.