Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Response Body for a HTTP Error in python

Need to capture the response body for a HTTP error in python. Currently using the python request module's raise_for_status(). This method only returns the Status Code and description. Need a way to capture the response body for a detailed error log.

Please suggest alternatives to python requests module if similar required feature is present in some different module. If not then please suggest what changes can be done to existing code to capture the said response body.

Current implementation contains just the following:

resp.raise_for_status()
like image 586
Anupam Nair Avatar asked Sep 21 '18 07:09

Anupam Nair


People also ask

How do you return a response in Python?

When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests. method(), method being – get, post, put, etc.

How do you raise the HTTP exception in Python?

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception. In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception. If a request times out, a Timeout exception is raised.


2 Answers

I guess I'll write this up quickly. This is working fine for me:

try:
  r = requests.get('https://www.google.com/404')
  r.raise_for_status()
except requests.exceptions.HTTPError as err:
  print(err.request.url)
  print(err)
  print(err.response.text)
like image 157
fuzzyTew Avatar answered Sep 27 '22 23:09

fuzzyTew


you can do something like below, which returns the content of the response, in unicode.

response.text

or

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)
    sys.exit(1) 
# 404 Client Error: Not Found for url: http://www.google.com/nothere

here you'll get the full explanation on how to handle the exception. please check out Correct way to try/except using Python requests module?

like image 43
Chandu codes Avatar answered Sep 27 '22 21:09

Chandu codes