Under The Hood
backend fastapi FastAPI 0.100+ (Pydantic v2)

response_model, response_model_exclude_unset, and Data Serialization

Last updated
Prerequisites:
Pydantic v2 BaseModel
FastAPI route decorators
  • fastapi
  • response-model
  • serialization
  • pydantic
  • security
  • data-filtering

Read at your depth

The practical view

Use `response_model=MyResponseSchema` in route decorators to filter output: `@app.get('/users/{id}', response_model=UserPublic)`. Even if your function returns a full database entity containing `password_hash`, FastAPI automatically filters the data so only fields declared in `UserPublic` are serialized. Modifiers like `response_model_exclude_unset=True` ensure default values that were not explicitly set are excluded from the JSON output.

The same idea in other frameworks

fastapi equivalent
`@app.get('/users', response_model=UserOut)` or `def get_user() -> UserOut:`.

Legacy vs modern

Unfiltered Return (Password Leak) vs response_model Filter

Returning raw DB models leaks sensitive password hashes; `response_model` enforces an egress security boundary.

before → after
Unfiltered Database Return
return user_db_object // ❌ Leaks hashed_password and internal flags to public API
response_model Security Boundary
@app.get('/user/{id}', response_model=UserPublic) // ✅ NEW: Filters private fields

Interview gotchas

Context

Interviewers test your precision with JSON serialization flags in FastAPI.

The mechanical answer

`response_model_exclude_unset=True` excludes fields that were **not explicitly set** when creating the model instance (it only serializes data explicitly provided in the dictionary/ORM object). `response_model_exclude_defaults=True` excludes any field whose value matches its declared default value, regardless of whether it was set.

Trap

`response_model_exclude_unset` is essential for `PATCH` endpoints where you only want to return fields that were modified.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.