#!/usr/bin/env python3
"""
Python script that integrates with an external API (using JSONPlaceholder as example)
and retries on failure with exponential backoff.
Requirements:
- pip install requests
Usage:
python api_retry_script.py
"""
import requests
import time
import sys
from typing import Optional, Dict, Any
def fetch_api_data(
url: str,
max_retries: int = 5,
base_delay: float = 1.0,
timeout: int = 10
) -> Dict[str, Any]:
"""
Fetch data from the API with exponential backoff on failure.
:param url: API endpoint URL
:param max_retries: Maximum number of retries
:param base_delay: Base delay in seconds for backoff
:param timeout: Request timeout in seconds
:return: JSON response data
:raises: requests.exceptions.RequestException on final failure
"""
for attempt in range(max_retries + 1):
try:
print(f"Making request to {url} (attempt {attempt + 1}/{max_retries + 1})")
response = requests.get(url, timeout=timeout)
response.raise_for_status() # Raises HTTPError for bad responses
data = response.json()
print("Success! Data fetched.")
return data
except requests.exceptions.Timeout:
error_msg = "Request timed out"
except requests.exceptions.HTTPError as e:
error_msg = f"HTTP error: {e}"
except requests.exceptions.ConnectionError:
error_msg = "Connection error"
except requests.exceptions.RequestException as e:
error_msg = f"Request failed: {e}"
except ValueError as e:
error_msg = f"Invalid JSON response: {e}"
except Exception as e:
error_msg = f"Unexpected error: {e}"
if attempt == max_retries:
print(f"Max retries ({max_retries}) reached. Final error: {error_msg}")
raise requests.exceptions.RequestException(error_msg)
# Exponential backoff: delay = base_delay * 2^attempt + jitter
delay = base_delay * (2 ** attempt) + (0.1 * attempt) # Small jitter for variance
print(f"Attempt {attempt + 1} failed: {error_msg}. Retrying in {delay:.2f}s...")
time.sleep(delay)
def main():
# Example API: JSONPlaceholder (free fake REST API)
api_url = "https://jsonplaceholder.typicode.com/posts/1"
# To test retries, temporarily change to a bad URL like "https://jsonplaceholder.typicode.com/nonexistent"
# or run behind a flaky network
try:
data = fetch_api_data(api_url)
print("\nFetched data:")
print(f"Title: {data.get('title', 'N/A')}")
print(f"Body: {data.get('body', 'N/A')[:100]}...") # Truncate for brevity
print(f"User ID: {data.get('userId', 'N/A')}")
except Exception as e:
print(f"Failed to fetch data after retries: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Key Features:
External API Integration: Uses requests to call a public API (JSONPlaceholder). Easily swap the api_url.
Retry Logic: Up to 5 retries on various failures (timeout, HTTP errors, connection issues, invalid JSON).
Exponential Backoff: Delay starts at 1s, doubles each attempt (1s, 2s, 4s, 8s, 16s) + small jitter.
Robust Error Handling: Catches specific requests exceptions and generics.
Timeout: Prevents hanging (10s default).
Logging: Prints progress for visibility.
Testable: Uncomment/change URL to a bad endpoint (e.g., /nonexistent) to see retries in action.
Run it: python api_retry_script.py. It works out-of-the-box with a reliable API but gracefully retries on failures!