1. import requests
  2. import time
  3. import random
  4. def retry_api_call(url, max_retries=3, delay=2, backoff_factor=1.5):
  5. """
  6. Retries an API call with exponential backoff.
  7. Args:
  8. url (str): The API endpoint URL.
  9. max_retries (int): The maximum number of retry attempts.
  10. delay (int): Initial delay in seconds.
  11. backoff_factor (float): Factor by which the delay increases with each retry.
  12. Returns:
  13. requests.Response: The response object if successful, None otherwise.
  14. """
  15. for attempt in range(max_retries):
  16. try:
  17. response = requests.get(url) # Or other HTTP method
  18. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  19. return response # Success!
  20. except requests.exceptions.RequestException as e:
  21. if attempt == max_retries - 1:
  22. print(f"API call failed after {max_retries} retries: {e}")
  23. return None # Last attempt failed
  24. else:
  25. wait_time = delay * (backoff_factor ** attempt) + random.uniform(0, 0.5) # Exponential backoff with jitter
  26. print(f"Attempt {attempt + 1} failed. Retrying in {wait_time:.2f} seconds...")
  27. time.sleep(wait_time)
  28. if __name__ == '__main__':
  29. # Example Usage (replace with your actual API URL)
  30. api_url = "https://your-internal-api.com/data" # Replace with your API endpoint
  31. response = retry_api_call(api_url)
  32. if response:
  33. print("API call successful!")
  34. print(response.json()) # Or process the response as needed
  35. else:
  36. print("API call failed after multiple retries.")

Add your comment