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