FastAPI: Pretty print JSON
All notes in this series:
- NiceGUI: Always show main scrollbar
- NiceGUI: Show a confirmation popup
- NiceGUI: File upload and download
- FastAPI: Pretty print JSON
- NiceGUI with Click, Poetry, auto-reload and classes
- NiceGUI: tkinter error when updating pyplot
- NiceGUI: Bind visibility to arbitrary value
- NiceGUI: Change threshold for binding propagation warning
- NiceGUI with async classes
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
:
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:
Now, instead of getting a compact response:
Responses will be pretty printed in a more readable manner with 2 space indentation:
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
.