Interview Prep/Python for DevOps/Data formats, HTTP & REST APIs

How do you add retries with exponential backoff to `requests`?

IntermediateConceptData formats, HTTP & REST APIs
Answer

Mount an HTTPAdapter configured with urllib3's Retry:

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=5, connect=5, read=3, backoff_factor=0.5,
              status_forcelist=(429, 500, 502, 503, 504),
              allowed_methods=frozenset({"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}),
              respect_retry_after_header=True)
s = requests.Session()
s.mount("https://", HTTPAdapter(max_retries=retry, pool_maxsize=20))

Backoff grows as backoff_factor * 2 ** (retry - 1), capped by backoff_max. POST is excluded by default because it is not idempotent.

All Python for DevOps questions Roadmap: Python for automation

More on Data formats, HTTP & REST APIs