Nested models
In FastAPI, we often deal with data coming from users or other services. This data is usually provided in the form of JSON and needs to be processed in various ways. One of the essential features FastAPI provides is the ability to use Pydantic models to handle and validate this data. In this tutorial, we will dive deeper and explore Nested Models
in FastAPI, which allow us to build more complex and structured data models.
Understanding Pydantic Models
A Pydantic model is a data validation and settings management library provided by Pydantic. It allows us to define the structure of our data using Python classes. These classes can then be used to validate incoming data, provide autocomplete hints, and convert data types like datetimes and UUIDs automatically.
Here's a simple example of a Pydantic model:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str
price: float
tax: float = None
This Item
model will expect a name
, description
, and price
in the incoming data. It also includes an optional tax
field, which can be omitted.
Nesting Pydantic Models
When dealing with complex data structures, we can nest Pydantic models within each other, creating a hierarchy of models. Let's extend our previous example with a nested model:
from pydantic import BaseModel
class Manufacturer(BaseModel):
name: str
location: str
class Item(BaseModel):
name: str
description: str
price: float
tax: float = None
manufacturer: Manufacturer
In this example, Manufacturer
is a Pydantic model nested within the Item
model. Now, the Item
model expects data for a manufacturer
, which should include name
and location
.
Using Nested Models in Request Body
Let's see how we can use this nested model in a FastAPI endpoint:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return {"item": item}
This endpoint expects a POST request with a body matching the Item
model. The request body should include a nested JSON object for the manufacturer
:
{
"name": "Item1",
"description": "This is Item1",
"price": 49.99,
"manufacturer": {
"name": "Manufacturer1",
"location": "Location1"
}
}
FastAPI will automatically validate this data and raise an error if the data doesn't match the Pydantic model.
Conclusion
Nested models in FastAPI are a powerful feature that allows us to create complex data structures and ensure that incoming data matches these structures. By leveraging Pydantic's capabilities, we can build robust and secure APIs with minimal effort.
In the next tutorials, we will further explore FastAPI's features and how they can be used to build efficient, scalable, and maintainable APIs.
This tutorial covers the basics of nested models in FastAPI. For more advanced topics, refer to FastAPI's official documentation. Happy coding!