Flask-ORJSON
Flask-ORJSON is a Flask JSON provider that leverages the `orjson` library for significantly faster JSON serialization and deserialization. It replaces Flask's default `json` module with `orjson`, offering performance improvements, especially for high-throughput applications handling large JSON payloads. The current version is 2.0.0, and it is actively maintained by the Pallets-eco team, following a release cadence tied to Flask and `orjson` updates.
Common errors
-
orjson.JSONEncodeError: Object of type <YourCustomClass> is not JSON serializable
cause You are attempting to serialize a custom Python object that `orjson` does not natively support, and no `default` serialization function has been provided to handle it.fixProvide a `default` callable function when initializing `OrjsonProvider`. This function will be called for objects that `orjson` cannot serialize by default, allowing you to convert them to a serializable type. Example: `app.json = OrjsonProvider(app, default=my_custom_serializer)`. -
TypeError: Object of type Decimal is not JSON serializable
cause While `flask-orjson` (and `orjson` >= 3.0) supports `Decimal` natively, this error can occur if you're using an older `orjson` version or if `flask-orjson` isn't correctly configured. For other unsupported types, the cause is the same as the custom class error.fixEnsure `flask-orjson` (version 2.0.0 and above) is correctly installed and configured. If the error persists for `Decimal` (or for other types not natively supported), define and pass a `default` callable to `OrjsonProvider` to handle the specific type. For `Decimal`, a common fix within a `default` is `return float(obj)` or `return str(obj)`. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position X: invalid start byte
cause This typically happens when `orjson.loads()` receives input that is not valid UTF-8 encoded bytes, or when you explicitly `decode('utf-8')` an invalid byte sequence before passing it to `orjson.loads`.fixEnsure that the input data to `orjson.loads()` is always valid UTF-8 encoded bytes. If you're receiving data from a request, verify the client is sending correct encoding. `orjson.loads` can directly consume `bytes` or `bytearray`, so avoid unnecessary `decode()` calls if the input is already in bytes format.
Warnings
- breaking `orjson.dumps()` returns `bytes`, not `str`, directly. While `flask-orjson` integrates this, any custom code directly calling `orjson.dumps()` and expecting a string output will break.
- gotcha `orjson` is stricter regarding JSON compliance than Python's standard `json` module. Values like `NaN` (Not-a-Number) or `Infinity` in floats will raise a `JSONEncodeError` during serialization.
- gotcha Custom object serialization with `orjson` uses a `default` hook function, not subclassing `json.JSONEncoder` as in the standard library. If you're migrating from a custom `JSONEncoder`, your logic will need refactoring.
- gotcha Datetime and date objects are serialized to ISO 8601 format (e.g., '2026-04-16T18:02:00.000000') instead of RFC 822 (used by Flask's default provider).
Install
-
pip install flask-orjson
Imports
- OrjsonProvider
from flask_orjson import OrjsonProvider
Quickstart
from flask import Flask, jsonify
from flask_orjson import OrjsonProvider
from datetime import datetime, date
from decimal import Decimal
app = Flask(__name__)
app.json = OrjsonProvider(app)
@app.route("/")
def hello_world():
# This will use OrjsonProvider for serialization
return jsonify({"hello": "world", "current_time": datetime.now()})
@app.route("/data")
def get_data():
# OrjsonProvider natively supports datetime, date, Decimal, UUID, etc.
return {
"timestamp": datetime.now(),
"today": date.today(),
"amount": Decimal("123.45"),
"complex_list": [{"id": 1, "name": "item 1"}, {"id": 2, "name": "item 2"}]
}
if __name__ == "__main__":
app.run(debug=True)