1

How do I access the error stream using the Python requests library? For example, using HttpURLConnection in Java, I would do something like:

InputStream errorStream = conn.getErrorStream();

Is there a function like this with requests?
I'm looking for the error message in the response that was supplied by the source, NOT the error status e.g. Internal Server Error

3
  • You mean the body content of the response? Commented Oct 13, 2017 at 11:46
  • Well, in Java calling getInputStream, which gets the response content, would throw an exception if the response code was an error response. In that situation you'd have to call getErrorStream. Are you saying that requests treats them both the same? So calling response.text will give me whatever is available? Commented Oct 13, 2017 at 11:51
  • Well, give it a try. Commented Oct 13, 2017 at 11:53

1 Answer 1

1

requests won't raise an exception if HTTP error occurs, but you can get the error message in the response content. Example:

url = 'https://stackoverflow.com/does_not_exist'
r = requests.get(url)
print(r.status_code, r.reason)
print(r.text)
Sign up to request clarification or add additional context in comments.

2 Comments

I'd misunderstood HTTP responses in general. I thought error responses were set in a separate part of the raw response, but presumably the Java example I posted forces you to call getErrorStream to make sure you know you're retrieving an error response, to prevent accidentally calling getInputStream thinking your response is good.
You can raise HTTPError exceptions if you want with raise_for_status()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.