HTTPX Retries

0.4.6 · active · verified Fri Apr 10

HTTPX Retries is a Python library that provides a comprehensive retry layer for HTTPX, addressing common issues with flaky and unreliable APIs. It offers an API surface similar to `urllib3.util.retry.Retry`, making it familiar for users migrating from `requests`. The library supports both synchronous and asynchronous HTTPX clients and is actively maintained with frequent releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates both synchronous and asynchronous usage of `httpx-retries`. It shows how to apply the `RetryTransport` with its default retry strategy and how to configure a custom `Retry` strategy with parameters like `total` retries, `backoff_factor`, and `statuses_forcelist` to specify which HTTP status codes should trigger a retry. The example attempts to retrieve a 503 status, which will trigger the retry logic.

import httpx
from httpx_retries import RetryTransport, Retry

def sync_example():
    # Basic usage with default retry strategy
    with httpx.Client(transport=RetryTransport()) as client:
        print("Sync Client (default retries):")
        try:
            response = client.get("https://httpbin.org/status/503")
            print(f"  Status: {response.status_code}")
        except httpx.HTTPStatusError as e:
            print(f"  Failed after retries: {e.response.status_code}")

    # Custom retry strategy
    custom_retry = Retry(total=5, backoff_factor=0.5, statuses_forcelist=[503, 504])
    with httpx.Client(transport=RetryTransport(retry=custom_retry)) as client:
        print("\nSync Client (custom retries):")
        try:
            response = client.get("https://httpbin.org/status/503")
            print(f"  Status: {response.status_code}")
        except httpx.HTTPStatusError as e:
            print(f"  Failed after retries: {e.response.status_code}")

async def async_example():
    # Async usage with default retry strategy
    async with httpx.AsyncClient(transport=RetryTransport()) as client:
        print("\nAsync Client (default retries):")
        try:
            response = await client.get("https://httpbin.org/status/503")
            print(f"  Status: {response.status_code}")
        except httpx.HTTPStatusError as e:
            print(f"  Failed after retries: {e.response.status_code}")

    # Async usage with custom retry strategy
    custom_retry = Retry(total=5, backoff_factor=0.5, statuses_forcelist=[503, 504])
    async with httpx.AsyncClient(transport=RetryTransport(retry=custom_retry)) as client:
        print("\nAsync Client (custom retries):")
        try:
            response = await client.get("https://httpbin.org/status/503")
            print(f"  Status: {response.status_code}")
        except httpx.HTTPStatusError as e:
            print(f"  Failed after retries: {e.response.status_code}")

if __name__ == "__main__":
    sync_example()
    import asyncio
    asyncio.run(async_example())

view raw JSON →