1

I have been trying this for days - including lots of exchanges with Bard and ChatGPT, digging up stackoverflow, etc. I have the simple need to log requests (before they hit my API processing function) and responses - for debugging. Part of this is necessitated by the fact that FastAPI has strict validations and on the server side, I want to know what the request looked like when it rejected with a certain error code. I tried various things and have distilled my problem statement to the following:

This code block works to the extent of printing the request details. But after that the API does not complete. The client waits forever and on the server side logs, I never see Message#2. If I simply replace the line j = await request.json() with j="foo", everything works functionally although I am not able to capture the json data for my logging. I am sure I am missing something very basic here. I am also surprised by how difficult it is in fastapi to insert a simple intervention like Flask's @before_request.

@app.middleware("http")
async def log_requests(request, call_next):
    j = await request.json()
    print(f"Message#1: Request received: method:{request.method} url:{request.url}, json:{j}")
    response = await call_next(request)
    print(f"Message#2: Response ready to be sent")
    return response
Chris
  • 18,724
  • 6
  • 46
  • 80
sachinsdesai
  • 109
  • 1
  • 11
  • Thank you @Chris . I tried this quite a bit - including making fixes to it. But it did not work for me. It did the job of logging the request details. But it basically returned `404 Not Found` error for all API end-points (including the ones that work without this middleware intervention). So, something might have changed in fastapi since this solution was provided by the author – sachinsdesai Apr 13 '23 at 19:34
  • @Chris, I take my last response back. I made one mistake - put the middleware function at the end (after other methods). I missed that detail when I read your (again apologies - did not know that you were the original author!) original post. Just moved this code block higher up in the file and it all works now. Thanks again! – sachinsdesai Apr 13 '23 at 20:28

0 Answers0