Handling HTTP errors
HTTP errors are a common occurrence when dealing with server communications, and consequently, it's crucial to know how to handle them when using the Python requests module. This tutorial will walk you through the basics of handling HTTP errors in requests.
Understanding HTTP Status Codes
Every HTTP response comes with a status code that informs us about the status of the request made. Some common ones include:
200 OK
: The request was successful.404 Not Found
: The resource you tried to access could not be found on the server.500 Internal Server Error
: The server encountered an unexpected condition.
A detailed list of HTTP status codes can be found here.
Checking the Response Status Code
You can check the status code of a response using the status_code
attribute of the response object. Below is an example:
import requests
response = requests.get('https://httpbin.org/get')
print(response.status_code)
Handling HTTP Errors
There are several ways to handle HTTP errors when using the requests module.
Using HTTP Status Code
One simple approach is to use a conditional statement to check the status code of the response:
import requests
response = requests.get('https://httpbin.org/get')
if response.status_code == 200:
print('Success!')
elif response.status_code == 404:
print('Not Found.')
else:
print('An error has occurred.')
Using the raise_for_status
Method
The raise_for_status
method of the response object will raise a HTTPError
if one occurred:
import requests
response = requests.get('https://httpbin.org/get')
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print('Error: ', err)
else:
print('Success!')
raise_for_status
will raise a requests.exceptions.HTTPError
if the HTTP request returned an unsuccessful status code. If the status code indicates a successful request, the method will return None
.
Remember, error handling is a crucial part of any application that interacts with external systems, such as servers. By understanding and handling HTTP errors, you can make your Python programs more robust and reliable.
We hope this tutorial was helpful in understanding how to handle HTTP errors when using the Python requests module. Practice handling different types of HTTP status codes to get a better understanding of how they work. Happy coding!