Skip to main content

A production-ready, reliable HTTP client for Python.

Project description

relihttp

A production-ready, reliable HTTP client for Python

English | 简体中文

Python Requests License Status

📖 Quick Start✨ Features🧰 Development🏗️ Architecture🔧 Configuration🤝 Contributing

🌟 Why choose relihttp?

relihttp is a lightweight HTTP client built on requests with reliability features enabled by default. It provides a policy-based design that makes behaviors easy to customize or replace.

🎯 Reliability by Default Fast Development 🛡️ Customizable 📊 Structured Logging
Built-in timeouts, retries, and rate limiting Simple API with sensible defaults Policy-based architecture Standard logging with request/response details

Status

Alpha (v0.1.0). APIs may change.

✨ Core Features

🔧 Reliability Controls

  • Timeout Control - Global and per-request timeout settings
  • Smart Retries - Retry policy for safe methods by default
  • Exponential Backoff - With jitter to prevent thundering herds
  • Network Resilience - Retries on network errors and select HTTP status codes
  • Circuit Breaker - Prevent cascading failures under error bursts
  • Idempotency Keys - Safe retries for non-idempotent methods

📦 Rate Limiting

  • Token Bucket Algorithm - Smooth rate limiting
  • Flexible Modes - sleep (wait for tokens) or raise (fail fast)
  • Per-Client Configuration - Easy to adjust for different endpoints

📝 Logging & Observability

  • Structured Logging - Standard logging module integration
  • Rich Context - Request ID, method, URL, status, and timing information
  • Event Types - http.request, http.response, http.error events
  • Tracing Headers - Inject request/trace IDs for end-to-end tracking

🏗️ Extensible Architecture

  • Policy-Based Design - Easy to add or replace behaviors
  • Pluggable Transport - Defaults to requests, but customizable
  • Middleware Hooks - Before/after request and retry decision callbacks

🎨 Developer Experience

  • Familiar API - Built on requests interface
  • Per-Request Overrides - Customize settings for individual requests
  • Type Hints - Full Python type annotations support
  • Clear Documentation - Comprehensive guides and examples
  • AsyncIO Support - Async client and transport (optional aiohttp)

Installation

pip install relihttp

🧰 Development with uv

uv is the recommended package manager for development. It provides faster installation and better dependency management.

Install uv

# Install uv (if not already installed)
pip install uv

Common Commands

# Create a virtual environment
uv venv

# Activate the virtual environment
source .venv/bin/activate  # Linux/macOS
.venv\Scripts\activate     # Windows

# Install dependencies
uv install

# Install with development dependencies
uv install -e .[dev]

# Run tests
uv run pytest

# Run tests with coverage
uv run pytest --cov=relihttp

# Format code with ruff
uv run ruff format

# Lint code with ruff
uv run ruff check

# Type check with mypy
uv run mypy

# Build the package
uv build

# Clean up
uv clean

📦 Packaging & Publish

Build locally

# Build sdist and wheel into dist/
uv build

Publish to PyPI

# 1) Create API token on PyPI and export it
export TWINE_USERNAME="__token__"
export TWINE_PASSWORD="pypi-***"

# 2) Upload
python -m pip install twine
twine upload dist/*

Publish to TestPyPI (recommended first)

export TWINE_USERNAME="__token__"
export TWINE_PASSWORD="pypi-***"

python -m pip install twine
twine upload --repository testpypi dist/*

🛠️ Technology Stack

Component Technology Version
Core HTTP Client requests 2.0+
Python Version Python 3.9+
Logging Standard logging module -
Architecture Policy-based middleware -

🚀 Quick Start (Sync)

from relihttp import Client

client = Client(
    base_url="https://api.example.com",
    timeout=3.0,
    retry="safe",
    max_retries=3,
    rate_limit=100,
)

resp = client.get("/users")
print(resp.json())

Per-request overrides:

client.post("/pay", json={"amount": 10}, timeout=1.5, max_retries=1)

⚡ Async Quick Start

import asyncio
from relihttp import AsyncClient

async def main() -> None:
    async with AsyncClient(
        base_url="https://api.example.com",
        timeout=3.0,
        retry="safe",
        max_retries=3,
    ) as client:
        resp = await client.get("/users")
        print(resp.text)

asyncio.run(main())

🔧 Usage Examples

Sync Client (Basic)

from relihttp import Client

client = Client(base_url="https://api.example.com")
resp = client.get("/health")
print(resp.status_code)

Sync Client (Custom Policies)

from relihttp import Client
from relihttp.policies.circuit import CircuitBreakerPolicy
from relihttp.policies.idempotency import IdempotencyPolicy
from relihttp.policies.tracing import TracingPolicy
from relihttp.policies.timeout import TimeoutPolicy
from relihttp.policies.retry import RetryPolicy
from relihttp.policies.logger import LoggingPolicy
from relihttp.policies.rate_limit import RateLimitPolicy

client = Client(
    policies=[
        TimeoutPolicy(timeout=3.0),
        RetryPolicy(max_retries=3, retry="safe"),
        RateLimitPolicy(rate_limit=50, burst=100, mode="sleep"),
        CircuitBreakerPolicy(window_size=20, failure_ratio=0.5, min_requests=10),
        IdempotencyPolicy(),
        TracingPolicy(request_id_header="X-Request-ID", trace_id_header="X-Trace-ID"),
        LoggingPolicy(),
    ]
)

resp = client.post("/payments", json={"amount": 10})
print(resp.status_code)

Async Client (Basic)

import asyncio
from relihttp import AsyncClient

async def main() -> None:
    async with AsyncClient() as client:
        resp = await client.get("https://example.com")
        print(resp.status_code)

asyncio.run(main())

Async Client (Per-request Override)

import asyncio
from relihttp import AsyncClient

async def main() -> None:
    async with AsyncClient(base_url="https://api.example.com") as client:
        resp = await client.post("/pay", json={"amount": 10}, timeout=1.5, max_retries=1)
        print(resp.text)

asyncio.run(main())

Async Client (Custom Transport)

import asyncio
from relihttp import AsyncClient
from relihttp.transport.aiohttp import AiohttpTransport

async def main() -> None:
    transport = AiohttpTransport()
    async with AsyncClient(transport=transport) as client:
        resp = await client.get("https://example.com")
        print(resp.status_code)

asyncio.run(main())

🔧 Configuration

Enable additional reliability features with simple flags:

from relihttp import Client

client = Client(
    base_url="https://api.example.com",
    circuit_breaker=True,
    idempotency=True,
    trace=True,
)

Circuit Breaker (Advanced)

from relihttp import Client
from relihttp.policies.circuit import CircuitBreakerPolicy
from relihttp.policies.timeout import TimeoutPolicy
from relihttp.policies.retry import RetryPolicy
from relihttp.policies.logger import LoggingPolicy

client = Client(
    policies=[
        TimeoutPolicy(timeout=3.0),
        RetryPolicy(max_retries=3, retry="safe"),
        LoggingPolicy(),
        CircuitBreakerPolicy(failure_threshold=3, recovery_timeout=10.0),
    ]
)

Idempotency Key (Advanced)

from relihttp import Client
from relihttp.policies.idempotency import IdempotencyPolicy
from relihttp.policies.timeout import TimeoutPolicy
from relihttp.policies.retry import RetryPolicy
from relihttp.policies.logger import LoggingPolicy

client = Client(
    policies=[
        TimeoutPolicy(timeout=3.0),
        RetryPolicy(max_retries=3, retry="safe"),
        LoggingPolicy(),
        IdempotencyPolicy(header_name="Idempotency-Key"),
    ]
)

Tracing & Request ID (Advanced)

from relihttp import Client
from relihttp.policies.tracing import TracingPolicy
from relihttp.policies.timeout import TimeoutPolicy
from relihttp.policies.retry import RetryPolicy
from relihttp.policies.logger import LoggingPolicy

client = Client(
    policies=[
        TimeoutPolicy(timeout=3.0),
        RetryPolicy(max_retries=3, retry="safe"),
        LoggingPolicy(),
        TracingPolicy(request_id_header="X-Request-ID", trace_id_header="X-Trace-ID"),
    ]
)

Async Client (AsyncIO)

 # Install async support:
 # pip install relihttp[async]
 
import asyncio
from relihttp import AsyncClient

async def main() -> None:
    async with AsyncClient() as client:
        resp = await client.get("https://example.com")
        print(resp.status_code)

asyncio.run(main())

Retry Behavior

Default retry="safe" only retries idempotent methods: GET, HEAD, OPTIONS, PUT, DELETE.
Retries are triggered for network errors from requests and for HTTP status codes 500, 502, 503, 504, 429.

max_retries is the maximum total attempts (including the first try).

Custom policy example:

from relihttp import Client
from relihttp.policies.retry import RetryPolicy
from relihttp.policies.timeout import TimeoutPolicy
from relihttp.policies.logger import LoggingPolicy

client = Client(
    policies=[
        TimeoutPolicy(timeout=2.0),
        RetryPolicy(max_retries=5, retry="all", retry_on_status=[500, 502, 503]),
        LoggingPolicy(),
    ]
)

Rate Limiting

rate_limit is tokens per second. By default, the limiter blocks until a token is available.
You can switch to raise mode to fail fast; it raises RateLimitedError.

from relihttp import Client
from relihttp.policies.rate_limit import RateLimitPolicy
from relihttp.policies.timeout import TimeoutPolicy
from relihttp.policies.retry import RetryPolicy
from relihttp.policies.logger import LoggingPolicy

client = Client(
    policies=[
        TimeoutPolicy(timeout=3.0),
        RetryPolicy(max_retries=3),
        RateLimitPolicy(rate_limit=50, burst=100, mode="raise"),
        LoggingPolicy(),
    ]
)

Logging

The library emits structured logs through the relihttp logger with event names:

  • http.request
  • http.response
  • http.error

Each record includes fields like request_id, method, url, attempt, status_code, and elapsed_ms. Configure handlers and formatters via the standard logging module.

Policies and Transport

Client(policies=...) uses exactly the policies you pass; defaults are not added automatically.
If you override policies, include TimeoutPolicy, RetryPolicy, and LoggingPolicy explicitly as needed.

The default transport is RequestsTransport, built on requests.Session. You can implement your own transport by subclassing Transport and passing it to Client(transport=...).

📁 Project Structure

relihttp/
  __init__.py                 # Package initialization
  client.py                   # Main Client class
  async_client.py             # Async Client (AsyncIO)
  models.py                   # Data models
  transport/                  # Transport layer implementations
    base.py                  # Transport base class
    requests.py              # Requests-based transport
    async_base.py            # Async transport base class
    aiohttp.py               # aiohttp-based transport
  policies/                   # Policy implementations
    base.py                  # Policy base class
    retry.py                 # Retry policy
    timeout.py               # Timeout policy
    rate_limit.py            # Rate limiting policy
    logger.py                # Logging policy
    circuit.py               # Circuit breaker policy
    idempotency.py           # Idempotency key support
    tracing.py               # Tracing support
  utils.py                    # Utility functions
tests/                        # Test suite
pyproject.toml               # Project configuration
README.md                    # English documentation
README-ZH.md                 # Chinese documentation

🔮 Roadmap (Planned)

  • OpenTelemetry Integration - Standardized tracing propagation
  • More Transports - httpx/urllib3 support

📋 Requirements

  • Python 3.9+

🤝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Run tests before submitting:

pytest

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

💡 Philosophy

Reliability should be the default, not an afterthought.

We believe that building resilient systems shouldn't require complex configuration or boilerplate code. relihttp provides reliability features out of the box, so you can focus on building your application rather than worrying about network failures or transient errors.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

relihttp-0.1.0.tar.gz (137.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

relihttp-0.1.0-py3-none-any.whl (20.0 kB view details)

Uploaded Python 3

File details

Details for the file relihttp-0.1.0.tar.gz.

File metadata

  • Download URL: relihttp-0.1.0.tar.gz
  • Upload date:
  • Size: 137.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.13

File hashes

Hashes for relihttp-0.1.0.tar.gz
Algorithm Hash digest
SHA256 5a9af30315fa0d87592e41564240500fd496315d184045d60fb1f88948bd9edd
MD5 65342bf60d5d0cc28fb7f124b040b5a3
BLAKE2b-256 6ebc96b5addcd09ceff8e1eb1c1772950dbe984e48c29b6b5ad7dc6e5041f2b5

See more details on using hashes here.

File details

Details for the file relihttp-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: relihttp-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 20.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.13

File hashes

Hashes for relihttp-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2a16c389da2eb0f6c6474ca7faf11cdb70e50b59c71a0e4fcb3a4f7228f6167f
MD5 81e146299e49a72ad703afe419dbc5ec
BLAKE2b-256 9dbd740bb0d74d9525c5fc50339a188f991707d6d0377425ccd0a137871b1c6b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page