Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 38 ยท Integration with FastAPI

FastAPI Response Models

Control what a FastAPI endpoint returns with response_model. Hide private fields, shape lists, exclude unset values, use inheritance for input and output models and set status codes.

Validating what comes in protects your program. Controlling what goes out protects your users. A database row has a password hash, internal flags and timestamps; the API response should show only what the client needs. FastAPI does this with a response model: a Pydantic model that describes the output. Whatever your function returns is validated against it, and every field not in the model is dropped.

response_model drops private fields

Return a rich object (a dictionary, an ORM row, a model with more fields) and name the public shape in the decorator.

Python Hiding the password hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The response contains only id and name. The model acts as an allow-list: forgetting to remove a sensitive field from your row object cannot leak it.

flowchart LR
    F["your function<br/>returns any object"] --> V{"validate against<br/>response_model"}
    V -->|extra fields| D["dropped"]
    V -->|fields kept| S["serialize to JSON"]
    V -->|invalid| E["500 server error<br/>(your bug)"]

The response model both filters and checks your output.

Return type annotations

Since FastAPI 0.89 you can use the return annotation instead of response_model: async def get_user() -> UserOut:. FastAPI uses it for filtering and for the docs. Keep response_model=... for the cases where your function returns something that is not the model, such as a dictionary or an ORM object that you want filtered.

Python Return annotation and input/output pair

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pattern is a small family of models that share a base: UserIn adds the password the client sends, UserInDB adds the stored hash, UserOut adds the public id. Shared fields live in UserBase once. The route returns the database model and the annotation trims it to UserOut. status_code=201 sets the success status.

Lists, optional results and unset values

A response model can be a list (list[UserOut]) or a wrapper model with paging info. Two options help when fields are optional:

  • response_model_exclude_unset=True leaves out fields that were never set, so a response does not list dozens of null values.
  • response_model_exclude_none=True leaves out None values.
  • response_model_include={...} / response_model_exclude={...} pick fields per route. They are handy, but separate models are easier to read and test.
Python Lists and exclude_unset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Several possible responses

A route may answer with different shapes. Declare the alternatives with responses= so they appear in the docs, and give each error a model:

Python Documenting error responses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Serialization details

The response goes through the same machinery as model_dump(mode="json"), so dates become ISO strings, Decimal values become strings or numbers by your model's rules, and SecretStr stays masked. If you also configured aliases, FastAPI uses them in the output by default (response_model_by_alias=True), the opposite of a plain model_dump().

FastAPI validates the returned value against the response model again. For huge responses this costs time. If your function already returns a finished UserOut, the return annotation still triggers serialization with Pydantic's fast Rust core, which is usually cheap. Measure before optimizing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to fields that are not in the response model?

    The response model works as an allow-list; extra data such as a password hash is dropped.
  2. 2. Which pattern avoids repeating shared fields in UserIn, UserInDB and UserOut?

    A UserBase with name and email, extended by the input, database and output models, keeps the shared part in one place.
  3. 3. What does response_model_exclude_unset=True do?

    Fields with defaults that were not explicitly provided are left out, keeping responses compact.
  4. 4. How do you tell the docs that an endpoint can answer 404 with a particular body?

    The responses argument adds alternative status codes and their models to the OpenAPI document.

Summary

  • response_model (or a return annotation) validates and filters what a route returns.
  • Build model families with a shared base: input, stored and output variants.
  • Use exclude_unset, exclude_none, lists and wrapper models to shape responses; document other outcomes with responses=.
  • Response serialization follows Pydantic's JSON mode, and aliases apply by default.

Next: FastAPI Errors, Dependencies and Settings