Response models define what data the API should return. They can also prevent sensitive fields from being exposed in the API response.
For example, a database user might contain a password, but you may not want to return the password to the client. A response model allows you to specify which fields should be included in the response.
Code
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserResponse(BaseModel):
name: str
email: str
@app.get("/users", response_model=UserResponse)
def get_user():
return {
"name": "Tarun",
"email": "tarun@example.com",
"password": "secret123"
}
Understanding the Code
First, create a Pydantic response model:
class UserResponse(BaseModel):
name: str
email: str
The response model defines the fields that should be returned by the API.
In this example, the response model contains only:
name
email
The endpoint uses the model with response_model:
@app.get("/users", response_model=UserResponse)
Even though the function returns a password field:
return {
"name": "Tarun",
"email": "tarun@example.com",
"password": "secret123"
}
the password is not included in the API response because it is not part of UserResponse.
Output
{
"name": "Tarun",
"email": "tarun@example.com"
}
The password field is excluded from the response.
Why Use Response Models?
Response models are useful for:
- Defining the structure of API responses
- Controlling which fields are returned
- Preventing sensitive fields from being exposed
- Keeping API responses consistent
For example, instead of returning all user information, you can define exactly what the client should receive:
class UserResponse(BaseModel):
name: str
email: str
Then use it in the endpoint:
@app.get("/users", response_model=UserResponse)
def get_user():
...
This ensures that the API response follows the defined response model.