Template request | Bug report | Generate Data Product
Tags: #request #error #exception #handling #python #library
Author: Benjamin Filly
Description: This notebook template explores how to handle errors and exceptions when using the requests library. It provides examples of error handling techniques, including proper status code checking, handling timeouts, and dealing with connection errors.
References:
import requests
url
: URL of the API endpointtimeout
: Timeout in seconds for the requestresponse
: Response to the requests. Usually in data
url = "https://api.example.com/endpoint"
timeout = 100
response = None
try:
response = requests.get(url, timeout=timeout)
response.raise_for_status() # Raises an exception if the response status code is not 2xx
data = response.json()
# Process the data
print("Data retrieved successfully:", data)
except requests.exceptions.RequestException as e:
# Handle connection errors, timeouts, and other request exceptions
print("Error occurred:", e)
except requests.exceptions.HTTPError as e:
# Handle HTTP errors (status codes 4xx and 5xx)
print("HTTP Error occurred:", e)
except ValueError as e:
# Handle JSON decoding errors
print("JSON decoding error occurred:", e)
except Exception as e:
# Handle any other unexpected exceptions
print("An unexpected error occurred:", e)
# Display the response
print(response)