Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 50 ยท Pydantic models and validation

Response models and nested data

Use response_model in FastAPI to filter output, hide password fields, split Create/Read/Update schemas, nest models, return lists and use exclude_unset.

An endpoint that returns whatever object it has is a leak waiting to happen. The database row has a password_hash, the internal object has a cost_price, and one careless return user publishes both. FastAPI's answer is the response model: you declare the shape of the output, and FastAPI validates and filters every response to match it.

In this lesson you will use response_model, split your schemas into input and output classes, nest models inside each other, return lists, and control which fields appear. The examples build on Pydantic models for APIs and field constraints.

What response_model does

Filters Fields not in the model are dropped.
Validates The returned data must fit the model.
Documents The schema appears in OpenAPI.

Your function may return more than the client ever sees.

1 / 2

Filtering output with response_model

Pass response_model= to the decorator. FastAPI runs the returned value through that model before serializing it, so extra fields never leave the server.

Python Hiding a secret field

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 /leaky route publishes the hash; /safe quietly drops everything the model doesn't name. That filtering is the main reason to always declare a response model for anything that touches user data.

You can also use a return type annotation instead: async def safe() -> UserPublic:. FastAPI treats it as the response model. Use the decorator argument when the function returns something else, such as a database object or a dict, that only becomes the response model after filtering; use the annotation when you really return that type.

Input and output models

Clients send a password when they register, but must never receive it. One class can't serve both directions, so use separate schemas. A tidy pattern is a shared base with the common fields, then one subclass per direction.

Python Create, Read and the base class

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 stored dictionary (a stand-in for a database row, with a toy "hash" you must never use for real) contains the password, but neither response does. Real hashing comes in password hashing.

The reversed string above is only a placeholder so the example stays short. Never invent your own hashing; use a slow, salted password hash.

Nested models

Models can contain other models and lists of them. The response filtering applies at every level, so a nested secret is dropped too.

Python Nested models and list 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.

Use list[PostOut] as the response model for collections. Avoid returning a bare list from a real API when you can: wrapping it in an object such as {"items": [...], "total": 2} lets you add pagination fields later without breaking clients.

exclude_unset, exclude_defaults and exclude_none

Sometimes a field with a default should not appear unless it was actually set. The decorator accepts response_model_exclude_unset=True, response_model_exclude_defaults=True and response_model_exclude_none=True.

Python Trimming optional fields

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.

Compare the rows for item b. exclude_unset keeps every field because the data explicitly sets them all; exclude_defaults drops the ones that equal the default; exclude_none removes only the null. Use exclude_unset carefully: it makes the response shape depend on how the data was built, which can surprise clients. It is more useful when reading partial input, which you'll do in partial updates.

include and exclude

For a quick one-off you can name fields directly with response_model_include={"name"} or response_model_exclude={"tax"}. Prefer a dedicated model when the shape is used more than once: a separate class is documented in OpenAPI, while include and exclude sets are easy to forget.

If the data you return does not fit the response model, for example a required field is missing, FastAPI raises a ResponseValidationError and the client gets a 500. That is a bug in your server, not in the request, so it is reported as a server error.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens to a field the endpoint returns that is not part of the response model?

    The response model filters the output, which is how you keep secrets such as password hashes out of responses.
  2. 2. Why use separate UserCreate and UserRead models?

    Input and output differ, so one class per direction avoids accidental leaks and lets the server own fields such as ids.
  3. 3. How do you declare that an endpoint returns a list of PostOut objects?

    Use the standard list[...] generic; FastAPI validates every element.
  4. 4. What does response_model_exclude_none=True do?

    Only None values are dropped. exclude_defaults drops values equal to their defaults.
  5. 5. The data your endpoint returns is missing a required field of the response model. What does the client receive?

    That is a server-side bug, so FastAPI raises a ResponseValidationError and answers 500.

Summary

  • response_model (or a return annotation) validates and filters every response, keeping secrets private.
  • Split schemas by direction: a shared base, a Create class for input, a Read class for output.
  • Nested models and list[Model] are filtered at every level.
  • response_model_exclude_unset, _exclude_defaults and _exclude_none trim optional fields; include and exclude are quick one-offs.
  • A response that doesn't fit its model is a server error (500), not a client error.

Next: change existing data safely in PUT, PATCH and partial updates.