
FastAPI
Learn the fundamentals of nested responses in FastAPI.
Real-world APIs often return complex, hierarchical data. Nested response models allow you to define and validate arbitrarily deep data structures using Pydantic's composable models.
In this section, you'll understand:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Address(BaseModel):
street: str
city: str
country: str
class User(BaseModel):
id: int
name: str
address: Address
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
return {
"id": user_id,
"name": "John Doe",
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}class Comment(BaseModel):
id: int
text: str
author: str
class Post(BaseModel):
id: int
title: str
content: str
comments: List[Comment]
@app.get("/posts/{post_id}", response_model=Post)
async def get_post(post_id: int):
return {
"id": post_id,
"title": "My Post",
"content": "Content here",
"comments": [
{"id": 1, "text": "Great post!", "author": "Jane"},
{"id": 2, "text": "Thanks for sharing", "author": "Bob"}
]
}class Tag(BaseModel):
name: str
class Author(BaseModel):
name: str
email: str
class Article(BaseModel):
title: str
author: Author
tags: List[Tag]
metadata: dict
@app.get("/articles/{article_id}", response_model=Article)
async def get_article(article_id: int):
return {...}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