skip to content

In FastAPI, how do you declare a paginated list-of-users endpoint so every returned row is validated and stripped to the public fields?

level: middleimportance: should knowfreq 45%

answer

  1. the model wraps the collection
  2. list[UserOut] inside a page model
  3. rows read by attribute
  4. one bad row fails the response

basics

~20 s

Declare the response model as list[UserOut] or a page model with items: list[UserOut]. FastAPI validates every item, reads ORM rows by attribute, and sends only UserOut's fields; one invalid row makes the whole response a 500.

solid answer

~30 s

I declare a page model, `class UserPage(BaseModel): items: list[UserOut]; total: int`, and set it as the response model, either `-> UserPage` or `response_model=UserPage` when the function returns a dict of rows. FastAPI validates the whole structure with `from_attributes=True`, so ORM rows inside `items` are read by attribute without any config on `UserOut`, and each item is serialized with only `UserOut`'s fields, which drops `hashed_password` from every row. A bare `list[UserOut]` works the same for an unpaginated endpoint. If any single row fails validation, FastAPI raises `ResponseValidationError` and the client gets a 500 rather than a partial page.

code

python · 42 lines
python
from typing import Annotated, Any

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


class UserOut(BaseModel):
    id: int
    username: str


class UserPage(BaseModel):
    items: list[UserOut]
    total: int


class UserRow:
    """What an ORM query hands back: a plain object with attributes."""

    def __init__(self, id: int, username: str, hashed_password: str) -> None:
        self.id = id
        self.username = username
        self.hashed_password = hashed_password


ROWS = [UserRow(i, f"user{i}", f"hash{i}") for i in range(1, 51)]

app = FastAPI()


@app.get("/users", response_model=UserPage)
async def list_users(
    offset: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(ge=1, le=100)] = 2,
) -> dict[str, Any]:
    return {"items": ROWS[offset : offset + limit], "total": len(ROWS)}


client = TestClient(app)
print(client.get("/users").json())
# {'items': [{'id': 1, 'username': 'user1'}, {'id': 2, 'username': 'user2'}], 'total': 50}

go deeper

for a junior

Remember that list[UserOut] or a page model with items: list[UserOut] is a valid response model, and that each item is filtered to UserOut's fields.

for a middle

Explain from_attributes reading nested rows, all-or-nothing validation that turns one bad row into a 500, and how a union is documented as anyOf.

for a senior

Match output models to what storage holds, nullable columns included, and bound page sizes so per-item validation on the event loop stays cheap.

for a principal

Make a shared page model the team's list contract so every listing is validated, filtered and documented the same way.

## Collections are response models too A **response model** does not have to be a single Pydantic class. FastAPI accepts anything that is a valid Pydantic field type, so collections and wrappers work the same way as one object: - `list[UserOut]` for a plain JSON array of users. - A **page model** such as `UserPage` with `items: list[UserOut]` and `total: int`, for paginated results with metadata. - `dict[str, UserOut]` or `dict[str, float]` when the keys are not known in advance. - A union such as `Union[PlaneItem, CarItem]` when one endpoint can return one of several shapes. Each can be declared as the return annotation or as `response_model=` on the decorator. In the page example, the function returns a plain dict of rows, so it is annotated with that and `response_model=UserPage` decides what is sent. ## What FastAPI does with each row When the function returns, FastAPI validates the value against the response model and then serializes it: 1. **Validation reads by attribute.** FastAPI calls Pydantic's validator with `from_attributes=True`, and it applies to nested values too. ORM row objects inside `items` are therefore read field by field without setting `from_attributes` on `UserOut` itself. 2. **Every item is checked.** A row missing a required field, or holding a value the field type rejects, fails validation. 3. **Every item is filtered.** Serialization uses the declared type, so each element carries only `UserOut`'s fields. A `hashed_password` attribute on the row never reaches the array. 4. **The schema shows the collection.** OpenAPI documents the page model with an array of `UserOut`, so clients see the same shape. ## Building the page A paginated endpoint usually combines three pieces: 1. **Bounded query parameters**, such as `offset: Annotated[int, Query(ge=0)] = 0` and `limit: Annotated[int, Query(ge=1, le=100)] = 20`, so a client cannot ask for every row at once. 2. **The data and the total**, fetched from storage as row objects and a count. 3. **A return value that matches the page model's shape**, here `{"items": rows, "total": count}`. FastAPI turns it into a `UserPage`, reading each row into a `UserOut`. Because the handler returns a dict and not a `UserPage` instance, annotating it `-> UserPage` would upset a type checker. Declaring `response_model=UserPage` and annotating the function with what it really returns keeps both FastAPI and the type checker correct. ## When one row is bad Validation of the response is all or nothing. If one of twenty rows lacks a required field, FastAPI raises `ResponseValidationError` for the whole response and the client receives a **500 Internal Server Error**. It does not drop the bad row, fill it with `null`, or return a 422; a 422 is reserved for invalid *requests*. That is deliberate: FastAPI treats data that cannot match the declared output as a bug in the application, not something to send half-right. In practice this means the output model has to match what storage really holds. If a column can be null, the output field must allow `None`; otherwise one legacy row turns a whole listing into a 500. ## Unions and arbitrary dicts | Declaration | Response | OpenAPI | |---|---|---| | `list[UserOut]` | JSON array, each item filtered | array of `UserOut` | | page model with `items: list[UserOut]` | object with filtered items | object schema | | `Union[PlaneItem, CarItem]` | the member Pydantic's union rules pick | `anyOf` of both | | `dict[str, float]` | object with free keys | `additionalProperties` | A union is validated by Pydantic's union rules, so give members something that tells them apart, such as a `Literal` type field. In `response_model=` the union is passed as a value; the docs use `typing.Union` there, while in an annotation the `X | Y` spelling is the natural one. ## Cost on large pages Validation and serialization run for every item on every request: - In an `async def` path operation, FastAPI validates the response on the event loop, so a very large page delays other requests while it is checked. - In a `def` path operation, FastAPI runs that validation in the thread pool. - Bounding the page with `Query(le=100)` on `limit` keeps the work per request predictable. Pagination keeps both the payload and that validation cost small, which is one more reason to page list endpoints instead of returning every row.

  • Does UserOut need model_config = ConfigDict(from_attributes=True) for FastAPI to read ORM rows?
    Not for the response. FastAPI validates returned data with `from_attributes=True` itself, so rows are read by attribute anyway. You still need it on the model when your own code calls `UserOut.model_validate(row)` outside FastAPI's response handling.
  • Why not use response_model_exclude={"hashed_password"} on a list of the stored model instead?
    On a list response model that flat set does nothing: for a list, Pydantic reads exclusion keys as item indices or `__all__`, so the hash still goes out unless you write `{"__all__": {"hashed_password"}}`. Even then the OpenAPI schema documents the stored model with its hash field. A separate output model avoids both traps.

  • A list return type is just documentation; FastAPI does not validate list items.
  • response_model_exclude={"hashed_password"} strips the hash from every item of a list response.
  • One invalid row is skipped and the rest of the page is still sent.
  • A bad row in the response comes back to the client as a 422.
  • UserOut must set from_attributes=True or FastAPI cannot read ORM rows.
  • Filtering applies to the top-level model but not to nested items.