Pydantic is used to define and validate the structure and data types of API data.
With Pydantic, you can create models that describe what fields your API data should contain and what type of data each field should have.
Code
from pydantic import BaseModel
class User(BaseModel):
name: str
email: str
age: int
Understanding the Code
First, import BaseModel from Pydantic:
from pydantic import BaseModel
Then create a User model:
class User(BaseModel):
The User model contains three fields:
name: str
email: str
age: int
Here:
namemust be a string.emailmust be a string.agemust be an integer.
Pydantic uses these type definitions to validate the data structure.
Example Data
A valid User object can contain:
{
"name": "Tarun",
"email": "tarun@example.com",
"age": 25
}
Why Use Pydantic?
Pydantic helps FastAPI work with structured and validated data. Instead of manually checking every field, you define the expected structure in a model:
class User(BaseModel):
name: str
email: str
age: int
FastAPI can then use this model when receiving or returning API data.