Django RestFramework JSON Renderer Backed by orjson
drf-orjson-renderer is a highly performant JSON renderer and parser for Django Rest Framework (DRF), leveraging the `orjson` library, which is backed by Rust for speed, safety, and correctness. It significantly boosts API response times by replacing DRF's default JSON renderer and also supports pretty-printed JSON for the Browsable API. The current version is 1.8.0, with ongoing active maintenance and updates.
Warnings
- gotcha When configuring `ORJSON_RENDERER_OPTIONS` in `settings.py`, ensure that any `orjson.OPT_*` flags are correctly imported from `orjson` within your settings file or defined as constants.
- gotcha For custom serialization of objects not natively supported by `orjson` (e.g., custom Python classes), you may need to provide a `default` function. This is typically done by overriding the `get_renderer_context()` method within your DRF `APIView` or `ViewSet`.
- gotcha If you are manually creating and returning `ORJsonResponse` instances (rather than letting DRF's renderer handle it), you might encounter a `TypeError` for non-dictionary root objects. This is because `orjson` (and standard JSON) expects the top-level object to be a dictionary or list.
- breaking Version 1.8.0 specifically added support for NumPy 2.0. While `orjson` generally handles NumPy types, older `drf-orjson-renderer` versions might have had specific internal encoders or different compatibility with newer NumPy versions.
Install
-
pip install drf-orjson-renderer
Imports
- ORJSONRenderer
from drf_orjson_renderer.renderers import ORJSONRenderer
- ORJSONParser
from drf_orjson_renderer.parsers import ORJSONParser
Quickstart
import os
# settings.py
REST_FRAMEWORK = {
"DEFAULT_RENDERER_CLASSES": (
"drf_orjson_renderer.renderers.ORJSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer",
),
"DEFAULT_PARSER_CLASSES": (
"drf_orjson_renderer.parsers.ORJSONParser",
"rest_framework.parsers.FormParser",
"rest_framework.parsers.MultiPartParser",
),
"ORJSON_RENDERER_OPTIONS": (
# Example options for orjson
# import orjson # You would import orjson in settings.py to use these
# orjson.OPT_NON_STR_KEYS,
# orjson.OPT_SERIALIZE_DATACLASS,
# orjson.OPT_SERIALIZE_NUMPY,
),
}