skip to content

In FastAPI, how do response_model and a return type annotation differ, and which one wins when a path operation declares both?

level: middleimportance: must knowfreq 60%

answer

  1. decorator parameter vs function signature
  2. one for FastAPI, one for tooling
  3. response_model takes priority
  4. response_model=None switches it off

basics

~20 s

Both declare the response model FastAPI validates, filters and documents. The return annotation also satisfies type checkers; response_model is a decorator parameter for when the function returns something else. If both are set, response_model wins; response_model=None disables it.

solid answer

~40 s

A return annotation like `-> UserOut` is the default way to declare the response model: FastAPI validates, filters and documents with it, and the editor checks the function against it. `response_model=` on the decorator does the same job when the function honestly returns a different type, such as a dict or a stored model, and it **takes priority** when both are present. A subclass trick often removes the need for it: annotate `-> UserBase` and return a `UserInDB` subclass; the type checker is happy and FastAPI still sends only `UserBase`'s fields. An annotation that is a `Response` class creates no response model, and `response_model=None` turns it off for annotations Pydantic cannot handle.

code

python · 47 lines
python
from typing import Any

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


class UserBase(BaseModel):
    username: str
    email: str


class UserInDB(UserBase):
    hashed_password: str


DB = {"ada": UserInDB(username="ada", email="[email protected]", hashed_password="x")}

app = FastAPI()


# 1. Return annotation only: a subclass passes the type checker,
#    and FastAPI still sends only UserBase's fields.
@app.get("/users/{username}")
async def read_user(username: str) -> UserBase:
    return DB[username]


# 2. Both declared: response_model wins; the annotation is for tooling.
@app.get("/raw/{username}", response_model=UserBase)
async def read_raw(username: str) -> dict[str, Any]:
    return DB[username].model_dump()


# 3. No response model at all: the annotation is left to the type checker.
@app.get("/go", response_model=None)
async def go(to_docs: bool = False) -> RedirectResponse | dict[str, str]:
    if to_docs:
        return RedirectResponse("/docs")
    return {"status": "ok"}


client = TestClient(app)
print(client.get("/users/ada").json())  # {'username': 'ada', 'email': '[email protected]'}
print(client.get("/raw/ada").json())    # {'username': 'ada', 'email': '[email protected]'}
print(client.get("/go").json())         # {'status': 'ok'}

go deeper

for a junior

Know both spellings: a return annotation such as -> UserOut, or response_model=UserOut on the decorator, and that either one makes FastAPI validate and filter the output.

for a middle

Explain the priority rule, the subclass trick with a base-class annotation, and why a Response-plus-dict union fails at startup until response_model=None is set.

for a senior

Show the cost of response_model=None and -> Any: no filtering or schema in the first, no type checking of the handler in the second, so neither should become a habit.

for a principal

Set the team default: honest return annotations, response_model only where the sent type differs, and response_model=None treated as a reviewed exception because it removes the output filter.

## Two places to declare one thing A FastAPI **response model** is the type that FastAPI uses to validate the value a path operation returns, filter it to the declared fields, serialize it, and describe it in the OpenAPI schema. There are two ways to declare it: - **The return type annotation** on the path operation function: `async def read_user(...) -> UserOut:`. FastAPI reads it at route registration and builds the response model from it. - **The `response_model` parameter** of the path operation decorator: `@app.get("/users/{id}", response_model=UserOut)`. It belongs to the decorator, like `status_code`, not to the function. The annotation is the recommended default because one declaration serves two readers: FastAPI at runtime and the type checker or editor at development time. ## Which one wins | Declared | Response model FastAPI uses | |---|---| | annotation only | the annotation | | `response_model` only | `response_model` | | both | `response_model` (it takes priority) | | `response_model=None` | none: no validation, filtering or response schema | | annotation is `Response` or a subclass | none; the returned response is sent as is | Priority matters when the function's true return type differs from what should be sent. A handler that returns a stored `UserInDB` can be annotated `-> UserInDB`, which is honest for the type checker, while `response_model=UserOut` tells FastAPI what to send. Without that split you would have to annotate `-> Any` or silence the type checker. FastAPI's docs mention `-> Any` as the way to tell the editor you are returning anything on purpose while `response_model` does the real work. ## The subclass trick Often the output model is a **base class** of what the function returns. FastAPI's docs build exactly that: 1. Declare `UserBase` with the public fields. 2. Declare `UserInDB(UserBase)` adding `hashed_password`. 3. Annotate the function `-> UserBase` and return a `UserInDB`. The type checker accepts this, since a subclass instance is a valid `UserBase`. FastAPI does **not** use inheritance to decide what to send: it serializes by the declared type, so only `UserBase`'s fields go out. No `response_model` parameter is needed. ## Annotations FastAPI cannot turn into a model Not every useful annotation is a valid Pydantic type: - **A `Response` class or subclass**, such as `-> RedirectResponse`, is recognised and simply produces no response model. - **A union mixing a `Response` with data**, such as `-> Response | dict`, is neither. FastAPI tries to build a response model, fails and raises `FastAPIError` ("Invalid args for response field!") when the decorator runs, so the app does not start. - **An arbitrary class** that Pydantic cannot validate, such as a plain database class that is not a Pydantic model, fails the same way. The fix for both is `response_model=None` on the decorator: FastAPI skips building a response model and leaves the annotation to the type checker. The cost is real, though. With no response model there is no validation, no field filtering and no response schema in `/docs`; the return value is encoded with `jsonable_encoder` as it is. ## When the check happens FastAPI builds the response model while the decorator runs, typically when the module is imported, not when the first request arrives. That has two practical effects: - An invalid annotation is caught at startup, in the traceback of the import, rather than in production traffic. - The response model is fixed per path operation. FastAPI does not inspect the returned object's class to choose a model at request time, which is exactly why returning a subclass is filtered down to the declared type. At request time FastAPI checks one more thing first: if the function returned a `Response` instance, that response is sent as it is and the response model is not applied, whatever the declaration says. ## Choosing in practice - Prefer the annotation when the function returns exactly the output type or a subclass of it. - Use `response_model=` when the function returns a dict, a stored model or rows that need reading into the output type, and annotate the function with what it really returns. - Use `response_model=None` only when the annotation is not a Pydantic type, and remember the filter is gone. Setting other decorator options does not change this. `response_class=` or `include_in_schema=False` still leave FastAPI building a response model from the annotation, so an invalid annotation still fails with them.

  • Why not always annotate -> Any and put the model in response_model?
    It works at runtime, but it throws away the type checker's view of the handler: nothing then catches a function that returns the wrong thing until FastAPI's response validation fails with a 500. Annotate the real return type and use `response_model` only when what is sent differs from what the function returns.
  • Does response_model=None also stop FastAPI from filtering the output?
    Yes. With no response model, FastAPI neither validates nor filters the returned value; it encodes it with `jsonable_encoder` and the OpenAPI schema has no response model for that path. If the value is a dict with a secret in it, the secret goes out.

  • When both are declared, the return annotation overrides response_model.
  • Returning a subclass of the annotated model sends the subclass's extra fields too.
  • -> Response | dict works fine; FastAPI just skips validation for unions.
  • response_model=None keeps filtering on and only hides the schema in /docs.
  • response_model is an argument of the path operation function, next to the body.