Extracting content from response in middleware FASTAPI

42 Views Asked by At

I am trying to extract response content from the response stream inside middleware.

@app.middleware("http")
def async def publish_to_event_stream(request: Request, call_next):
    response = await call_next(request)
    resp_content = None
    content_type = response.headers["content-type"]
    try:
        if content_type == "application/json":
            response_body = b""
            async for chunk in response.body_iterator:
                response_body += chunk
            resp_content = json.loads(response_body.decode())
    except Exception as e:
        logger.error('response_parsing_failure', response=response)
    return response

response_content has actual content but then from middleware when I am returning the response, it's throwing an error:

RuntimeError("Response content shorter than Content-Length")

Because of the above async for loop, I think the response stream is reaching to end. When I tried to print the response body it was empty b''

One way to solve it is to recreate ResponseStream with extracted content and type.

     return Response(content=response_content, media_type=content_type)
     

Please help me find a better to get content from the response stream without affecting the actual response.

0

There are 0 best solutions below