📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI Response Models

Response Models

5 min read Quiz at the end
Shape API responses with response_model — exclude sensitive fields and serialize ORM objects.

Response Models

from pydantic import BaseModel
from typing import Optional, List
from datetime import datetime

class UserBase(BaseModel):
    name:  str
    email: str

class UserCreate(UserBase):
    password: str

class UserResponse(UserBase):
    id:         int
    created_at: datetime

    model_config = {"from_attributes": True}

class PaginatedUsers(BaseModel):
    data:  List[UserResponse]
    total: int
    page:  int
    pages: int

# Endpoint with response model
@app.get("/users/{id}", response_model=UserResponse)
def get_user(id: int, db: Session = Depends(get_db)):
    return db.get(User, id) or HTTPException(404, "Not found")

@app.get("/users", response_model=PaginatedUsers)
def list_users(page: int = 1, db: Session = Depends(get_db)):
    total = db.query(User).count()
    users = db.query(User).offset((page-1)*10).limit(10).all()
    return {"data": users, "total": total, "page": page, "pages": -(-total//10)}