CS504070 - FastAPI Tutorials
  • 🧩CS504070 - FastAPI Tutorials
  • 🔎Unit 1: Python Type Hint
  • ⚙️Unit 2: Pydantic
  • 🔃Unit 3: Concurrency
  • 💾Unit 4: Install FastAPI
  • 🍉Unit 5: Hello World!
  • 🍌Unit 6: Path Parameters
  • 🍋Unit 7: Query Parameters
  • 🍊Unit 8: Request Body
  • 🍐Unit 9: Query Parameters and Validations
  • 🍎Unit 10: Path Parameters and Validations
  • 🍏Unit 11: Multiple Parameters
  • 🍇Unit 12: Request Body - List Fields and Nested Models
  • 🍓Unit 13: Data Types
  • 🍪Unit 14: Cookie Parameters
  • 🫐Unit 15: Header Parameters
  • 🍈Unit 16: Response Model - Return Type
  • 🍒Unit 17: Additional Models
  • 🥑Unit 18: Implementing JWT Authentication with FastAPI
  • ⚙️Appendix A
  • 🍭Appendix B
Powered by GitBook
On this page
  • Introduction
  • Response Model
  • Return Type

🍈Unit 16: Response Model - Return Type

Introduction

Response Model and Response Type are crucial concepts for defining the structure of the responses your API will send to the client.

Response Model

The "Response Model" in FastAPI is used to:

  • Define the data structure of the response sent to the client.

  • Automatically convert the output data to this structure.

  • Validate the data before sending it to the client.

  • Limit the data that you send to the client, allowing you to hide certain data that the client does not need to receive.

You define a response model by creating a Pydantic model that describes the structure of the response. Then, you specify this model as the response_model argument in your path operation function (like @app.get() or @app.post()).

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.post("/v1/create-item/", response_model=Item)
async def create_item(item: Item):
    return item

In this example, the Item model is used as the response model for the create_item function. This means FastAPI will:

  • Ensure the response matches the Item model structure.

  • Convert the output to JSON format using the model's definition.

  • Validate the response data.

  • Document the API with the model.

Let's extend the program by defining a new class, named ItemV2 (line 12) where we exclude the description attribute from the original Item. The create_item (line 22) receives an item having 4 attributes since it is based on the Item class, and returns an item having 3 attributes based on ItemV2 class.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

class ItemV2(BaseModel):
    name: str
    price: float
    tax: float = None

@app.post("/v1/create-item/", response_model=Item)
async def create_item(item: Item):
    return item

@app.post("/v2/create-item/", response_model=ItemV2)
async def create_item(item: Item):
    return item

You can open the API Docs (http://127.0.0.1:8000/docs/) and view the Schemas of Item and ItemV2, as shown in Fig. 1.

Return Type

The "Return Type" of a path operation function is inferred from the Python type hints. FastAPI uses these type hints to perform data conversion (serialization and deserialization), validation, and documentation.

For example, if you have a path operation function that returns an instance of a Pydantic model, FastAPI will serialize this model to JSON using the model's schema. If you use standard Python types (like dict, list, str, int), FastAPI will directly convert these to JSON.

You can return any object that can be converted to JSON, including Pydantic models, dict, list, tuple, and standard Python types. FastAPI will handle the conversion and ensure the response is in the correct format.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

@app.get("/v1/get-item/")
async def get_item() -> Item:
    item = {"name": "Item 1", "price": 10.5} # We exclude the description and tax
    return item

The usage of response models and return types in FastAPI allows for flexible and efficient API design. You can define the structure and constraints of your data using Pydantic models, and FastAPI will handle the serialization, validation, and documentation.

PreviousUnit 15: Header ParametersNextUnit 17: Additional Models

Last updated 1 year ago

Page cover image
Fig. 1. Schemas in API Docs