FastAPI Tutorial
Selected Reading
- FastAPI - Discussion
- FastAPI - Useful Resources
- FastAPI - Quick Guide
- FastAPI - Deployment
- FastAPI - Mounting Flast App
- FastAPI - Middleware
- FastAPI - Mounting A Sub-App
- FastAPI - FastAPI Event Handlers
- FastAPI - Websockets
- FastAPI - Using GraphQL
- FastAPI - Using MongoDB
- FastAPI - SQL Databases
- FastAPI - Crud Operations
- FastAPI - CORS
- FastAPI - Dependencies
- FastAPI - Nested Models
- FastAPI - Response Model
- FastAPI - Header Parameters
- FastAPI - Cookie Parameters
- FastAPI - Uploading Files
- FastAPI - Accessing Form Data
- FastAPI - HTML Form Templates
- FastAPI - Static Files
- FastAPI - Templates
- FastAPI - Request Body
- FastAPI - Pydantic
- FastAPI - Parameter Validation
- FastAPI - Query Parameters
- FastAPI - Path Parameters
- FastAPI - Rest Architecture
- FastAPI - IDE Support
- FastAPI - Type Hints
- FastAPI - Uvicorn
- FastAPI - OpenAPI
- FastAPI - Hello World
- FastAPI - Introduction
- FastAPI - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
FastAPI - Nested Models
FastAPI - Nested Models
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.
The Customer schema when expanded to show all the nodes looks pke this −
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