Topics in this subject
FastAPI 3 min read Updated 11 Aug 2026

Pydantic and Validation

Type hints and Pydantic models for automatic data validation and serialization.

🧑‍🏫 Sabse pehle — simple mein samjho#

Jab user sign up form bharta hai, humein check karna padta hai ki usne email sahi format mein daala hai ya nahi, aur age number hai ya text. Node/Express mein humein Joi ya Zod jaise alag packages lagane padte hain aur lamba code likhna padta hai. FastAPI mein ye by-default aata hai Pydantic ke through. Tum bas ek "Model" banate ho (jisme batate ho ki name string hona chahiye, age number). Agar user galti se age mein "twenty" bhejta hai, to FastAPI usko khud hi reject karke ek sundar sa error message bhej deta hai. Tumhe if-else likhne ki zaroorat hi nahi!

What is Pydantic?#

Pydantic is a data validation and settings management library utilizing Python type annotations. It enforces type hints at runtime and provides user-friendly errors when data is invalid.

Creating a Pydantic Model#

You define the shape of your data by creating a class that inherits from BaseModel.

from pydantic import BaseModel, EmailStr

# This model acts as both the schema and the validator
class UserCreate(BaseModel):
    username: string
    # Using EmailStr strictly validates that the string is a valid email format
    email: EmailStr 
    # Providing a default value makes the field optional
    age: int | None = None 
    is_active: bool = True

How FastAPI Uses Pydantic#

When you declare a parameter in a FastAPI path operation function to be of the type of a Pydantic model, FastAPI does the following automatically:

  1. Reads the body of the HTTP request as JSON.
  2. Converts the JSON into Python data types.
  3. Validates the data. If the data is invalid (e.g., age is passed as the string "old"), it immediately stops the request and returns a 422 Unprocessable Entity error detailing exactly which field failed.
  4. Gives you the validated data directly inside your route function, providing full IDE autocomplete!
from fastapi import FastAPI

app = FastAPI()

@app.post("/users/")
async def create_user(user: UserCreate):
    # Here, 'user' is already a fully validated Python object, not a raw dict!
    
    # We can access properties using dot notation
    print(user.username)
    
    # We can convert it back to a dictionary if needed (e.g., to save in DB)
    user_dict = user.model_dump()
    
    # FastAPI will automatically serialize the Pydantic model back to JSON
    return user

The Power of Type Coercion#

Pydantic doesn't just reject data; it tries to coerce (convert) it if it safely can. If you define age: int, and the client sends JSON with "age": "25" (as a string), Pydantic is smart enough to convert that string into the integer 25. It only throws an error if coercion is impossible (like "age": "twenty").