Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exception for HTTP response codes

I'd like to raise a Python-standard exception when an HTTP response code from querying an API is not 200, but what specific exception should I use? For now I raise an OSError:

if response.status_code != 200:
  raise OSError("Response " + str(response.status_code)
                  + ": " + response.content)

I'm aware of the documentation for built-in exceptions.

like image 931
BoltzmannBrain Avatar asked Jun 15 '15 22:06

BoltzmannBrain


People also ask

How do I get exception status code in Python?

Python exceptions do not have "codes". You can create a custom exception that does have a property called code and then you can access it and print it as desired. This answer has an example of adding a code property to a custom exception. Show activity on this post.


Video Answer


1 Answers

You can simply call Response.raise_for_status() on your response:

>>> import requests
>>> url = 'http://stackoverflow.com/doesnt-exist'
>>> r = requests.get(url)
>>>
>>> print r.status_code
404
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 831, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found

This will raise a requests.HTTPError for any 4xx or 5xx response.

See the docs on Response Status Code for a more complete example.


Note that this does not exactly do what you asked (status != 200): It will not raise an exception for 201 Created or 204 No Content, or any of the 3xx redirects - but this is most likely the behavior you want: requests will just follow the redirects, and the other 2xx are usually just fine if you're dealing with an API.

like image 143
Lukas Graf Avatar answered Oct 08 '22 05:10

Lukas Graf