Performance: Response model exclude and include
This affects the size of the JSON response sent to the client, impacting network load and client rendering speed.
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'}) async def get_user(): user = User(id=1, username='alice', email='alice@example.com', password='secret') return user
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) async def get_user(): user = User(id=1, username='alice', email='alice@example.com', password='secret') return user
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Full response with all fields | N/A | N/A | Higher due to larger JSON parsing | [X] Bad |
| Response with exclude/include to limit fields | N/A | N/A | Lower due to smaller JSON parsing | [OK] Good |
response_model_exclude parameter do in FastAPI?response_model_excluderesponse_model_include which shows only specified fields, response_model_exclude hides specified fields.password from a FastAPI response model?response_model_exclude parameter expects a set or dict of field names to exclude.{'password'} is valid; lists are not accepted and cause ValueError.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?response_model_exclude effectpassword field is excluded from the response, so it will not appear in the JSON output.id, username, and email remain and appear in the response.@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?response_model_includeresponse_model_include to be a set or dict of fields, not a list.response_model_include -> Option Aid and username fields included, but exclude password and email. Which is the best way to do this in FastAPI?id and username is simpler and clearer than excluding fields.response_model_include={'id', 'username'} to include only needed fields. -> Option DPass the test and this pattern moves unknown