skip to content

A FastAPI endpoint sets response_model_exclude_unset=True, yet returning the stored user model still sends every default field; why, and how do you fix it?

level: seniorimportance: should knowfreq 25%

answer

  1. unset is decided after validation
  2. a different class gets rebuilt
  3. from_attributes reads every field
  4. dump with exclude_unset first

basics

~20 s

FastAPI rebuilds a returned object of another class into the response model by reading its attributes, so every field it finds counts as set and nothing is excluded. Return the response model itself or a subclass, or return stored.model_dump(exclude_unset=True).

solid answer

~40 s

`response_model_exclude_unset=True` is applied to the value *after* FastAPI validates it against the response model. An instance of the response model or a subclass passes through with its record of which fields were set, and a dict yields only the keys it has. A stored `UserInDB` is a different class, so FastAPI validates it with `from_attributes=True`: it reads every attribute `UserOut` declares, defaults included, and each one becomes an explicitly set field. The fix is to return something that still carries the unset information: `stored.model_dump(exclude_unset=True)`, the response model built from only the set fields, or a subclass instance. When the real intent is dropping defaults or nulls, `response_model_exclude_defaults` or `response_model_exclude_none` say that directly.

code

python · 37 lines
python
from typing import Any

from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel


class UserOut(BaseModel):
    username: str
    bio: str | None = None
    theme: str = "light"


class UserInDB(BaseModel):
    username: str
    hashed_password: str
    bio: str | None = None
    theme: str = "light"


app = FastAPI()


@app.get("/a", response_model=UserOut, response_model_exclude_unset=True)
async def trap() -> Any:
    return UserInDB(username="ada", hashed_password="x")


@app.get("/b", response_model=UserOut, response_model_exclude_unset=True)
async def fixed() -> Any:
    stored = UserInDB(username="ada", hashed_password="x")
    return stored.model_dump(exclude_unset=True)


client = TestClient(app)
print(client.get("/a").json())  # {'username': 'ada', 'bio': None, 'theme': 'light'}
print(client.get("/b").json())  # {'username': 'ada'}

go deeper

for a junior

Recall that response_model_exclude_unset=True leaves out fields that kept their default instead of being set when the model was created.

for a middle

Explain that FastAPI validates the returned value into the response model first, and that the unset record comes from that validated instance.

for a senior

Diagnose the from_attributes rebuild that marks every field set, and fix it with model_dump(exclude_unset=True), a subclass return, or exclude_defaults or exclude_none.

for a principal

Prefer explicit output models over the include, exclude and exclude_unset family of flags, so the documented schema and the sent body cannot drift apart.

## What "unset" means here `response_model_exclude_unset=True` is a path operation decorator parameter. It asks FastAPI to leave out of the JSON every field of the response model that was **not explicitly set**, meaning it took its default value when the model instance was created. Pydantic keeps that record per instance, the model's set of fields provided at construction. FastAPI's docs show it with a stored item that only has `name` and `price`: the defaults for `description`, `tax` and `tags` are omitted. The catch is *which instance* that record belongs to. FastAPI does not look at the object your function returned. It looks at the value produced by **validating** that object against the response model. ## How the returned object is validated FastAPI validates the returned value with Pydantic's `validate_python(..., from_attributes=True)` and then serializes the result with the `exclude_unset` flag. What survives depends on what was returned: | Returned value | After validation | Unset defaults omitted? | |---|---|---| | instance of the response model | same instance, set record kept | yes | | instance of a subclass of it | same instance, set record kept | yes | | dict with only some keys | new instance from those keys | yes | | instance of an unrelated model | new instance read attribute by attribute | **no** | | ORM row or other object | new instance read attribute by attribute | **no** | When a different class is read with `from_attributes`, each field the response model declares that exists as an attribute is read, defaults included. Each one read is passed into the new instance, so it counts as **set**. A stored model or a row normally has every one of those attributes. `exclude_unset` then has nothing to exclude. The same happens with a record loaded from a database: every column has a value, so nothing on it was ever unset in Pydantic's sense. ## Fixes, from most to least direct 1. **Dump before returning.** `return stored.model_dump(exclude_unset=True)` gives FastAPI a dict of only the fields that were set on the stored model; validation builds the response model from those keys, and the rest stay unset. Extra keys such as `hashed_password` are still filtered by the response model. 2. **Return the response model or a subclass of it.** If the stored model subclasses the output model, its set record travels with it. 3. **Say what you mean.** If the goal is "omit fields equal to their default", use `response_model_exclude_defaults=True`; if it is "omit nulls", use `response_model_exclude_none=True`. Both work on values, so they behave the same whatever object was returned. ## A related shortcut with a cost `response_model_include` and `response_model_exclude` take a set of field names and trim the output of a single model. They are quick, but the **OpenAPI schema still documents the full response model**, so clients are told a field exists that never arrives. `response_model_by_alias` has the same mismatch. FastAPI's docs recommend separate output models instead, so the filter and the documented schema agree. ## The worked example Take an output model `UserOut` with `username`, `bio: str | None = None` and `theme: str = "light"`, and a stored model `UserInDB` with the same fields plus `hashed_password`. The endpoint sets `response_model=UserOut` and `response_model_exclude_unset=True`. - Returning `UserInDB(username="ada", hashed_password="x")` sends `username`, `bio: null` and `theme: "light"`. The stored model is not a `UserOut`, so FastAPI reads all three declared attributes, and all three are set on the new instance. - Returning `stored.model_dump(exclude_unset=True)` sends only `username`. The dict holds `username` and `hashed_password`; validation keeps `username`, ignores the hash, and leaves `bio` and `theme` unset, so they are omitted. In both cases the hash is filtered out. Only the unset handling differs. ## How to spot it - The JSON from a PATCH-style or sparse endpoint is full of `null` and default values that nobody set. - A test that returns a hand-built response model passes, while the real handler, which returns a stored model or row, does not. - Switching the return to a dict "fixes" it, which points straight at the validation step. None of this is a FastAPI bug. `from_attributes` is what lets an endpoint return ORM rows at all; the side effect is that an object read that way has no notion of unset fields.

  • Would a stored model that subclasses the response model avoid the problem?
    Yes. An instance of a subclass passes Pydantic's validation as it is, so its record of set fields survives and `response_model_exclude_unset` omits the defaults. The subclass's extra fields, such as a hash, are still left out because FastAPI serializes by the response model's declared fields.
  • When is response_model_exclude_defaults the better choice?
    When the client should not see values equal to the field default, however they got there, for example when reading records from storage where nothing is ever unset. It compares values, so it gives the same result for a dict, a model or a row. Note that it also drops a default value someone set explicitly.

A paper form records which boxes you filled in by hand. Copy someone's finished form box by box onto a fresh one, and every box on the copy looks hand-filled, including the ones they left at the printed default.

  • exclude_unset looks at the object the handler returned, not the validated copy.
  • Returning an ORM row with exclude_unset omits columns that hold their default.
  • The fix is setting from_attributes=True in the response model's config.
  • response_model_exclude changes the OpenAPI schema to match the trimmed output.
  • exclude_unset and exclude_defaults always give the same output.