Lesson 16 of 45 ยท FastAPI Basics
Response Model - Return Type
Learn to declare response models using return type annotations and the response_model parameter for data validation, documentation, and filtering.
Open this lesson in the editor โWhat you'll learn
- Use return type annotations to declare response models
- Understand how FastAPI validates and filters response data
- Apply the response_model parameter for complex scenarios
- Create proper input and output models for data security
- Generate automatic API documentation with response schemas
Response Model - Return Type
๐ฏ What You'll Learn
- Use return type annotations to declare response models
- Understand how FastAPI validates and filters response data
- Apply the response_model parameter for complex scenarios
- Create proper input and output models for data security
- Generate automatic API documentation with response schemas
๐ Theory
You can declare the type used for the response by annotating the path operation function return type. You can use type annotations the same way you would for input data in function parameters, you can use Pydantic models, lists, dictionaries, scalar values like integers, booleans, etc.
FastAPI will use this return type to:
- Validate the returned data. If the data is invalid (e.g. you are missing a field), it means that your app code is broken, not returning what it should, and it will return a server error instead of returning incorrect data.
- Add a JSON Schema for the response, in the OpenAPI path operation. This will be used by the automatic docs and by automatic client code generation tools.
- Limit and filter the output data to what is defined in the return type. This is particularly important for security.
๐ง Key Concepts
Return Type Annotations
The simplest way to declare a response model is using return type annotations:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item) -> Item:
return item
@app.get("/items/")
async def read_items() -> list[Item]:
return [
{"name": "Portal Gun", "price": 42.0},
{"name": "Plumbus", "price": 32.0},
]
response_model Parameter
In some cases, you need to use the response_model parameter instead of return type annotations:
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
return item
This is useful when you want to return a dictionary or database object but declare it as a Pydantic model for documentation and validation.
Data Filtering and Security
FastAPI automatically filters the response data to match your declared model. This means if your function returns more data than declared in the response model, the extra data will be filtered out. This is crucial for security - you won't accidentally expose sensitive data.
๐ก Best Practices
- Always use return type annotations when possible for better editor support and type checking
- Use the
response_modelparameter when returning dictionaries or database objects - Create separate input and output models to avoid exposing sensitive data like passwords
- Use
list[Model]for endpoints that return arrays of objects - FastAPI will automatically generate comprehensive API documentation based on your response models
๐ Additional Resources
Hint
Use return type annotations like -> Item or the response_model parameter in decorators. FastAPI will automatically validate and filter the response data based on your model.
Now write it
The editor runs a real FastAPI server and grades your code against this lesson's own endpoints.
Start Response Model - Return Type