How to raise exception for http errors in python?

Python request module is very rich to run the http methods such as get, post, put or delete etc. It is useful and easy to use in python programs. In case when http errors we can easily raise the exceptions in python.

Let say we want the http errors such as 404 not found or 401 Unauthorized etc to raise exceptions, we can write the following code:

try:
    r = requests.get(API_URL)
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    print err

If we want specific exception then following is the requests exception docs:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.
If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.
Share