Sam Hooke

FastAPI: Pretty print JSON

FastAPI is a Python web framework for building APIs. The default response class is JSONResponse, but to improve performance you can install orjson and switch to ORJSONResponse.

The steps below cover how to enable pretty printing with ORJSONResponse in both FastAPI and NiceGUI.

Pretty print with orjson §

The underlying orjson package provides the option for pretty printing (with 2 space indentation) by enabling orjson.OPT_INDENT_2. However, the ORJSONResponse class provided by FastAPI does not expose a way to use this option.

Fortunately it is trivial to create your own response class with this option enabled.

Create an ORJSONPrettyResponse class §

Let’s use the source code for ORJSONResponse as a starting point. Create a new class named ORJSONPrettyResponse and add the option orjson.OPT_INDENT_2:

from typing import Any
from fastapi.responses import JSONResponse
import orjson

class ORJSONPrettyResponse(JSONResponse):
    def render(self, content: Any) -> bytes:
        return orjson.dumps(
            content,
            option=orjson.OPT_NON_STR_KEYS
            | orjson.OPT_SERIALIZE_NUMPY 
            | orjson.OPT_INDENT_2,
        )

That’s it. Now we just need to use this class in our application code.

Use the ORJSONPrettyResponse class §

Using this class is as simple as specifying it in the response_class field of the @app.get decorator:

@app.get("/endpoint.json", response_class=ORJSONPrettyResponse)
def endpoint_get():
    return {
        "key_1": "value_1",
        "key_2": "value_2",
        "key_3": {
            "key_3a": "value_3a",
            "key_3b": "value_3b",
        }
    }

Now, instead of getting a compact response:

{"key_1":"value_1","key_2":"value_2","key_3":{"key_3a":"value_3a","key_3b":"value_3b"}}

Responses will be pretty printed in a more readable manner with 2 space indentation:

{
  "key_1": "value_1",
  "key_2": "value_2",
  "key_3": {
    "key_3a": "value_3a",
    "key_3b": "value_3b"
  }
}

Pretty print JSON response in NiceGUI §

Since NiceGUI uses FastAPI for their @app.get decorator, the steps for pretty printing JSON from NiceGUI are identical.

Just import your custom ORJSONPrettyResponse class, then update the @app.get decorators to add response_class=ORJSONPrettyResponse.