Error handling
When an error occurs, the API returns an error object:
{
"error": {
"code": "ERROR_CODE",
"message": "A human-readable error message"
}
}
Common HTTP status codes:
- 200: OK
- 201: Created
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 429: Too Many Requests
- 500: Internal Server Error
Proper error handling is crucial for creating robust applications that integrate with APIs. Here are some best practices:
- Check Status Codes: Always check the HTTP status code of the response to determine if the request was successful.
- Read Error Messages: Most APIs will provide detailed error messages in the response body. Parse and log these for debugging.
- Implement Retry Logic: For transient errors (like 429 Too Many Requests or 503 Service Unavailable), implement a retry mechanism with exponential backoff.
- Handle Rate Limiting: Respect rate limits imposed by the API. Look for headers like
X-RateLimit-Remainingand adjust your request rate accordingly. - Validate Input: Before sending requests, validate your input to catch errors early and reduce unnecessary API calls.
- Use Try-Catch Blocks: Wrap API calls in try-catch blocks to handle exceptions gracefully.
import requests
import time
def make_api_request(url, max_retries=3, backoff_factor=0.1):
retries = 0
while retries < max_retries:
try:
response = requests.get(url)
response.raise_for_status() # Raises an HTTPError for bad responses
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429: # Too Many Requests
retry_after = int(e.response.headers.get('Retry-After', 1))
print(f"Rate limited. Retrying after {retry_after} seconds.")
time.sleep(retry_after)
elif 500 <= e.response.status_code < 600: # Server errors
print(f"Server error: {e}. Retrying...")
time.sleep(backoff_factor * (2 ** retries))
else:
print(f"HTTP error occurred: {e}")
break # Don't retry for client errors
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
break
retries += 1
print("Max retries reached. Request failed.")
return None
# Usage
data = make_api_request('https://api.example.com/users')
if data:
print("Request successful:", data)
else:
print("Failed to retrieve data")
tip
By following these error handling practices, you can create more resilient applications that gracefully handle API integration challenges.