Skip to content

Latest commit

 

History

History
71 lines (50 loc) · 2.68 KB

Request_Handling_Errors_and_Exceptions.md

File metadata and controls

71 lines (50 loc) · 2.68 KB



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:

Input

Import libraries

import requests

Setup Variables

  • url: URL of the API endpoint
  • timeout: Timeout in seconds for the request
  • response: Response to the requests. Usually in data
url = "https://api.example.com/endpoint"
timeout = 100
response = None

Model

Making a Request

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)

Output

Display result

# Display the response
print(response)