Collection of Python implementations for handling API calls with token refresh retry logic.
When processing multiple items through an API, authentication tokens can expire mid-process. This requires:
- Looping through items
- Retrying API calls when tokens expire
- Refreshing tokens between retries
- Avoiding nested loop complexity
Baseline implementation with explicit nested loops.
Pros: Clear control flow
Cons: Nested structure can be hard to follow
Separates retry logic into a dedicated function.
Pros: Better separation of concerns
Cons: Still uses nested structure internally
Uses break and continue to flatten control flow.
Pros: Simplest to understand
Cons: Still has explicit loops
Abstracts retry attempts through a generator function.
Pros: More readable retry logic
Cons: Adds abstraction layer
Eliminates loops entirely using recursion.
Pros: Functional programming style, no explicit loops
Cons: Stack depth concerns for many retries
Encapsulates retry logic in a reusable decorator.
Pros: Most reusable, clean separation
Cons: Slightly more complex setup
Uses map() and itertools for functional approach.
Pros: Functional style, no explicit top-level loops
Cons: Less familiar to some developers
Uses the tenacity library for declarative retry logic.
Pros: Industry standard, handles edge cases, battle-tested
Cons: External dependency
Requires: pip install tenacity
- For production:
api_retry_tenacity.py- Industry standard with robust error handling - For learning:
api_retry_flat.py- Easiest to understand - For reusability:
api_retry_decorator.py- Apply to any API function - For functional style:
api_retry_recursive.pyorapi_retry_itertools.py
All implementations follow the same interface:
results = process_items_with_retry(
items=items,
api_call_func=make_api_call,
get_token_func=get_auth_token,
max_retries=3,
retry_delay=2
)Each returns a list of result dictionaries:
{
'item': <original_item>,
'response': <api_response>, # on success
'error': <error_message>, # on failure
'status': 'success' | 'failed'
}