Is there a way to pretty print / prettify a JSON response in FastAPI?

Viewed 2355

I'm looking for something that is similar to Flask's app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True.

2 Answers

This is taken from David Montague.

You can annotate any endpoint with a custom response class, for example

@app.get("/config", response_class=PrettyJSONResponse)
def get_config() -> MyConfigClass:
    return app.state.config

An example for PrettyJSONResponse could be (indent=4 is what you were asking)

import json, typing
from starlette.responses import Response

class PrettyJSONResponse(Response):
    media_type = "application/json"

    def render(self, content: typing.Any) -> bytes:
        return json.dumps(
            content,
            ensure_ascii=False,
            allow_nan=False,
            indent=4,
            separators=(", ", ": "),
        ).encode("utf-8")

I'm not sure what exactly your problem is, can you tell what the background of your need?

however, because FASTAPI is based on open standards(OpenAPI, JSONSchema) it has automatic docs. --> FastAPI Auto Docs.

you have the Swagger UI under host/docs. or the ReDoc under host/redoc. Both will give you pretty representation of the JSON response in ease.

Related