Open In App

FastAPI – Nested Models

Last Updated : 06 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

FastApi is a modern web framework used for building API with Python. One of its powerful features is the ability to work with nested models, which allows you to structure and organize your data more effectively. In this article, we will explore the concept of nested models in FastAPI.

What is the Nested Model?

In the context of FastAPI, A nested model is a Python class that represents a structured piece of data within another model. These nested models are used to define the structure of complex data such as JSON objects that can be sent and received by your API. The nested Model helps you to create an API Code that is clean, more organized, and easier to understand.

Creating Nested Model In Fast API

Example: To understand nested models in FastAPI, I have created an API in FastAPI to retrieve user information. In this project, I have created two models: `User` and `Address`. These Python classes inherit from the pydantic.BaseModel class provided by FastAPI. Here’s an example of a simple nested model for a user’s address.

Python3




from pydantic import BaseModel
 
class Address(BaseModel):
    street: str
    city: str
    zip_code: str
 
class User(BaseModel):
    username: str
    email: str
    address: Address


Example: After creating a nested model,use the nested model in request. FastAPI’s automatic request validation and serialization make working with nested models seamless. When you receive data in a request, FastAPI automatically parses it and validates it according to the defined nested model. Here’s how you can use the User model in a POST request

Python3




# api.py
from fastapi import FastAPI
from database import User
 
app = FastAPI()
 
@app.post("/create_user/")
async def create_user(user: User):
    return user


In this example, the User model is used to create a user object with nested address details, which is automatically serialized to JSON when the /get_user/ endpoint is called.

To run a fast API project hit this command

uvicorn api:app --reload

After running this command, my API is run on this URL ‘http://127.0.0.1:8000’.

Output:

Screenshot-(1152)

After running the FastAPI project, I have used Postman to test the API and ensure it works correctly.

Screenshot_1151_50

Conclusion

FastAPI’s support for nested models simplifies the development of complex APIs by providing a clean and organized way to structure and validate your data. It improves code readability, reduces errors, and enhances the overall development experience. Whether you are building a simple REST API or a more complex web service, leveraging nested models in FastAPI can greatly enhance your productivity and code quality.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads