In FastAPI 0.143, why are ORJSONResponse and UJSONResponse deprecated, and what should a team using default_response_class=ORJSONResponse do instead?
answer
- 0.130 then 0.131
- Pydantic writes the bytes
- declare a type, drop the class
- an explicit class turns it off
basics
~20 sSince 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.
solid answer
~40 sTeams used `ORJSONResponse` because the default path, converting data to Python objects and then calling `json.dumps`, was slow. FastAPI 0.130 changed that: when a route has a return type or `response_model` and no custom `response_class`, Pydantic validates and writes the JSON bytes in its compiled core, and FastAPI sends them with `application/json`. 0.131 then deprecated `ORJSONResponse` and `UJSONResponse`; they still work but emit a `FastAPIDeprecationWarning` each time one is created. The migration is to delete `default_response_class=ORJSONResponse` and make sure every JSON route declares its type. The trap is that any explicit class, including `JSONResponse`, turns the fast path off, and a route with no declared type still goes through `jsonable_encoder`.
code
python · 14 linesfrom fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Prediction(BaseModel):
label: str
score: float
@app.post("/predict")
def predict() -> Prediction:
return Prediction(label="spam", score=0.97)go deeper
Recall that FastAPI 0.131 deprecated ORJSONResponse and that declaring a return type is now the fast way to send JSON.
Explain the three serialization paths and which one a route takes, depending on a declared type and an explicit response class.
Plan the migration: remove the app and router defaults, type the untyped routes, and check array or non-string-key output that orjson used to handle.
Decide whether a team standard of declared return types on every JSON route is worth enforcing, given the speed, docs and validation it brings.
## Why the orjson classes existed Before FastAPI 0.130, every JSON route was serialized in Python: FastAPI converted the returned data to plain dicts and lists, with `jsonable_encoder` or Pydantic, and `JSONResponse` turned that into bytes with the standard `json` module. For large payloads, such as a list of predictions with scores, that was a visible share of request time. `ORJSONResponse` and `UJSONResponse` were `JSONResponse` subclasses whose `render()` used the faster `orjson` or `ujson` libraries instead, and many teams set `FastAPI(default_response_class=ORJSONResponse)` once to get the speed everywhere. ## What changed | Release | Change | |---|---| | 0.130 | With a Pydantic return type or `response_model`, FastAPI serializes the JSON response with Pydantic in its compiled core; the release notes cite roughly twice the speed or more | | 0.131 | `ORJSONResponse` and `UJSONResponse` are deprecated | The deprecation message states the reason directly: FastAPI now serializes data straight to JSON bytes via Pydantic when a return type or response model is set, which is faster and needs no custom response class. Pydantic's serializer is built on the same kind of compiled machinery as orjson, so the extra library buys nothing on that path, and it is one more optional dependency to install (neither `orjson` nor `ujson` ships with FastAPI). ## How the fast path is chosen In FastAPI 0.143 the request handler picks one of three paths for plain returned data: 1. **Declared type, no custom class.** The route has a return annotation or `response_model`, and `response_class` was never set (on the route, the router or the app). Pydantic validates and dumps JSON bytes; FastAPI sends them in a plain `Response` with `media_type="application/json"`. `JSONResponse` is not used at all. 2. **Declared type, explicit class.** Pydantic validates and converts the data to JSON-compatible Python objects, then the declared class's `render()` produces the bytes, `json.dumps` for `JSONResponse`. 3. **No declared type.** FastAPI calls `jsonable_encoder` and passes the result to the response class. The consequence surprises people: writing `response_class=JSONResponse` explicitly, which looks like a no-op, moves a route from path 1 to path 2. So does any `default_response_class` passed to `FastAPI()` or an `APIRouter`, because it is an explicit choice rather than FastAPI's built-in default. ## The migration, step by step 1. **Remove** `default_response_class=ORJSONResponse` from `FastAPI(...)` and every `APIRouter(...)`, and any per-route `response_class=ORJSONResponse`. 2. **Declare types.** Give JSON routes a return annotation (`-> Prediction`, `-> list[Prediction]`) or a `response_model`. Routes that return bare dicts with no type fall back to `jsonable_encoder`, so they gain nothing until typed. 3. **Check the output.** orjson's options in FastAPI's class included `OPT_NON_STR_KEYS` and `OPT_SERIALIZE_NUMPY`. A route that relied on array-library values or non-string dict keys being serialized needs those values converted to lists, floats or string keys, or declared as types Pydantic knows how to dump. 4. **Keep a custom class only for a format need.** If clients genuinely need, say, indented output, a `Response` subclass with your own `render()` is still supported. Accept that it leaves the fast path. 5. **Watch the warnings.** The warning class is `FastAPIDeprecationWarning`, a `UserWarning` subclass chosen so Python's default filters do not hide it. It is raised when an instance is created, so it shows up in logs and test output once the deprecated class sends responses, not when the app is constructed. ## Verifying the migration A few checks confirm that routes really moved to the fast path and that clients see the same bytes: - **Inspect the configuration.** Search the code base for `response_class=` and `default_response_class=`; each hit on a JSON route is a route that still renders through a class. - **Compare outputs.** Call a sample of routes before and after with the test client and compare the parsed JSON. Field order and values should match; differences usually point at array-library values, non-string keys or custom types orjson used to accept. - **Measure, do not assume.** Time a large-payload route before and after. The gain is largest where the response is big and the type is declared; a route dominated by a database call will barely move. - **Keep the response options.** `response_model_exclude_unset`, `response_model_exclude_none` and aliases are applied on the fast path too, so typed routes keep their filtering settings. ## How to answer in an interview - Name the two releases: Pydantic-side serialization in 0.130, the deprecation in 0.131. - Explain why a response class is now the slower choice for typed routes. - Mention the trap that an explicit `JSONResponse` disables the fast path, and that untyped routes never had it.
- How would you make a FastAPI test suite fail on any remaining ORJSONResponse before removing it?Turn the warning into an error with the filter `error::fastapi.exceptions.FastAPIDeprecationWarning`, through Python's `-W` option or the test runner's warning settings, so a test that hits such a route fails. The warning fires when an instance is created, so only routes the tests actually call are caught; pair it with a search of the code for `ORJSONResponse` and `UJSONResponse`.
- In FastAPI, why might removing ORJSONResponse break a route that returns arrays from a numerical array library?FastAPI's `ORJSONResponse` rendered with orjson's `OPT_SERIALIZE_NUMPY` option, so such arrays and their scalars were encoded silently. Pydantic and the standard `json` module do not serialize those types out of the box, so after the switch those values must be converted to lists or floats, or declared as types Pydantic can dump.
- Recommending ORJSONResponse as the way to make FastAPI JSON fast today
- Thinking response_class=JSONResponse is a harmless no-op on typed routes
- Assuming untyped dict-returning routes get Pydantic's fast serialization
- Believing the deprecated classes were removed and now fail at import
- Expecting the deprecation warning when the FastAPI app is created
Assumes FastAPI 0.143; Pydantic-side JSON serialization arrived in 0.130 and ORJSONResponse and UJSONResponse were deprecated in 0.131.