0
0
FastAPIframework~5 mins

Response model declaration in FastAPI

Choose your learning style9 modes available
Introduction

Response model declaration tells FastAPI what shape the output should have. It helps make sure your API sends data in the right format.

When you want to control what data your API sends back to users.
When you want to hide some internal data fields from the response.
When you want to automatically generate clear API documentation.
When you want to validate the response data before sending it.
When you want to keep your API responses consistent and easy to understand.
Syntax
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

class ResponseModel(BaseModel):
    field1: str
    field2: int

app = FastAPI()

@app.get("/items/{item_id}", response_model=ResponseModel)
async def read_item(item_id: int):
    return {"field1": "value", "field2": 123, "extra": "ignored"}

The response_model parameter in the route decorator sets the expected output format.

Extra fields not in the model are ignored by default when sending the response.

Examples
This defines a response model with two fields: username and email.
FastAPI
from pydantic import BaseModel

class UserResponse(BaseModel):
    username: str
    email: str
The password field is not in the response model, so it will be excluded from the output.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
    return {"username": "alice", "email": "alice@example.com", "password": "secret"}
You can also declare response models for lists or other types.
FastAPI
@app.get("/numbers", response_model=list[int])
async def get_numbers():
    return [1, 2, 3, 4]
Sample Program

This FastAPI app returns an item with only the name and price fields in the response. The secret_code is hidden because it is not in the response model.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

class ItemResponse(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.get("/items/{item_id}", response_model=ItemResponse)
async def read_item(item_id: int):
    # Simulate fetching item with extra data
    item = {"name": "Book", "price": 12.99, "secret_code": "XYZ123"}
    return item
OutputSuccess
Important Notes

Response models help keep your API responses clean and secure by excluding unwanted data.

They also improve API docs by showing exactly what data clients can expect.

Summary

Response model declaration defines the shape of data your API sends back.

It hides extra fields and validates output automatically.

Using response models makes your API easier to use and safer.