- 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 - Response Model
An operation function returns A JSON response to the cpent. The response can be in the form of Python primary types, i.e., numbers, string, pst or dict, etc. It can also be in the form of a Pydantic model. For a function to return a model object, the operation decorator should declare a respone_model parameter.
With the help of response_model, FastAPI Converts the output data to a structure of a model class. It vapdates the data, adds a JSON Schema for the response, in the OpenAPI path operation.
One of the important advantages of response_model parameter is that we can format the output by selecting the fields from the model to cast the response to an output model.
Example
In the following example, the POST operation decorator receives the request body in the form of an object of the student class (a subclass of BaseModel). As one of the fields in this class, i.e. marks (a pst of marks) is not needed in the response, we define another model called percent and use it as the response_model parameter.
from typing import List from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class student(BaseModel): id: int name :str = Field(None, title="name of student", max_length=10) marks: List[int] = [] percent_marks: float class percent(BaseModel): id:int name :str = Field(None, title="name of student", max_length=10) percent_marks: float @app.post("/marks", response_model=percent) async def get_percent(s1:student): s1.percent_marks=sum(s1.marks)/2 return s1
If we check the Swagger documentation, it shows that the "/marks" route gets an object of student class as the request body. Populate the attributes with appropriate values and execute the get_percent() function.
The server response is cast to the percent class as it has been used as the response_model.
Advertisements