
FastAPI
Pydantic models define the structure and validation rules for request body data in your API.
A Pydantic model is a Python class that defines:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
description: str = NoneThis defines an Item with:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
description: str = None
@app.post("/items")
async def create_item(item: Item):
# item is automatically validated as an Item
return itemValid Request:
{
"name": "Laptop",
"price": 999.99,
"description": "High-performance laptop"
}Response: `{"name": "Laptop", "price": 999.99, "description": "High-performance laptop"}`
Request Missing Optional Field:
{
"name": "Mouse",
"price": 25.00
}Response: `{"name": "Mouse", "price": 25.00, "description": null}`
Invalid Request (missing required field):
{
"price": 100.00
}Response: 422 Error - "name" field is required
class User(BaseModel):
username: str
email: str
age: int
@app.post("/users")
async def create_user(user: User):
# Access fields like object attributes
print(f"Username: {user.username}")
print(f"Email: {user.email}")
# Convert to dictionary
user_dict = user.dict()
# Save to database
db.save_user(user_dict)
return userfrom typing import Optional
class BlogPost(BaseModel):
title: str
content: str
author: str
tags: list = []
published: bool = False
views: int = 0
@app.post("/posts")
async def create_post(post: BlogPost):
return {
"id": 1,
"created": "2024-03-02",
**post.dict()
}When you define a Pydantic model, FastAPI automatically:
1. Shows the expected data structure in `/docs`
2. Provides example requests
3. Validates incoming data
4. Returns helpful error messages
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward