Full answer
After your function returns, FastAPI converts the value to the response_model type, filters fields that are not in the model (so a password_hash on the returned object never leaks if the model omits it), and serialises it.
Options on the decorator:
response_model_exclude_unset=True: omit fields that were not explicitly set when the returned object was created, so defaults do not appear. Useful for sparse PATCH-style responses.response_model_exclude_defaults=True: omit fields whose value equals the default.response_model_exclude_none=True: drop keys whose value isNone.response_model_include={"name"}andresponse_model_exclude={"email"}: a quick way to trim, but it hides the real contract, and the OpenAPI schema still shows the full model.response_model_by_alias=True(the default): fields appear under their alias (Field(alias="rollNo")). Set it to False to use Python names.
Guidance:
- For a public API, define explicit models (
StudentPublic,StudentAdmin) and use them asresponse_model, because the docs, client generators and tests then match the real output. exclude_unsetworks only when the returned object carries the "set" information, for example a Pydantic model instance ordictconverted to a model. For ORM objects every attribute counts as set.- The return type annotation (
-> StudentPublic) now also serves as the response model whenresponse_modelis omitted. - Filtering costs a validation pass; for very hot endpoints, return the right shape directly and set
response_model=None.
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class StudentPublic(BaseModel):
name: str
roll_no: str = Field(alias="rollNo")
nickname: str | None = None
grade: str = "C"
DB = {"name": "Asha", "rollNo": "BCA-1", "password_hash": "secret"} # a row with an extra private column
@app.get("/full", response_model=StudentPublic)
def full():
return DB # password_hash is filtered out
@app.get("/unset", response_model=StudentPublic, response_model_exclude_unset=True)
def unset():
return {"name": "Asha", "rollNo": "BCA-1"} # only these keys were set
@app.get("/none", response_model=StudentPublic, response_model_exclude_none=True)
def none():
return DB
@app.get("/names", response_model=StudentPublic, response_model_by_alias=False)
def names():
return DB
@app.get("/include", response_model=StudentPublic, response_model_include={"name", "grade"})
def include():
return DB
c = TestClient(app)
for path in ("full", "unset", "none", "names", "include"):
print(path, c.get(f"/{path}").json())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): full {'name': 'Asha', 'rollNo': 'BCA-1', 'nickname': None, 'grade': 'C'} unset {'name': 'Asha', 'rollNo': 'BCA-1'} none {'name': 'Asha', 'rollNo': 'BCA-1', 'grade': 'C'} names {'name': 'Asha', 'roll_no': 'BCA-1', 'nickname': None, 'grade': 'C'} include {'name': 'Asha', 'grade': 'C'}
Key points
- response_model filters and serialises the return value
- exclude_unset and exclude_none shrink output
- include and exclude lists hide the real contract in docs
- by_alias controls alias use in output
- Prefer separate public and admin models
Common mistakes
- Returning ORM or dict objects with sensitive fields and no response model
- Returning a model instance whose attributes use Python names when the response model validates by alias
- Relying on include or exclude lists as the long-term contract
- Expecting exclude_unset to work with ORM objects
- Forgetting that aliases appear in output by default
Follow-ups
- How does the return type annotation interact with response_model?
- When would you set response_model=None?
- How do you return different shapes for admins and users?
Tips
- Explain the filtering effect
- List the options
- Prefer explicit models