Anupam Nair
Anupam Nair

Reputation: 103

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()

Upvotes: 10

Views: 21718

Answers (4)

Chandu
Chandu

Reputation: 2129

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?

Upvotes: 5

fuzzyTew
fuzzyTew

Reputation: 3768

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)

Upvotes: 7

CandyCrusher
CandyCrusher

Reputation: 316

There are some tools you may pick up such as Fiddler, Charles, wireshark.

However, those tools can just display the body of the response without including the reason or error stack why the error raises.

Upvotes: 0

blhsing
blhsing

Reputation: 106465

You can log resp.text if resp.status_code >= 400.

Upvotes: 5

Related Questions