Sometimes you want to send only some parts of your data to users. Exclude and include help you pick what to show or hide in the response.
Response model exclude and include in FastAPI
from fastapi import FastAPI from pydantic import BaseModel from typing import Optional class User(BaseModel): id: int name: str email: Optional[str] = None password: Optional[str] = None app = FastAPI() @app.get("/user", response_model=User, response_model_exclude={"password"}) async def get_user(): return User(id=1, name="Alice", email="alice@example.com", password="secret")
response_model_exclude hides fields from the response.
response_model_include shows only listed fields.
@app.get("/user", response_model=User, response_model_exclude={"password"}) async def get_user(): return User(id=1, name="Alice", email="alice@example.com", password="secret")
@app.get("/user", response_model=User, response_model_include={"id", "name"}) async def get_user(): return User(id=1, name="Alice", email="alice@example.com", password="secret")
@app.get("/user", response_model=User, response_model_exclude_unset=True) async def get_user(): return User(id=1, name="Alice")
This FastAPI app defines a User model with four fields. The endpoint /user returns a User but excludes the password field from the response. So users will see id, name, and email only.
from fastapi import FastAPI from pydantic import BaseModel from typing import Optional class User(BaseModel): id: int name: str email: Optional[str] = None password: Optional[str] = None app = FastAPI() @app.get("/user", response_model=User, response_model_exclude={"password"}) async def get_user(): return User(id=1, name="Alice", email="alice@example.com", password="secret")
You can use sets or dictionaries for exclude/include to specify fields.
Exclude and include can be combined with nested models using dot notation or dictionaries.
response_model_exclude_unset hides fields not set in the returned object, useful for partial updates.
Exclude and include control what fields appear in API responses.
Use response_model_exclude to hide fields like passwords.
Use response_model_include to show only specific fields.
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
