
FastAPI
Learn the fundamentals of list responses in FastAPI.
Returning lists of objects is a common API pattern. FastAPI's response models ensure all items in the list match the expected schema, providing type safety and automatic validation.
In this section, you'll understand:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Item(BaseModel):
id: int
name: str
price: float
@app.get("/items", response_model=List[Item])
async def list_items():
return [
{"id": 1, "name": "Widget", "price": 9.99},
{"id": 2, "name": "Gadget", "price": 19.99},
]@app.get("/users", response_model=List[User])
async def list_users(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
users = db.query(User).offset(skip).limit(limit).all()
return usersclass Category(BaseModel):
id: int
name: str
class ItemWithCategory(BaseModel):
id: int
name: str
categories: List[Category]
@app.get("/products", response_model=List[ItemWithCategory])
async def list_products():
return [
{
"id": 1,
"name": "Product A",
"categories": [
{"id": 1, "name": "Electronics"},
{"id": 2, "name": "Gadgets"}
]
}
]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