🗑️ Deprecate ORJSONResponse and UJSONResponse#14964
Conversation
📝 Docs previewLast commit c21b0aa at: https://e3d39a97.fastapitiangolo.pages.dev Modified Pages |
|
With this deprecation, what's the recommended approach for exception handlers that return plain dict bodies? For example: @app.exception_handler(ValidationError)
async def validation_error_handler(request: Request, exception: ValidationError) -> Response:
return ORJSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"errors": exception.errors()},
)Since exception handlers don't use Pydantic return types, they don't benefit from the Pydantic serialization. Should we just switch to JSONResponse and accept the performance difference, or is there another approach? |
|
Are there any benchmark or something? |
You can copy the implementation of |
@tmdgusya I ran benchmarks for my responses (#14299 (comment)). Feel free to plug in yours and check. |
|
@YuriiMotov thanks for the answer! Though I think deprecating these classes is a mistake, for plain dict serialization, orjson are still significantly faster than stdlib, and that's free performance. Copying the implementation feels like a workaround for removing something that's still useful. |
Do you mean routes like this: @app.get("/default")
def get_default() -> dict:
return {"name": "widget", "price": 9.99}? In this case FastAPI will also serialize it with Pydantic, not Detailsfrom unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
app = FastAPI()
@app.get("/default")
def get_default() -> dict:
return {"name": "widget", "price": 9.99}
client = TestClient(app)
def test_default_response_class_skips_json_dumps():
"""When no response_class is set, the fast path serializes directly to
JSON bytes via Pydantic's dump_json and never calls json.dumps."""
with patch(
"starlette.responses.json.dumps", wraps=__import__("json").dumps
) as mock_dumps:
response = client.get("/default")
assert response.status_code == 200
assert response.json() == {"name": "widget", "price": 9.99}
mock_dumps.assert_not_called()If you still think we need to de-deprecate these classes, please open a discussion and let's continue discussing it there |
|
Oh my bad, I didn't realize Pydantic could serialize plain dicts too! In that case, should Pydantic serialization become the default for Edit: I just started a discussion on this topic #14980 |
🗑️ Deprecate
ORJSONResponseandUJSONResponseNow that there's better performance by default, with response models: #14962
This removes
ujsonandorjsonfrom the"fastapi[all]"extras.To use these responses,
ujsonororjsonneed to be explicitly installed.