Home
Python
FastAPI: Pydantic
Daniel Nguyen
Daniel Nguyen
September 13, 2026
1 min

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.

Pydantic — raw JSON validated into Python data
Pydantic — raw JSON validated into Python data

1. BaseModel

BaseModel is the foundation of Pydantic models. It defines the expected structure and types of your data.

from pydantic import BaseModel
class Product(BaseModel):
name: str
price: float

When data is passed to this model, Pydantic validates it and converts compatible values when possible.

2. Field()

Use Field() to define constraints such as minimum length, numeric ranges, and default values.

from pydantic import BaseModel, Field
class 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.

3. field_validator

Use field_validator when a field requires custom validation logic.

from pydantic import BaseModel, field_validator
class Product(BaseModel):
sku: str
@field_validator("sku")
@classmethod
def 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.

4. model_validator

Use model_validator when validation depends on multiple fields.

from datetime import date
from pydantic import BaseModel, model_validator
class Promotion(BaseModel):
start_date: date
end_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.

5. model_validate() and model_dump()

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.

Key Takeaways

FeaturePurpose
BaseModelDefine data structure and types
Field()Apply built-in validation constraints
field_validatorValidate an individual field with custom logic
model_validatorValidate 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.


Tags

#Python#FastAPI

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

AI
Building an AI Gateway with FastAPI
October 06, 2026
2 min
Dev98

Dev98

React · Next.js · Web development