Fastapi. How to get request.body from starlette-context plugin?

  fastapi, httpcontext, python, request, starlette

I am using fastapi to build website and I want to get request.body() for logging. I import starlette-context==0.3.3 to get a global context from request.

Since the default plugin could only get variable from request.header, I need to write a plugin to get request.body()

I could easily get some variable like request.url, but I When I write plugin to get my request body, I got problem ‘RuntimeWarning: coroutine ‘Request.body’ was never awaited’ and my route of fastapi could not get any request.

My plugin code is :

from typing import Any, Optional, Union

from starlette.requests import HTTPConnection, Request
from starlette_context.plugins import Plugin

class BodyPlugin(Plugin):
    key = "body"

    async def process_request(
        self, request: Union[Request, HTTPConnection]
    ) -> Optional[Any]:
        body = await request.body()

        return body

And my middleware is below:

middleware = [
    Middleware(
        ContextMiddleware,
        plugins=(
            BodyPlugin()
        )
    )
]

Source: Python Questions

LEAVE A COMMENT