skip to content

Custom Response Types

A path operation returns data for FastAPI to serialize or a Response it sends as is. Interviewers ask what a returned JSONResponse skips and why ORJSONResponse was deprecated in 0.131.

on this pageshow

explore

questions

5

In FastAPI 0.143, what does a path operation give up when it returns a JSONResponse directly instead of plain data?

level: middleimportance: must knowfreq 45%

answer

  1. passed through untouched
  2. response_model never sees it
  3. json.dumps meets a datetime
  4. the Response parameter is dropped
  5. docs still show the model

basics

~20 s

A returned JSONResponse is sent as is: no response_model validation or filtering, no conversion of datetimes or models, no headers or status from a Response parameter, no Pydantic JSON fast path, and docs that may not match the body.

solid answer

~50 s

FastAPI passes any returned `Response` subclass straight through. So the `response_model` or return type is not applied: no validation and no filtering, which means extra fields such as a password hash reach the client. The content is not converted either; `JSONResponse` renders with `json.dumps`, so a `datetime` or a Pydantic model raises unless I run it through `jsonable_encoder` first. Headers, cookies and a status code set on a `Response` parameter are ignored, because FastAPI only merges them into a response it builds. The route also misses the faster path: since 0.130, a declared return type or `response_model` makes Pydantic write the JSON bytes directly. And the OpenAPI docs still describe the declared model, so they can promise a shape the endpoint does not send. I return a `JSONResponse` only for a deliberate exception, such as an extra status code.

code

python · 37 lines
python
from datetime import datetime, timezone

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()


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


ROW = {
    "id": 1,
    "email": "[email protected]",
    "password_hash": "stored-hash",
    "joined": datetime(2026, 1, 5, tzinfo=timezone.utc),
}


@app.get("/users/me", response_model=UserOut)
def me_filtered():
    return ROW


@app.get("/users/me/raw", response_model=UserOut)
def me_raw():
    return JSONResponse(jsonable_encoder(ROW))


client = TestClient(app)
print(client.get("/users/me").json())
print(client.get("/users/me/raw").json())

go deeper

for a junior

Recall that returning plain data lets FastAPI convert and filter it, while returning a JSONResponse sends exactly what you put in it.

for a middle

Walk through each skipped step: validation and filtering, jsonable_encoder conversion, merging the Response parameter, and the documented schema.

for a senior

Spot the leak where a returned JSONResponse sends a field the response_model would have removed, and explain why a status-only test misses it.

for a principal

Weigh a team rule that path operations return data and declared types, keeping returned responses for redirects, files and documented exceptions.

## Two ways a path operation can answer A **path operation** in FastAPI can hand back either **plain data** (a `dict`, a list, a Pydantic model, an ORM object) or a **response object**: an instance of Starlette's `Response` or one of its subclasses such as `JSONResponse`, `HTMLResponse` or `RedirectResponse`. With plain data, FastAPI does the work after your function returns. In FastAPI 0.143: 1. If a `response_model` or a return type annotation is declared, FastAPI **validates** the data against it and **filters** it down to the declared fields. 2. With no custom `response_class`, Pydantic then serializes the validated value **straight to JSON bytes** (the fast path added in 0.130) and FastAPI wraps them in a response with `application/json`. 3. With no model at all, FastAPI runs the data through `jsonable_encoder` and puts the result in a `JSONResponse`. 4. Headers, cookies and a status code that the function or its dependencies set on a **`Response` parameter** are copied into that final response. With a response object, FastAPI checks `isinstance(..., Response)` and **sends it as is**. None of the four steps run. ## What is skipped, item by item | Step | Plain data | Returned `JSONResponse` | |---|---|---| | Validate against `response_model` | yes; a mismatch is a server error | no | | Filter to declared fields | yes | no; every key you put in is sent | | Convert `datetime`, `UUID`, models | yes | no; `json.dumps` raises a `TypeError` | | Merge a `Response` parameter's headers, cookies, status | yes | no | | Pydantic writes JSON bytes directly | yes, with a declared type and no custom class | no | | OpenAPI matches the body | yes | not guaranteed | Three of these rows cause real incidents: - **Data leaks.** A route declares `response_model=UserOut` with only `id` and `email`, then returns `JSONResponse(user_row)`. The row's `password_hash` goes to the client, because filtering never ran. Nothing fails, so tests that only check the status code pass. - **Runtime `TypeError`.** `JSONResponse` renders with the standard `json` module (`ensure_ascii=False`, `allow_nan=False`). A `datetime` in the content fails with "Object of type datetime is not JSON serializable". The documented fix is `JSONResponse(content=jsonable_encoder(data))`, which turns models into dicts and datetimes into ISO strings. - **Silent loss of headers and cookies.** If a dependency sets a cookie on the `Response` parameter and the endpoint then returns its own `JSONResponse`, the cookie never arrives. Set it on the object you return instead. ## The documentation trap The schema is built from the decorator and the declared model, not from what the function returns at runtime. In the example below the docs advertise `UserOut` for the raw route while the body carries extra fields. A status code you set on the returned object (say 201) is not documented either; describing such extra responses is the job of the decorator's `responses` argument. ## Why it costs performance as well Before 0.130, every JSON route was converted to plain Python objects first and then rendered by `JSONResponse` with the `json` module. Since 0.130, a route with a declared return type or `response_model` and no `response_class` lets Pydantic produce the bytes in its compiled core, which the release notes put at roughly twice as fast or more. Returning a `JSONResponse` puts you back on the slower path: you convert the data in Python, then `json.dumps` writes the bytes. ## When returning a response object is right - An **additional status code** on an otherwise normal route, for instance an upsert that answers 201 when it created the item. A `Response` parameter is often the better tool here, because it keeps filtering. - A body that is **not JSON**: XML in a `Response(content=xml, media_type="application/xml")`, a file, a redirect. - Full control over headers that must be exactly as built. In each case you take on the checks FastAPI would have done: encode the content, include only fields the client may see, and document the response yourself. ## Safer alternatives to reach for first Most reasons people give for returning a `JSONResponse` have a tool that keeps FastAPI's checks: | Goal | Tool that keeps validation and filtering | |---|---| | A different status for one branch | `response.status_code = 201` on a `Response` parameter | | An extra header or cookie | `response.headers[...]` or `response.set_cookie(...)` on that parameter | | A non-default status for every call | `status_code=` on the decorator | | Fewer fields in the body | a narrower return type or `response_model` | A useful review question for any pull request that adds `return JSONResponse(...)`: which of these four would have done the job, and if none, is the body encoded and filtered by hand?

  • In FastAPI, if a returned JSONResponse is not validated, can it ever cause a ResponseValidationError?
    No. `ResponseValidationError` comes from FastAPI's own check of returned data against a declared `response_model` or return type. A returned `Response` skips that check entirely, so wrong or extra data goes out without any error. That is why a returned response needs its own tests on the body, not only on the status code.
  • In FastAPI, do BackgroundTasks still run when a path operation returns its own JSONResponse?
    Yes. If the returned response has no background task of its own, FastAPI attaches the request's `BackgroundTasks` to it before sending, so tasks added with `add_task` still run after the response. Only if you set `background=` on the response yourself does FastAPI leave it alone.
  • In FastAPI, how do you send a 201 for one branch of a route without losing response_model filtering?
    Declare a `Response` parameter and set `response.status_code = 201` in that branch, then return plain data as usual. FastAPI still validates and filters the data, and copies the status code, headers and cookies from the parameter into the response it builds.

Returning plain data is like handing a shop the items to pack: staff check them against the order, remove what does not belong and add the labels. Returning a JSONResponse is handing over a box you sealed yourself: it ships as is, with whatever is inside and none of the labels the shop would have added.

  • Assuming response_model still filters a JSONResponse the function returns
  • Putting a Pydantic model or datetime straight into JSONResponse content
  • Setting a cookie on the Response parameter, then returning a JSONResponse
  • Returning JSONResponse everywhere because it is supposedly the fastest option
  • Trusting the docs page to show exactly what a returned response sends

Assumes FastAPI 0.143; the Pydantic-side JSON serialization that a returned response bypasses arrived in 0.130, while passing returned responses through untouched is older.

open as a page

In FastAPI, how do you return an HTML page or a CSV file instead of JSON, and what does response_class change?

level: juniorimportance: should knowfreq 38%

basics

~20 s

Pass response_class=HTMLResponse (or PlainTextResponse) to the path operation decorator and return a string, or return a FileResponse for a file. response_class sets the response's class, its Content-Type and the media type FastAPI documents in OpenAPI.

open as a page

In a FastAPI create endpoint answering 201 with a Location header, how do you set status, headers and cookies yet keep response_model filtering?

level: middleimportance: should knowfreq 40%

basics

~10 s

Put status_code=status.HTTP_201_CREATED on the decorator, declare a parameter typed Response, set response.headers["Location"] or call response.set_cookie on it, and return plain data. FastAPI copies the status, headers and cookies into the filtered response.

open as a page

After a FastAPI login form POST returns RedirectResponse("/dashboard"), the browser re-sends the POST and gets 405. Why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

FastAPI's RedirectResponse defaults to 307, which tells the browser to repeat the same method and body, so it POSTs to a GET-only /dashboard and gets 405. Pass status_code=status.HTTP_303_SEE_OTHER so the browser follows with a GET.

open as a page

In FastAPI 0.143, why are ORJSONResponse and UJSONResponse deprecated, and what should a team using default_response_class=ORJSONResponse do instead?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Since FastAPI 0.130 a declared return type or response_model makes Pydantic serialize straight to JSON bytes, which is faster than an orjson response class. So 0.131 deprecated both classes; remove default_response_class and declare return types instead.

open as a page