Implementing API Integration in Python
The user wants a Python script that interacts with an external API and includes retry logic with exponential backoff. I'll use the requests library and focus on handling specific HTTP status codes while implementing a retry mechanism. Since they didn't specify an API, I can choose a generic one, like a placeholder. I'll create a function called call_api_with_retries, incorporating logging and comments to enhance clarity. I also need to ensure the backoff formula accounts for jitter. Let's get started!Crafting API Call Functionality
I’m outlining a function called call_api_with_retries that integrates retry logic with exponential backoff for API calls. In this function, I’ll track attempts and wait times, raising a custom exception for retryable status codes like 429 and 500. Using the Retry-After header for 429 responses is a thoughtful touch to consider. I also plan to make the script runnable as __main__, demonstrating a simple call to an external API. I’ll use built-in modules and requests, mentioning the need for pip install requests. Below is a self-contained Python script that:
- Calls an external HTTP API using
requests
- Retries on transient failures
- Uses exponential backoff (with optional jitter)
- Retries on specific HTTP status codes and network errors
#!/usr/bin/env python3
"""
Example: API client with exponential backoff retries.
Requires:
pip install requests
"""
import time
import random
from typing import Any, Dict, Optional
import requests
from requests import Response
class TransientAPIError(Exception):
"""Raised when the API response suggests a transient problem (e.g., 5xx)."""
pass
def call_api_with_retries(
url: str,
method: str = "GET",
*,
params: Optional[Dict[str, Any]] = None,
json: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
timeout: float = 5.0,
max_retries: int = 5,
initial_backoff: float = 0.5, # seconds
backoff_factor: float = 2.0,
max_backoff: float = 30.0,
jitter: float = 0.1, # seconds
retry_statuses: Optional[set] = None,
) -> Response:
"""
Call an external HTTP API with retries and exponential backoff.
Raises:
requests.RequestException – if a non-retryable error occurs
TransientAPIError – if retries are exhausted on retryable error
"""
if retry_statuses is None:
# HTTP statuses that are commonly worth retrying
retry_statuses = {429, 500, 502, 503, 504}
attempt = 0
backoff = initial_backoff
while True:
attempt += 1
try:
response = requests.request(
method=method,
url=url,
params=params,
json=json,
headers=headers,
timeout=timeout,
)
# Check if status code is retryable
if response.status_code in retry_statuses:
# Optional: handle Retry-After header
retry_after = response.headers.get("Retry-After")
if retry_after is not None:
try:
retry_after = float(retry_after)
except ValueError:
retry_after = None
# Decide whether to retry
if attempt > max_retries:
raise TransientAPIError(
f"Max retries exceeded for {url} "
f"(status {response.status_code})"
)
# Calculate delay
delay = min(backoff, max_backoff)
if retry_after is not None:
delay = max(delay, retry_after)
# Optional jitter to reduce thundering herd
delay += random.uniform(0, jitter)
print(
f"[Attempt {attempt}/{max_retries}] "
f"Retryable status {response.status_code}. "
f"Sleeping {delay:.2f} seconds before retry..."
)
time.sleep(delay)
backoff *= backoff_factor
continue # retry the request
# Non-retryable or success: return as-is
return response
except (requests.Timeout, requests.ConnectionError) as exc:
# Network-related errors that are often transient
if attempt > max_retries:
raise TransientAPIError(
f"Max retries exceeded for {url} due to network errors"
) from exc
delay = min(backoff, max_backoff)
delay += random.uniform(0, jitter)
print(
f"[Attempt {attempt}/{max_retries}] Network error: {exc}. "
f"Sleeping {delay:.2f} seconds before retry..."
)
time.sleep(delay)
backoff *= backoff_factor
except requests.RequestException:
# Other request exceptions are treated as non-retryable
raise
def main() -> None:
# Example: call an external API (httpbin) and retry if it fails
url = "https://httpbin.org/status/500" # always 500 for demo
try:
response = call_api_with_retries(
url,
method="GET",
max_retries=4,
initial_backoff=0.5,
backoff_factor=2.0,
max_backoff=10.0,
)
print("Final status:", response.status_code)
print("Response body:", response.text[:200])
except TransientAPIError as e:
print("Request failed after retries:", e)
except requests.RequestException as e:
print("Non-retryable request error:", e)
if __name__ == "__main__":
main()
To adapt this to your own external API:
- Change
url, method, params, and json in main() (or wherever you call call_api_with_retries).
- Adjust
retry_statuses if your API uses different status codes for transient failures.
- Optionally tweak
max_retries, initial_backoff, backoff_factor, and max_backoff to match your rate-limit and latency requirements.