Exception Handling Of Python Requests Module

Pavol Kutaj
1 min readMay 5, 2021

The aim of this playbook🏁 is to share a personal template for exception handling of the Python requests module.

First things first: what is not stressed enough is that if you want to raise an exception for 4xx/5xx HTTP status errors, you need the raise_for_status() method.

The HTTPError alone does not catch 4xx/5xx (e.g. also authentication failures, server outages that return with 5xx, etc.)

Also, in code around me, I am regularly finding something like which is not enough

try:
response = requests.get(url, auth=token)
except:
print("ERROR: Failed to establish connection")
raise
  • first, a personal real-life code I am using for the deletion of a document from Zendesk Guide (Knowledge base)
  • the HTTPError is (also) raised by response.raise_for_status() - if the HTTP Request returned an unsuccesful status code (4xx/5xx)
  • exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException
  • The official Requests exception docs offer more fine tuned exception types
  • in other words and if need be, create a dedicated exception block for each error type as the following example from SO

SOURCES

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com