🍇Unit 12: Request Body - List Fields and Nested Models
Introduction
In FastAPI, you can define request bodies with complex structures using Pydantic models. These can include fields and nested models. In the following sections, this unit will show how to implement list fields and nested models.
List fields
Let's take a look at the following program:
You should note that the above program is implemented in Python 3.12. If you are using Python before version 3.9, the List
declaration is as follows:
from typing import List
my_list: List[str]
To evaluate the program, you can compose a request in Postman as shown in Fig. 1. The request body can be as follows:
In Python, a list
allows duplicate elements and maintains their order, while a set
ensures element uniqueness without any guaranteed order.
Nested models
In the following program, we define two classes, i.e., Image
and Item
, and they have a HAS-A relationship. In Image
class, the metadata
is declared as a list of dictionary (key-value pairs).
The request body to evaluate the above program is as follows. You should note how we compose the metadata
values. Fig. 2 shows the results when evaluating the program in Postman.
Example program
In this example:
We define a Pydantic model
Item
with fieldsname
,description
,price
, andtax
.We then define another Pydantic model
Order
that contains a list ofItem
objects along withcustomer_name
andshipping_address
.In the route
/order/
, we accept POST requests with a request body of typeOrder
.When a request is made to
/order/
, FastAPI automatically validates the request body against theOrder
model and gives you an instance ofOrder
in the route functioncreate_order
.
Summary
In this unit, we have introduced how to enhance request body in FastAPI to allow the server program to capture more complex inputs using list fields and nested models in combination with Pydantic model.
Last updated