Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Update ORJSONResponse to support non str keys and serializing Numpy arrays #3892

Merged
merged 8 commits into from Sep 2, 2022
4 changes: 3 additions & 1 deletion fastapi/responses.py
Expand Up @@ -31,4 +31,6 @@ class ORJSONResponse(JSONResponse):

def render(self, content: Any) -> bytes:
assert orjson is not None, "orjson must be installed to use ORJSONResponse"
return orjson.dumps(content)
return orjson.dumps(
content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY
)
21 changes: 21 additions & 0 deletions tests/test_orjson_response_class.py
@@ -0,0 +1,21 @@
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
from fastapi.testclient import TestClient
from sqlalchemy.sql.elements import quoted_name

app = FastAPI(default_response_class=ORJSONResponse)


@app.get("/orjson_non_str_keys")
def get_orjson_non_str_keys():
key = quoted_name(value="msg", quote=False)
return {key: "Hello World", 1: 1}


client = TestClient(app)


def test_orjson_non_str_keys():
with client:
response = client.get("/orjson_non_str_keys")
assert response.json() == {"msg": "Hello World", "1": 1}