Response model declaration tells FastAPI what shape the output should have. It helps make sure your API sends data in the right format.
Response model declaration in 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.
from pydantic import BaseModel class UserResponse(BaseModel): username: str email: str
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"}
@app.get("/numbers", response_model=list[int]) async def get_numbers(): return [1, 2, 3, 4]
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.
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
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.
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.
Practice
response_model in a FastAPI route?Solution
Step 1: Understand response_model role
Theresponse_modeltells FastAPI what data shape to send back, ensuring output matches a defined structure.Step 2: Differentiate from other parameters
It does not set status codes, validate requests, or define database models, which are separate concerns.Final Answer:
To define the shape and type of data the API sends back to the client -> Option BQuick Check:
response_model defines output data shape = D [OK]
- Confusing response_model with request body validation
- Thinking response_model sets HTTP status codes
- Assuming response_model defines database schema
Solution
Step 1: Recall FastAPI syntax for response model
The correct parameter name isresponse_modelin the route decorator.Step 2: Check each option
Only @app.get('/items', response_model=Item) uses the exact correct syntaxresponse_model=Item. Others use incorrect parameter names.Final Answer:
@app.get('/items', response_model=Item) -> Option DQuick Check:
Correct parameter name is response_model = C [OK]
- Using wrong parameter names like response or model_response
- Capitalizing parameter names incorrectly
- Omitting the response_model parameter
/user/1?
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
password: str
@app.get('/user/{user_id}', response_model=User)
def get_user(user_id: int):
return {"id": user_id, "name": "Alice", "password": "secret", "token": "abc123"}Solution
Step 1: Understand response_model filtering
Theresponse_model=Usertells FastAPI to return only fields defined inUsermodel, ignoring extra fields liketoken.Step 2: Analyze returned dictionary
The returned dict hasid,name,password, and extratoken. The extratokenis removed in output.Final Answer:
{"id": 1, "name": "Alice", "password": "secret"} -> Option CQuick Check:
response_model filters extra fields = A [OK]
- Expecting extra fields to appear in output
- Thinking extra fields cause errors
- Confusing input validation with output filtering
@app.get('/products', response_model=Product)
def get_products():
return [{"id": 1, "name": "Book"}, {"id": 2, "name": "Pen"}]
Assuming Product is a Pydantic model for a single product.Solution
Step 1: Check return type vs response_model
The function returns a list of products, butresponse_model=Productexpects a single product instance.Step 2: Identify mismatch consequences
This mismatch causes FastAPI to raise a validation error or incorrect output because the response model does not match the returned data type.Final Answer:
The route returns a list but response_model expects a single Product instance -> Option AQuick Check:
response_model type must match returned data type = A [OK]
- Returning list but using single model as response_model
- Ignoring type mismatch errors
- Assuming route path affects response_model
id and name fields, hiding email and password. Given this User model:
class User(BaseModel):
id: int
name: str
email: str
password: str
Which is the best way to declare the response model in your route to achieve this?Solution
Step 1: Understand response_model controls output fields
FastAPI uses the response_model to decide which fields to include in the output. Using the full User model will include all fields.Step 2: Create a new model with only desired fields
To hideemailandpassword, define a new Pydantic model with onlyidandnameand use it as the response_model.Final Answer:
Create a new Pydantic model with only id and name, then use it as response_model -> Option AQuick Check:
Use tailored model to expose only needed fields = B [OK]
- Expecting FastAPI to hide fields automatically without a tailored model
- Returning partial dict but using full model as response_model
- Setting response_model=None and filtering manually (less safe)
Ready to prove it?
Pass the test and this pattern moves unknown
