0

I am new to FastAPI framework, I want to print out the response status code from a PUT request.

@app.put('/user/{id}', status_code=status.HTTP_200_OK) 
async def processing(id: str, request: Request, response: Response):
    data = await request.json()
    status = response.status_code
    print(status_code)
    logger.info("Got response [%s]", status)
    return data

The status returned is 'None'. But uvicorn server shows a 200 OK status. How can I include this code in my logging/print out?

Thanks.

uk_butterfly
  • 93
  • 1
  • 2
  • 8
  • The `status_code` from the decorator won't be set until you've returned from your function. Since you're inside the function handling the request itself, don't you know if everything went OK or not? – MatsLindh Dec 01 '21 at 14:10
  • @MatsLindh thanks for helping. The server (uvicorn) does indicate response status in Terminal, but I wanted to code an if/else condition depending on the status_code returned. How could I do this? – uk_butterfly Dec 01 '21 at 14:31
  • You're the one setting the status code - which status code do you want to intercept? The view function - the one you've included - configures its own status code, either through `response.status_code` or through the `status_code` parameter on the decorator. If you want to intercept internal status codes (4xx, 5xx) that your code doesn't generate by itself a middleware might be what you want, not a view endpoint. – MatsLindh Dec 01 '21 at 16:56
  • @MatsLindh Thanks for clarifying this, will try implement a middleware to intercept status codes generated by http calls from another server. – uk_butterfly Dec 01 '21 at 19:04

0 Answers0