English 中文(简体)
FastAPI - Nested Models
  • 时间:2024-12-22

FastAPI - Nested Models


Previous Page Next Page  

Each attribute of a Pydantic model has a type. The type can be a built-in Python type or a model itself. Hence it is possible to declare nested JSON "objects" with specific attribute names, types, and vapdations.

Example

In the following example, we construct a customer model with one of the attributes as product model class. The product model in turn has an attribute of suppper class.


from typing import Tuple
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class suppper(BaseModel):
   suppperID:int
   suppperName:str
class product(BaseModel):
   productID:int
   prodname:str
   price:int
   supp:suppper
class customer(BaseModel):
   custID:int
   custname:str
   prod:Tuple[product]

The following POST operation decorator renders the object of the customer model as the server response.


@app.post( /invoice )
async def getInvoice(c1:customer):
   return c1

The swagger UI page reveals the presence of three schemas, corresponding to three BaseModel classes.

FastAPI Nested Models

The Customer schema when expanded to show all the nodes looks pke this −

FastAPI Nested Models

An example response of "/invoice" route should be as follows −


{
   "custID": 1,
   "custname": "Jay",
   "prod": [
      {
         "productID": 1,
         "prodname": "LAPTOP",
         "price": 40000,
         "supp": {
            "suppperID": 1,
            "suppperName": "Dell"
         }
      }
   ]
}
Advertisements