0
0
FastAPIframework~5 mins

Nested models in FastAPI

Choose your learning style9 modes available
Introduction
Nested models help organize related data inside other data, making it easier to manage and understand complex information.
When you want to represent a user with an address inside their profile.
When you have an order that contains multiple items, each with its own details.
When you need to group related settings inside a main configuration.
When your API needs to accept or return structured data with parts inside parts.
Syntax
FastAPI
from pydantic import BaseModel

class InnerModel(BaseModel):
    field1: str
    field2: int

class OuterModel(BaseModel):
    inner: InnerModel
    other_field: float
Nested models are defined by including one model as a field type inside another.
FastAPI uses Pydantic models to validate and serialize nested data automatically.
Examples
A User model contains an Address model as a nested field.
FastAPI
from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    name: str
    address: Address
An Order model contains a list of Item models nested inside.
FastAPI
from pydantic import BaseModel
from typing import List

class Item(BaseModel):
    name: str
    price: float

class Order(BaseModel):
    items: List[Item]
    total: float
Sample Program
This FastAPI app defines a User model with a nested Address model. When you send a POST request with user data including address, it returns a confirmation message showing the user's name and city.
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Address(BaseModel):
    street: str
    city: str

class User(BaseModel):
    name: str
    age: int
    address: Address

@app.post("/users/")
async def create_user(user: User):
    return {"message": f"User {user.name} from {user.address.city} created."}
OutputSuccess
Important Notes
Nested models help keep your data organized and validated automatically.
You can nest models as deeply as needed, but keep readability in mind.
FastAPI automatically converts nested JSON data into nested model instances.
Summary
Nested models let you put one data model inside another to represent complex data.
FastAPI and Pydantic handle nested data validation and conversion smoothly.
Use nested models to keep your API data clear and structured.