Many API calls or database queries may fail temporarily. Adding retry logic helps make code more resilient.
import time
import requests
def fetch_data_with_retries(url, retries=3, delay=2):
for i in range(retries):
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Attempt {i + 1} failed: {e}")
if i < retries - 1:
time.sleep(delay)
return None # Return None if all attempts fail
# Usage
data = fetch_data_with_retries("https://api.example.com/data")