In FastAPI 0.143, when does Pydantic write a declared response model straight to JSON bytes, and why does any response_class, even an app-wide default, take a route off that path?
answer
- 0.130 moved JSON into Pydantic
- one pass straight to bytes
- only with no response_class
- an app-wide default counts as set
basics
~20 sSince 0.130, a return type or response_model with no response_class lets Pydantic's dump_json write the JSON bytes in one pass. Any explicit class, even JSONResponse or an app-wide default, makes Pydantic build Python data first for the class to render.
solid answer
~40 sIn FastAPI 0.143, when a path operation has a return annotation or `response_model` and no `response_class`, FastAPI validates the value and calls Pydantic's `dump_json`, which writes the filtered JSON bytes in one pass in Pydantic's Rust core, then wraps them in a plain `Response` with `application/json`. If a `response_class` is set on the route, or `default_response_class` on the app or router, FastAPI still validates and filters but first produces JSON-compatible Python data and hands it to that class, which renders it with its own encoder. So a response class set only for speed, the old `ORJSONResponse` tip included, now adds a step instead of saving one. Declare a response model and leave the class unset.
code
python · 31 linesfrom fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from pydantic import BaseModel
class UserOut(BaseModel):
id: int
username: str
app = FastAPI()
# Fast path: a response model and no response_class.
# Pydantic validates, filters and writes JSON bytes in one pass.
@app.get("/users/{user_id}")
async def read_user(user_id: int) -> UserOut:
return UserOut(id=user_id, username="ada")
# Same validation and filtering, but an explicit response_class
# means Pydantic builds Python data first and JSONResponse renders it.
@app.get("/explicit/{user_id}", response_class=JSONResponse)
async def read_user_explicit(user_id: int) -> UserOut:
return UserOut(id=user_id, username="ada")
client = TestClient(app)
r = client.get("/users/1")
print(r.headers["content-type"], r.json()) # application/json {'id': 1, 'username': 'ada'}go deeper
Know that declaring a response model, with no response class, is current FastAPI's fast JSON path.
Explain the condition: a response model and no response_class anywhere gives one-pass dump_json; any explicit class adds a Python data step.
Audit an upgraded codebase for app-wide or route-level response classes kept only for speed, and remove them while keeping every endpoint's response model.
Make the response model the single convention for both safety and performance, so speed tweaks never tempt a team to bypass output filtering.
## What changed in 0.130 For years the standard advice for faster FastAPI JSON was to install a faster third-party JSON encoder and set `ORJSONResponse` as the response class. FastAPI 0.130 changed the picture: when a path operation has a **Pydantic return type or response model**, FastAPI now serializes the JSON response **with Pydantic, in Rust**. The release notes report a 2x or larger speed-up for JSON responses. FastAPI 0.131 then **deprecated `ORJSONResponse` and `UJSONResponse`**. Their deprecation notice says FastAPI now serializes directly to JSON bytes via Pydantic when a return type or response model is set, which is faster and needs no custom response class. ## The paths a return value can take In FastAPI 0.143, after the path operation function returns, the routing code picks one of these paths: | Route setup | Validated and filtered | How the JSON is produced | |---|---|---| | response model, **no** `response_class` anywhere | yes | `dump_json` writes bytes in one pass; sent as a `Response` with `application/json` | | response model **plus** a `response_class` or a `default_response_class` | yes | Pydantic builds JSON-compatible Python data, then the class's `render` encodes it | | no response model | no | `jsonable_encoder` converts the value, then the response class encodes it | | the function returns a `Response` | no | sent as built | In 0.143 the condition for the fast path is that a response field exists **and** the response class is still FastAPI's default placeholder. Setting the class explicitly, even to `JSONResponse`, which is the default class anyway, takes the route off the fast path. ## Why the app-wide default counts `default_response_class` on `FastAPI(...)` or an `APIRouter` is resolved into each route's `response_class`. Once it is set, no route under it has the default placeholder any more, so every route with a declared response model: - still validates the returned value against the model, - still filters to the declared fields, - but goes through an intermediate Python data structure before the class encodes it. The validation and filtering guarantees do not change; only the serialization path does. That is why the change is easy to miss: responses look identical and tests stay green. ## How older releases behaved Before 0.130, a declared response model was validated and turned into JSON-compatible Python data, which the response class then encoded; `JSONResponse` did that with the standard library's `json.dumps`. Swapping in `ORJSONResponse` replaced only that last encoding step with a faster encoder, which is why the advice spread. Since 0.130 the default route does the whole job in Pydantic's serializer, so that swap no longer saves a step: it adds one back. Material written before the change still repeats the old tip, so expect it in code reviews of older services: - `FastAPI(default_response_class=ORJSONResponse)` in the app factory. - `response_class=ORJSONResponse` on individual hot endpoints. - Endpoints that return a model with no annotation, which never had a response model and still do not get the fast path. ## What to do on 0.143 1. **Remove** `default_response_class=ORJSONResponse` or `UJSONResponse` and route-level `response_class` settings that exist only for speed. 2. **Declare a response model** on every JSON endpoint, as a return annotation or `response_model=`. That is now both the safety mechanism and the fast path. 3. **Keep** `response_class` where it changes the response type, such as `HTMLResponse` or a streaming class, not for JSON speed. 4. **Measure** with your own payloads before and after; the release notes' figure is not a promise for every response shape. Using `ORJSONResponse` emits a `FastAPIDeprecationWarning` when it is instantiated; it does not stop the app, and its encoder library still has to be installed separately. ## A note on where the work runs For a `def` path operation, FastAPI runs response validation in the thread pool; for an `async def` one it runs on the event loop. Serialization runs inline in both. On very large responses, the fast path's single pass is a direct saving of event loop time, which is another reason to let the response model do the encoding.
- Does an endpoint without a response model get the Pydantic fast path if it returns a Pydantic model instance?No. The fast path needs a response field, which comes from a return annotation or `response_model`. Without one, FastAPI converts the returned value with `jsonable_encoder` and the response class encodes it, so there is neither filtering nor the one-pass serializer. Annotating the function with the model's type is enough to switch both on.
- Is setting response_class=JSONResponse explicitly harmless, since it is the default class?Not for speed in 0.143. The fast path checks that the response class is still FastAPI's default placeholder, not which class it is, so an explicit `JSONResponse` takes the route off the one-pass path. Output, validation and filtering are unchanged; only the serialization step differs.
- Setting default_response_class changes only the media type, never the serialization path.
- An explicit response_class=JSONResponse keeps the fast path, since it is the default class.
- A custom response class turns off response model validation and filtering.
- Returning a Pydantic model without a return annotation gets the Pydantic fast path.
- Using a deprecated response class makes the app fail at startup.
Assumes FastAPI 0.143; 0.130 added Pydantic-side JSON serialization for declared response models and 0.131 deprecated ORJSONResponse and UJSONResponse.