import requests
import time
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://theslow.net/api"
ENDPOINT = "/some-endpoint-that-might-hit-rate-limit" # Replace with an actual endpoint
headers = {
"X-API-KEY": API_KEY,
"Content-Type": "application/json"
}
def make_api_call_with_retry(url, headers, max_retries=5):
retries = 0
while retries < max_retries:
try:
response = requests.get(url, headers=headers)
if response.status_code == 429:
reset_time = int(response.headers.get('X-RateLimit-Reset', time.time() + 60))
wait_time = reset_time - int(time.time()) + 1 # Add 1 second buffer
print(f"Rate limit hit. Waiting for {wait_time} seconds before retrying...")
time.sleep(max(0, wait_time)) # Ensure wait_time is not negative
retries += 1
continue # Retry the request
response.raise_for_status()
print("Request successful:", response.json())
return response.json()
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
if response:
print(f"Response body: {response.text}")
break # Exit on other HTTP errors
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred: {conn_err}")
time.sleep(2 ** retries) # Exponential backoff for connection errors
retries += 1
except Exception as err:
print(f"An unexpected error occurred: {err}")
break # Exit on unexpected errors
print("Max retries exceeded or unhandled error.")
return None
# Example usage:
# make_api_call_with_retry(f"{BASE_URL}{ENDPOINT}", headers)