Handling API errors using Python requests

I’m hoping this little code snippet will help someone else. I was writing a few functions in Python to interact with an API and wanted to stop processing any remaining code in the function, but I wanted to know why it failed at the calling level.

So, here it is. We first make our initial request using the requests library and then have except blocks for each error type:

        try:
            response = requests.post(_url, files={'file': some_file})
            response.raise_for_status()
        except requests.exceptions.HTTPError as errh:
            return "An Http Error occurred:" + repr(errh)
        except requests.exceptions.ConnectionError as errc:
            return "An Error Connecting to the API occurred:" + repr(errc)
        except requests.exceptions.Timeout as errt:
            return "A Timeout Error occurred:" + repr(errt)
        except requests.exceptions.RequestException as err:
            return "An Unknown Error occurred" + repr(err)

I hope this helps someone in the future, especially when writing Python functions to talk with APIs.

2 Likes

Hey @joshswimlane
This looks great!
Thanks!

No problem! Let me know if you think of any other code snippets like this that may be helpful!

thank bro; very useful!
here are a lot of other requests errors to catch:

requests.exceptions.
requests.exceptions.BaseHTTPError(
requests.exceptions.ChunkedEncodingError(
requests.exceptions.ConnectTimeout(
requests.exceptions.ConnectionError(
requests.exceptions.ContentDecodingError(
requests.exceptions.FileModeWarning(
requests.exceptions.HTTPError(
requests.exceptions.InvalidHeader(
requests.exceptions.InvalidProxyURL(
requests.exceptions.InvalidSchema(
requests.exceptions.InvalidURL(
requests.exceptions.MissingSchema(
requests.exceptions.ProxyError(
requests.exceptions.ReadTimeout(
requests.exceptions.RequestException(
requests.exceptions.RequestsDependencyWarning(
requests.exceptions.RequestsWarning(
requests.exceptions.RetryError(
requests.exceptions.SSLError(
requests.exceptions.StreamConsumedError(
requests.exceptions.Timeout(
requests.exceptions.TooManyRedirects(
requests.exceptions.URLRequired(
requests.exceptions.UnrewindableBodyError(

2 Likes

Great to know, thanks for sharing this code could be really usefull.

1 Like

Awesome! Thanks! I’ll add these to the code snippet above! Thanks!