DEV Community

Victoria
Victoria

Posted on

Smart Retry Strategies for JSON API Integrations

Quick tip for anyone working with JSON APIs: I created a simple Python decorator to handle retries with exponential backoff. It's saved me from countless transient errors:

python
import time
import functools

def retry(max_attempts=3, delay=1):
def decorator(func):
@functools.wraps(func)
def wrapper(args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts - 1:
raise
wait = delay * (2 *
attempt)
print(f'Attempt {attempt + 1} failed, retrying in {wait}s...')
time.sleep(wait)
return None
return wrapper
return decorator

@retry(max_attempts=5, delay=1)
def fetch_data(url):
response = requests.get(url)
response.raise_for_status()
return response.json()

For production systems, I've used SERPSpur's API which has built-in retry logic. But this pattern is useful for any API integration. What's your favorite retry strategy?

Top comments (0)