Discover how to protect sensitive data effortlessly in your API responses!
Why Response model exclude and include in FastAPI? - Purpose & Use Cases
Imagine building an API that returns user data, but you want to hide sensitive info like passwords or only show certain fields depending on the request.
Manually removing or adding fields in every response is tiring, error-prone, and easy to forget. It leads to inconsistent data and security risks.
FastAPI's response model exclude and include options let you easily control which fields appear in the output, keeping your code clean and safe.
user_dict = user.__dict__ if 'password' in user_dict: del user_dict['password'] return user_dict
return UserResponse.from_orm(user).dict(exclude={'password'})
You can flexibly customize API responses without rewriting code or risking sensitive data leaks.
Showing a public profile with only username and bio, while hiding email and password fields automatically.
Manually filtering response data is slow and risky.
FastAPI's exclude/include cleanly controls output fields.
This improves security and keeps code simple.
Practice
response_model_exclude parameter do in FastAPI?Solution
Step 1: Understand the purpose of
This parameter is used to remove or hide certain fields from the response data.response_model_excludeStep 2: Compare with other parameters
Unlikeresponse_model_includewhich shows only specified fields,response_model_excludehides specified fields.Final Answer:
It hides specified fields from the API response. -> Option BQuick Check:
Exclude means hide fields [OK]
- Confusing exclude with include
- Thinking it changes data types
- Assuming it validates data
password from a FastAPI response model?Solution
Step 1: Identify correct data type for exclude
Theresponse_model_excludeparameter expects a set or dict of field names to exclude.Step 2: Check syntax correctness
Using a set like{'password'}is valid; lists are not accepted and cause ValueError.Final Answer:
response_model_exclude={'password'} -> Option CQuick Check:
Exclude uses set or dict of fields [OK]
- Using include instead of exclude
- Using a list ['password'] instead of set {'password'}
- Passing a string instead of set
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
username: str
email: str
password: str
@app.get('/user', response_model=User, response_model_exclude={'password'})
def get_user():
return User(id=1, username='alice', email='alice@example.com', password='secret')
What will the API response JSON include?Solution
Step 1: Understand
Theresponse_model_excludeeffectpasswordfield is excluded from the response, so it will not appear in the JSON output.Step 2: Identify included fields
All other fieldsid,username, andemailremain and appear in the response.Final Answer:
{"id": 1, "username": "alice", "email": "alice@example.com"} -> Option AQuick Check:
Excluded field missing in output [OK]
- Expecting excluded fields to appear
- Confusing exclude with include
- Ignoring response_model parameter
@app.get('/item', response_model=Item, response_model_include=['name', 'price'])
def get_item():
return Item(id=5, name='Book', price=10.0, description='A good read')
But the endpoint raises a ValueError instead of returning the filtered response. What is the likely error?Solution
Step 1: Check expected type for
FastAPI expectsresponse_model_includeresponse_model_includeto be a set or dict of fields, not a list.Step 2: Understand why list fails
Passing a list causes a ValueError because Pydantic requires set or dict for include/exclude.Final Answer:
Using a list instead of a set forresponse_model_include-> Option AQuick Check:
Include needs set or dict [OK]
- Using list instead of set for include
- Expecting include to filter with wrong type
- Not checking parameter types
id and username fields included, but exclude password and email. Which is the best way to do this in FastAPI?Solution
Step 1: Understand include vs exclude
Including onlyidandusernameis simpler and clearer than excluding fields.Step 2: Avoid mixing include and exclude
Using both can cause confusion or unexpected results; better to use include to specify exactly what to show.Final Answer:
Useresponse_model_include={'id', 'username'}to include only needed fields. -> Option DQuick Check:
Include specifies exact fields to show [OK]
- Mixing include and exclude causing conflicts
- Excluding fields but missing some unwanted fields
- Returning raw dict instead of model
Ready to prove it?
Pass the test and this pattern moves unknown
