# 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()`).

{% code lineNumbers="true" %}

```python
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
```

{% endcode %}

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.

{% code lineNumbers="true" %}

```python
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
```

{% endcode %}

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.

<figure><img src="https://4188609209-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fhp4eambztJcKKLa7ysKG%2Fuploads%2Fo4KSsrvO6i51ngMQFlSn%2FScreenshot%202024-03-21%20at%202.20.39%20PM.png?alt=media&#x26;token=93d3a2df-8f8f-4296-a0c0-3b12015d99a0" alt=""><figcaption><p>Fig. 1.  <code>Schemas</code> in API Docs</p></figcaption></figure>

## 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.

{% code lineNumbers="true" %}

```python
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
```

{% endcode %}

***

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.
