Response Model

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

You can declare the model used for the response with the parameter response_model in any of the path operations:

  • @app.get()
  • @app.post()
  • @app.put()
  • @app.delete()
  • etc.
  1. from typing import List, Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: Optional[float] = None
  10. tags: List[str] = []
  11. @app.post("/items/", response_model=Item)
  12. async def create_item(item: Item):
  13. return item

Note

Notice that response_model is a parameter of the “decorator” method (get, post, etc). Not of your path operation function, like all the parameters and body.

It receives the same type you would declare for a Pydantic model attribute, so, it can be a Pydantic model, but it can also be, e.g. a list of Pydantic models, like List[Item].

FastAPI will use this response_model to:

  • Convert the output data to its type declaration.
  • Validate the data.
  • Add a JSON Schema for the response, in the OpenAPI path operation.
  • Will be used by the automatic documentation systems.

But most importantly:

  • Will limit the output data to that of the model. We’ll see how that’s important below.

Technical Details

The response model is declared in this parameter instead of as a function return type annotation, because the path function may not actually return that response model but rather return a dict, database object or some other model, and then use the response_model to perform the field limiting and serialization.

Return the same input data

Here we are declaring a UserIn model, it will contain a plaintext password:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, EmailStr
  4. app = FastAPI()
  5. class UserIn(BaseModel):
  6. username: str
  7. password: str
  8. email: EmailStr
  9. full_name: Optional[str] = None
  10. # Don't do this in production!
  11. @app.post("/user/", response_model=UserIn)
  12. async def create_user(user: UserIn):
  13. return user

And we are using this model to declare our input and the same model to declare our output:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, EmailStr
  4. app = FastAPI()
  5. class UserIn(BaseModel):
  6. username: str
  7. password: str
  8. email: EmailStr
  9. full_name: Optional[str] = None
  10. # Don't do this in production!
  11. @app.post("/user/", response_model=UserIn)
  12. async def create_user(user: UserIn):
  13. return user

Now, whenever a browser is creating a user with a password, the API will return the same password in the response.

In this case, it might not be a problem, because the user himself is sending the password.

But if we use the same model for another path operation, we could be sending our user’s passwords to every client.

Danger

Never store the plain password of a user or send it in a response.

Add an output model

We can instead create an input model with the plaintext password and an output model without it:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, EmailStr
  4. app = FastAPI()
  5. class UserIn(BaseModel):
  6. username: str
  7. password: str
  8. email: EmailStr
  9. full_name: Optional[str] = None
  10. class UserOut(BaseModel):
  11. username: str
  12. email: EmailStr
  13. full_name: Optional[str] = None
  14. @app.post("/user/", response_model=UserOut)
  15. async def create_user(user: UserIn):
  16. return user

Here, even though our path operation function is returning the same input user that contains the password:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, EmailStr
  4. app = FastAPI()
  5. class UserIn(BaseModel):
  6. username: str
  7. password: str
  8. email: EmailStr
  9. full_name: Optional[str] = None
  10. class UserOut(BaseModel):
  11. username: str
  12. email: EmailStr
  13. full_name: Optional[str] = None
  14. @app.post("/user/", response_model=UserOut)
  15. async def create_user(user: UserIn):
  16. return user

…we declared the response_model to be our model UserOut, that doesn’t include the password:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel, EmailStr
  4. app = FastAPI()
  5. class UserIn(BaseModel):
  6. username: str
  7. password: str
  8. email: EmailStr
  9. full_name: Optional[str] = None
  10. class UserOut(BaseModel):
  11. username: str
  12. email: EmailStr
  13. full_name: Optional[str] = None
  14. @app.post("/user/", response_model=UserOut)
  15. async def create_user(user: UserIn):
  16. return user

So, FastAPI will take care of filtering out all the data that is not declared in the output model (using Pydantic).

See it in the docs

When you see the automatic docs, you can check that the input model and output model will both have their own JSON Schema:

Response Model - 图1

And both models will be used for the interactive API documentation:

Response Model - 图2

Response Model encoding parameters

Your response model could have default values, like:

  1. from typing import List, Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: float = 10.5
  10. tags: List[str] = []
  11. items = {
  12. "foo": {"name": "Foo", "price": 50.2},
  13. "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
  14. "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
  15. }
  16. @app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
  17. async def read_item(item_id: str):
  18. return items[item_id]
  • description: Optional[str] = None has a default of None.
  • tax: float = 10.5 has a default of 10.5.
  • tags: List[str] = [] as a default of an empty list: [].

but you might want to omit them from the result if they were not actually stored.

For example, if you have models with many optional attributes in a NoSQL database, but you don’t want to send very long JSON responses full of default values.

Use the response_model_exclude_unset parameter

You can set the path operation decorator parameter response_model_exclude_unset=True:

  1. from typing import List, Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: float = 10.5
  10. tags: List[str] = []
  11. items = {
  12. "foo": {"name": "Foo", "price": 50.2},
  13. "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
  14. "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
  15. }
  16. @app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
  17. async def read_item(item_id: str):
  18. return items[item_id]

and those default values won’t be included in the response, only the values actually set.

So, if you send a request to that path operation for the item with ID foo, the response (not including default values) will be:

  1. {
  2. "name": "Foo",
  3. "price": 50.2
  4. }

Info

FastAPI uses Pydantic model’s .dict() with its exclude_unset parameter to achieve this.

Info

You can also use:

  • response_model_exclude_defaults=True
  • response_model_exclude_none=True

as described in the Pydantic docs for exclude_defaults and exclude_none.

Data with values for fields with defaults

But if your data has values for the model’s fields with default values, like the item with ID bar:

  1. {
  2. "name": "Bar",
  3. "description": "The bartenders",
  4. "price": 62,
  5. "tax": 20.2
  6. }

they will be included in the response.

Data with the same values as the defaults

If the data has the same values as the default ones, like the item with ID baz:

  1. {
  2. "name": "Baz",
  3. "description": None,
  4. "price": 50.2,
  5. "tax": 10.5,
  6. "tags": []
  7. }

FastAPI is smart enough (actually, Pydantic is smart enough) to realize that, even though description, tax, and tags have the same values as the defaults, they were set explicitly (instead of taken from the defaults).

So, they will be included in the JSON response.

Tip

Notice that the default values can be anything, not only None.

They can be a list ([]), a float of 10.5, etc.

response_model_include and response_model_exclude

You can also use the path operation decorator parameters response_model_include and response_model_exclude.

They take a set of str with the name of the attributes to include (omitting the rest) or to exclude (including the rest).

This can be used as a quick shortcut if you have only one Pydantic model and want to remove some data from the output.

Tip

But it is still recommended to use the ideas above, using multiple classes, instead of these parameters.

This is because the JSON Schema generated in your app’s OpenAPI (and the docs) will still be the one for the complete model, even if you use response_model_include or response_model_exclude to omit some attributes.

This also applies to response_model_by_alias that works similarly.

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: float = 10.5
  10. items = {
  11. "foo": {"name": "Foo", "price": 50.2},
  12. "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
  13. "baz": {
  14. "name": "Baz",
  15. "description": "There goes my baz",
  16. "price": 50.2,
  17. "tax": 10.5,
  18. },
  19. }
  20. @app.get(
  21. "/items/{item_id}/name",
  22. response_model=Item,
  23. response_model_include={"name", "description"},
  24. )
  25. async def read_item_name(item_id: str):
  26. return items[item_id]
  27. @app.get("/items/{item_id}/public", response_model=Item, response_model_exclude={"tax"})
  28. async def read_item_public_data(item_id: str):
  29. return items[item_id]

Tip

The syntax {"name", "description"} creates a set with those two values.

It is equivalent to set(["name", "description"]).

Using lists instead of sets

If you forget to use a set and use a list or tuple instead, FastAPI will still convert it to a set and it will work correctly:

  1. from typing import Optional
  2. from fastapi import FastAPI
  3. from pydantic import BaseModel
  4. app = FastAPI()
  5. class Item(BaseModel):
  6. name: str
  7. description: Optional[str] = None
  8. price: float
  9. tax: float = 10.5
  10. items = {
  11. "foo": {"name": "Foo", "price": 50.2},
  12. "bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
  13. "baz": {
  14. "name": "Baz",
  15. "description": "There goes my baz",
  16. "price": 50.2,
  17. "tax": 10.5,
  18. },
  19. }
  20. @app.get(
  21. "/items/{item_id}/name",
  22. response_model=Item,
  23. response_model_include=["name", "description"],
  24. )
  25. async def read_item_name(item_id: str):
  26. return items[item_id]
  27. @app.get("/items/{item_id}/public", response_model=Item, response_model_exclude=["tax"])
  28. async def read_item_public_data(item_id: str):
  29. return items[item_id]

Recap

Use the path operation decorator’s parameter response_model to define response models and especially to ensure private data is filtered out.

Use response_model_exclude_unset to return only the values explicitly set.