The Python Requests library makes it easy to interact with web APIs and services. A key aspect of working with APIs is properly handling HTTP status codes in your Python code. Requests provides convenient ways to check status codes and take appropriate actions.
When you make a request with Requests, the
import requests
response = requests.get('https://api.example.com/users')
print(response.status_code)
# 200
While you could directly compare the status code to numeric values like 200, 401 etc., Requests provides more readable attributes that evaluate to True or False:
if response.ok:
# Status code 200-299
if response.status_code == requests.codes.NOT_FOUND:
# Handle 404 error
This makes status code handling easy to read and maintain. Some common status code checks:
For web APIs, 4xx client errors and 5xx server errors are common. When an error occurs, you need to handle it appropriately in your code instead of letting the script crash:
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.HTTPError as err:
# Log error details
print(f"HTTP Error: {err}")
except requests.exceptions.ConnectionError:
# Network error
print("Network error occurred")
Carefully handling status codes is important for writing robust Python code that interacts with web services. Requests makes status code checking concise and clean.