π¦ What Is Pydantic?
In FastAPI, Pydantic is a library that handles incoming data safely and correctly.
It is used for:
β Data modeling
β Data validation
β Data parsing (type conversion)
β Clear error messages
π Think of Pydantic as a data checker for your API.
Whenever data is sent to your API (e.g., POST request), Pydantic verifies that it is correct before your code uses it.
βοΈ What Pydantic Does
1οΈβ£ Validates Data
Ensures the data matches expected types and rules.
π Example: If rating must be 0β5, value 10 will be rejected.
2οΈβ£ Converts Data Automatically
Converts compatible values to the correct type.
Examples:
"5"β5"true"βTrue
3οΈβ£ Returns Clear Errors
If data is invalid, FastAPI returns a structured error instead of crashing.
4οΈβ£ Generates API Docs
Pydantic models help FastAPI automatically create documentation at:
/docs(Swagger UI)
π In short: Pydantic makes your API safe, reliable, and well-documented.
π§± How We Implement Pydantic (Step-by-Step)
Hereβs how we typically use Pydantic in a FastAPI project:
Step 1: Create a separate request model
Step 2: Inherit from BaseModel
Step 3: Add validation rules using Field
This keeps your API clean, organized, and secure.
π§ͺ Example β Pydantic Request Data Validation
class BookRequest(BaseModel):
id: int
title: str = Field(min_length=3)
author: str = Field(min_length=1)
description: str = Field(min_length=1, max_length=100)
rating: int = Field(gt=-1, lt=6)Letβs break this down carefully π
π BaseModel
BaseModelis the parent class from Pydantic.By inheriting from it, your model automatically gains:
Data validation
Type conversion
Error handling
Serialization support
π Field(...)
The Field() function allows you to apply validation rules to each attribute.
Example:
min_length=3β String must have at least 3 charactersmax_length=100β String must not exceed 100 charactersgt=-1β Greater than -1lt=6β Less than 6
So:
rating: int = Field(gt=-1, lt=6)
# π rating must strictly **between 0 and 5**Means:
π Rating must be between 0 and 5
π Important Keywords
Parameter | Meaning |
|---|---|
| Greater than |
| Less than |
| Minimum number of characters |
| Maximum number of characters |
This ensures your API only accepts properly structured data.
π Converting BookRequest to Book
Now that weβve validated the request dataβ¦
π€ What happens next?
After validation succeeds, we convert the Pydantic model into a domain object.
π€ Why?
Because:
BookRequestis for validationBookis your actual application model
This separation keeps your architecture clean.
π§© Example β Conversion in Action
@app.post("/create_book")
async def create_book(book_request: BookRequest):
new_book = Book(**book_request.model_dump())
BOOKS.append(new_book)Letβs go step-by-step π
π Step 1: Receive Validated Data
book_request: BookRequestFastAPI:
Automatically reads incoming JSON
Validates it using
BookRequestRejects invalid data
Passes only valid data to the function
π Step 2: Convert to Dictionary
book_request.model_dump()This converts the Pydantic object into a standard Python dictionary.
Example output:
{
"id": 1,
"title": "FastAPI Guide",
"author": "Author 4",
"description": "Beginner friendly guide",
"rating": 5
}π Step 3: Unpack Using *
Book(**book_request.model_dump())The double asterisk **:
Unpacks keyβvalue pairs
Passes them into the
Bookconstructor
This creates a proper Book object.
π Step 4: Store the Object
BOOKS.append(new_book)Now the validated and converted book is added to your data store.
β Only clean
β Only validated
β Only structured data