import requests
import time
def make_api_request(url, options, max_retries=3):
retries = 0
while retries < max_retries:
try:
response = requests.request(options.get('method', 'GET'), url, **options)
if response.ok:
return response.json()
error_data = response.json()
error = error_data.get('error', {})
# Handle specific error types
if response.status_code == 429:
retry_after = error.get('retry_after', 2 ** retries)
print(f"Rate limited. Retrying after {retry_after} seconds...")
time.sleep(retry_after)
retries += 1
continue
if response.status_code >= 500:
# Server error, retry with backoff
backoff_time = 2 ** retries
print(f"Server error. Retrying after {backoff_time} seconds...")
time.sleep(backoff_time)
retries += 1
continue
# Client error, don't retry
print(f"API error: {error.get('message')}")
raise Exception(error.get('message'))
except requests.exceptions.RequestException as e:
# Network error, retry with backoff
if retries == max_retries - 1:
raise e
backoff_time = 2 ** retries
print(f"Request failed: {str(e)}. Retrying after {backoff_time} seconds...")
time.sleep(backoff_time)
retries += 1
raise Exception("Maximum retries reached")