Handling Common HTTP Status Codes in Python Requests
When working with the Python requests
library, it's essential to handle different HTTP status codes to ensure your application can respond appropriately to various scenarios. Let's explore how to handle some of the most common HTTP status codes.
Handling Successful Responses
For successful requests, you can use the following code to check the status code and handle the response accordingly:
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f'Request failed with status code: {response.status_code}')
In this example, we check if the status code is 200 (OK), and if so, we process the response data. If the status code is not 200, we print an error message.
Handling Redirection Responses
When a server responds with a 3xx status code, it indicates that the requested resource has been moved to a different location. You can handle these cases as follows:
import requests
response = requests.get('https://example.com')
if response.status_code == 301 or response.status_code == 302:
new_url = response.headers['Location']
print(f'Redirecting to: {new_url}')
response = requests.get(new_url)
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f'Request failed with status code: {response.status_code}')
else:
print(f'Request failed with status code: {response.status_code}')
In this example, we check if the status code is 301 (Moved Permanently) or 302 (Found), and if so, we retrieve the new URL from the Location
header and make a new request to the updated location.
Handling Client and Server Errors
For client errors (4xx) and server errors (5xx), you can use the following approach:
import requests
response = requests.get('https://api.example.com/non-existent-endpoint')
if response.status_code >= 400 and response.status_code < 500:
print(f'Client error: {response.status_code} - {response.text}')
elif response.status_code >= 500:
print(f'Server error: {response.status_code} - {response.text}')
else:
data = response.json()
print(data)
In this example, we check if the status code is in the 4xx range (client error) or the 5xx range (server error), and we print the appropriate error message.
By handling these common HTTP status codes, you can create more robust and user-friendly Python applications that can gracefully handle various server responses.