
FastAPI
Learn the fundamentals of response pydantic in FastAPI.
Pydantic models in FastAPI serve dual purposes: validating input data AND ensuring response quality. Using Pydantic for responses provides automatic validation, documentation, and type safety throughout your API.
In this section, you'll understand:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
class Item(BaseModel):
id: int
name: str
price: float
description: Optional[str] = None
in_stock: bool = True
@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
return {
"id": item_id,
"name": "Widget",
"price": 9.99,
"in_stock": True
}from pydantic import BaseModel, Field
class Product(BaseModel):
id: int
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0, le=999999)
quantity: int = Field(default=0, ge=0)
@app.post("/products", response_model=Product)
async def create_product(product: Product):
# Pydantic validates response matches model
return product.dict()from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class UserDB(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
email = Column(String)
class UserResponse(BaseModel):
id: int
name: str
email: str
@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(UserDB).filter(UserDB.id == user_id).first()
return user # Pydantic converts DB model to responseResponse models are critical for:
Ready to explore more? Check out the advanced section for production patterns and edge cases.
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