Handling API errors using Python requests

#1

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.

0 Likes