← Back to Tutorials

22. Nested Models

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI()

# Sub-model
class Image(BaseModel):
    url: str
    name: str

# List of sub-models
class Item(BaseModel):
    name: str
    price: float
    tags: List[str] = []
    images: List[Image] = []  # nested list

# Deep nesting
class Address(BaseModel):
    street: str
    city: str
    zip: str

class User(BaseModel):
    username: str
    address: Address  # nested object
    items: List[Item] = []  # list of nested

@app.post("/users/")
def create_user(user: User):
    return user

# Arbitrary dicts
from pydantic import Field

class Product(BaseModel):
    name: str
    metadata: dict = {}  # arbitrary key-value
✏️ Exercise: Create models for a Blog with Author (name, bio), Post (title, content, tags[]), and Comment (author, text, date). Create a POST endpoint that accepts a full blog post.