import requests
import time
import random
def retry_api_call(url, max_retries=3, delay=2, backoff_factor=1.5):
"""
Retries an API call with exponential backoff.
Args:
url (str): The API endpoint URL.
max_retries (int): The maximum number of retry attempts.
delay (int): Initial delay in seconds.
backoff_factor (float): Factor by which the delay increases with each retry.
Returns:
requests.Response: The response object if successful, None otherwise.
"""
for attempt in range(max_retries):
try:
response = requests.get(url) # Or other HTTP method
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response # Success!
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
print(f"API call failed after {max_retries} retries: {e}")
return None # Last attempt failed
else:
wait_time = delay * (backoff_factor ** attempt) + random.uniform(0, 0.5) # Exponential backoff with jitter
print(f"Attempt {attempt + 1} failed. Retrying in {wait_time:.2f} seconds...")
time.sleep(wait_time)
if __name__ == '__main__':
# Example Usage (replace with your actual API URL)
api_url = "https://your-internal-api.com/data" # Replace with your API endpoint
response = retry_api_call(api_url)
if response:
print("API call successful!")
print(response.json()) # Or process the response as needed
else:
print("API call failed after multiple retries.")
Add your comment