Skip to content

Unable to get request body in custom request formatter when using FastAPI #84

Open
@vstrimaitis

Description

@vstrimaitis

I'm interested in getting the request body in a custom request formatter when using FastAPI. However, request.body() returns a coroutine and therefore requires the await keyword, but the _format_log_object method is not async. My custom formatter looks something like this:

class _RequestFormatter(json_logging.JSONRequestLogFormatter):
    def _format_log_object(
        self, record, request_util: json_logging.util.RequestUtil
    ):
        request: Request = record.request_response_data._request

        request_body_bytes = await request.body()  # <--- can't do this!
        request_body = bytes.decode(request_body_bytes)

        log_obj = super()._format_log_object(record, request_util)
        log_obj.update({"request_body": request_body})
        return log_obj

Such an approach works in frameworks like Flask, where you don't have to use await to get the body, but fails for FastAPI. Do you have any suggestions on how to work around this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions