python requests when error

hljs.highlightAll();

Python Requests Error Handling

Python Requests is a popular library used for making HTTP requests in Python. However, when making requests, sometimes errors can occur. It’s important to handle these errors appropriately to ensure the stability and reliability of your application.

Handling Common HTTP Errors

When making HTTP requests, there are several common errors that can occur, such as:

  • 404 Not Found
  • 401 Unauthorized
  • 500 Internal Server Error

To handle these errors, you can use the response.status_code attribute of the response object. For example:


import requests

response = requests.get('https://www.example.com/notfound')
if response.status_code == 404:
    print('Page not found')
elif response.status_code == 401:
    print('Unauthorized')
elif response.status_code == 500:
    print('Internal server error')
else:
    print('Request successful')
  

Handling Connection Errors

Connection errors can also occur when making HTTP requests, such as:

  • requests.exceptions.ConnectionError
  • requests.exceptions.Timeout

To handle these errors, you can use a try-except block. For example:


import requests

try:
    response = requests.get('https://www.example.com', timeout=5)
    response.raise_for_status()
except requests.exceptions.ConnectionError:
    print('Connection error')
except requests.exceptions.Timeout:
    print('Request timed out')
else:
    print('Request successful')
  

Handling Other Errors

In addition to the above errors, other errors can occur when making HTTP requests. To handle these errors, you can use the response.raise_for_status() method. This method will raise an exception if the status code of the response indicates an error. For example:


import requests

response = requests.get('https://www.example.com/notfound')
response.raise_for_status()
  

If the status code of the response is not in the 200 range, a HTTPError will be raised.