← Back to FastAPI, page 4

fastapi-0066 · Easy fresher

What is the difference between a return type annotation, response_model, and returning a Response directly in FastAPI?

A return annotation (-> StudentPublic) is the modern way to declare the response model: FastAPI validates and filters the returned data and documents the schema from it. The response_model parameter does the same and takes priority when both exist, which helps when the function returns a richer type than the API exposes. Returning a Response object (JSONResponse, HTMLResponse, FileResponse) bypasses validation and serialisation entirely and is used for custom bodies, streams and files.

Full answer

Three mechanisms, increasing control and decreasing automation:

  1. Return annotation: def read() -> StudentPublic:. FastAPI treats it as the response model (since 0.89), so type checkers and the API contract agree.
  2. response_model=StudentPublic: explicit; use when the function returns something else (an ORM object, a dict, a StudentInDB subclass) that must be filtered down. If both are present, response_model wins, which makes patterns like returning StudentInDB while publishing StudentPublic possible, with -> StudentInDB for type checkers.
  3. Return a Response subclass: no validation, no filtering, no docs inference. Provide response_class or responses= so OpenAPI still describes it, or set response_model=None to disable inference from the annotation (needed when the annotation is Response | dict).

What happens in 1 and 2: FastAPI validates the return value against the model (a bug in your function becomes a 500 ResponseValidationError, not silent bad output), removes extra fields (hiding secrets), serialises with Pydantic's JSON encoder (dates, UUIDs, Decimals handled), and publishes the JSON schema.

Use direct responses for: FileResponse and StreamingResponse, RedirectResponse, custom status and headers in one go, HTMLResponse, and performance-sensitive cases where you pre-serialised JSON bytes.

Cost note: validation and serialisation of big payloads takes time. For very hot endpoints, return exactly the right shape and measure whether skipping the model matters, but do not trade away filtering for sensitive data.

Responses for other status codes (404, 409) are documented with responses={404: {"model": ErrorOut}}; they are not enforced at runtime.

python
from fastapi import FastAPI
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()


class StudentPublic(BaseModel):
    name: str


class StudentInDB(StudentPublic):
    password_hash: str


@app.get("/annotated")
def annotated() -> StudentPublic:
    return StudentPublic(name="Asha")


@app.get("/filtered", response_model=StudentPublic)
def filtered() -> StudentInDB:                              # the response_model wins: the hash is removed
    return StudentInDB(name="Ravi", password_hash="x1y2")


@app.get("/direct", response_model=None)
def direct() -> JSONResponse | dict:
    return JSONResponse({"name": "Kiran", "password_hash": "not filtered"}, status_code=202)


@app.get("/text", response_class=PlainTextResponse)
def text():
    return "plain text body"


@app.get("/buggy", response_model=StudentPublic)
def buggy():
    return {"nickname": "no name field"}


c = TestClient(app, raise_server_exceptions=False)
for path in ("annotated", "filtered", "direct", "text"):
    r = c.get(f"/{path}")
    print(path, r.status_code, r.text.strip())
print("buggy", c.get("/buggy").status_code)
schemas = c.get("/openapi.json").json()["components"]["schemas"]
print(sorted(schemas))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): annotated 200 {"name":"Asha"} filtered 200 {"name":"Ravi"} direct 202 {"name":"Kiran","password_hash":"not filtered"} text 200 plain text body buggy 500 ['StudentPublic']

Key points

  • Return annotation acts as the response model
  • response_model wins and can filter a richer return type
  • Returning a Response bypasses validation and filtering
  • Response validation failures are 500 server errors
  • Document extra statuses with responses=; they are not enforced

Common mistakes

  • Returning ORM objects with private fields and no response model
  • Expecting responses={404: ...} to validate or enforce error bodies
  • Returning a Response and forgetting that nothing is filtered
  • Leaving the annotation as Response | dict without response_model=None

Follow-ups

  • What happens if the function returns data that does not match response_model?
  • How do you document multiple response statuses?
  • When would you skip response validation for speed?

Tips

  • Rank the three mechanisms
  • Explain filtering benefit
  • Mention response_model=None