Configuration API Reference

This page documents the configuration classes and builders for HTTP Client.

TokenData

class TokenData(access_token, token_type='Bearer', expires_at=None, refresh_token=None, scope=None, extra=None)

Immutable token data container.

Parameters:
  • access_token (str) – The access token string

  • token_type (str) – Token type (default: ‘Bearer’)

  • expires_at (datetime) – Token expiration datetime (optional)

  • refresh_token (str) – Refresh token (optional)

  • scope (str) – Token scope (optional)

  • extra (dict) – Additional token metadata (optional)

Attributes

TokenData.access_token: str

The access token string.

TokenData.token_type: str

Token type (e.g., ‘Bearer’, ‘Basic’).

TokenData.expires_at: datetime | None

Token expiration datetime.

TokenData.refresh_token: str | None

Refresh token for obtaining new access tokens.

TokenData.scope: str | None

Token scope/permissions.

TokenData.extra: dict[str, Any]

Additional token metadata.

Properties

TokenData.is_expired: bool

Check if token is expired (with 30 second buffer).

Example:

if token.is_expired:
    print("Token needs refresh")
TokenData.authorization_header: str

Get the authorization header value.

Example:

token = TokenData(access_token='abc123', token_type='Bearer')
print(token.authorization_header)  # 'Bearer abc123'

Class Methods

classmethod TokenData.from_response(data, expires_in_key='expires_in', access_token_key='access_token', refresh_token_key='refresh_token', token_type_key='token_type')

Create TokenData from API response.

Parameters:
  • data (dict) – Response data dictionary

  • expires_in_key (str) – Key for expires_in field

  • access_token_key (str) – Key for access_token field

  • refresh_token_key (str) – Key for refresh_token field

  • token_type_key (str) – Key for token_type field

Returns:

TokenData instance

Return type:

TokenData

Example:

response_data = {
    'access_token': 'abc123',
    'token_type': 'Bearer',
    'expires_in': 3600,
    'refresh_token': 'xyz789',
    'scope': 'read write'
}

token = TokenData.from_response(response_data)

print(token.access_token)     # 'abc123'
print(token.token_type)       # 'Bearer'
print(token.expires_at)       # datetime object (now + 3600s)
print(token.refresh_token)    # 'xyz789'

Custom Field Names:

# For APIs with different field names
response_data = {
    'token': 'abc123',
    'type': 'Bearer',
    'ttl': 3600
}

token = TokenData.from_response(
    response_data,
    access_token_key='token',
    token_type_key='type',
    expires_in_key='ttl'
)

HttpClientConfig

class HttpClientConfig(base_url='', default_timeout=30.0, default_headers=None, verify_ssl=True, allow_redirects=True, max_redirects=10, retry_strategy=None, auth_hook=None, request_hooks=(), response_hooks=(), error_hooks=(), pool_connection=10, pool_maxsize=20)

Immutable configuration container for HTTP client settings.

Note: This class is frozen (immutable). Use HttpClientConfigBuilder to create instances.

Parameters:
  • base_url (str) – Base URL for all requests

  • default_timeout (float) – Default timeout in seconds

  • default_headers (dict) – Default headers for all requests

  • verify_ssl (bool) – SSL certificate verification

  • allow_redirects (bool) – Follow HTTP redirects

  • max_redirects (int) – Maximum redirect hops

  • retry_strategy (RetryStrategyInterface) – Retry strategy

  • auth_hook (AuthHookInterface) – Authentication hook

  • request_hooks (tuple) – Request hooks

  • response_hooks (tuple) – Response hooks

  • error_hooks (tuple) – Error hooks

  • pool_connection (int) – Connection pool size

  • pool_maxsize (int) – Maximum pool size

Attributes

HttpClientConfig.base_url: str

Base URL for all requests.

HttpClientConfig.default_timeout: float

Default timeout in seconds.

HttpClientConfig.default_headers: dict[str, str]

Default headers included in all requests.

HttpClientConfig.verify_ssl: bool

Whether to verify SSL certificates.

HttpClientConfig.allow_redirects: bool

Whether to follow HTTP redirects.

HttpClientConfig.max_redirects: int

Maximum number of redirect hops.

HttpClientConfig.retry_strategy: RetryStrategyInterface | None

Retry strategy implementation.

HttpClientConfig.auth_hook: AuthHookInterface | None

Authentication hook.

HttpClientConfig.request_hooks: tuple[RequestHookInterface, ...]

Request lifecycle hooks.

HttpClientConfig.response_hooks: tuple[ResponseHookInterface, ...]

Response lifecycle hooks.

HttpClientConfig.error_hooks: tuple[ErrorHookInterface, ...]

Error handling hooks.

HttpClientConfig.pool_connection: int

Connection pool size.

HttpClientConfig.pool_maxsize: int

Maximum connection pool size.

Validation

The configuration validates on creation:

# Raises ValueError
HttpClientConfig(default_timeout=-1)      # Must be positive
HttpClientConfig(max_redirects=-1)        # Must be non-negative

HttpClientConfigBuilder

class HttpClientConfigBuilder

Fluent builder for creating HttpClientConfig instances.

Implements the Builder pattern for flexible, readable configuration.

Basic Configuration

with_base_url(url)

Set base URL for all requests.

Parameters:

url (str) – Base URL

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_base_url('https://api.example.com')
with_timeout(timeout)

Set default timeout in seconds.

Parameters:

timeout (float) – Timeout in seconds

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_timeout(60.0)
with_verify_ssl(verify)

Set SSL verification.

Parameters:

verify (bool) – Whether to verify SSL certificates

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_verify_ssl(True)
with_redirects(allow=True, max_redirects=10)

Configure redirect behavior.

Parameters:
  • allow (bool) – Whether to follow redirects

  • max_redirects (int) – Maximum redirect hops

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_redirects(allow=True, max_redirects=5)

Headers Configuration

with_headers(headers)

Set default headers.

Parameters:

headers (dict) – Headers dictionary

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_headers({
    'User-Agent': 'MyApp/1.0',
    'Accept': 'application/json'
})
with_header(name, value)

Add a single default header.

Parameters:
  • name (str) – Header name

  • value (str) – Header value

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_header('User-Agent', 'MyApp/1.0')
with_bearer_token(token)

Add Bearer token authorization header.

Parameters:

token (str) – Bearer token

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_bearer_token('your-api-token')
with_api_key(api_key, header_name='X-API-Key')

Add API key header.

Parameters:
  • api_key (str) – API key value

  • header_name (str) – Header name (default: ‘X-API-Key’)

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_api_key('your-key', header_name='X-API-Key')

Retry Configuration

with_retry_strategy(strategy)

Set retry strategy.

Parameters:

strategy (RetryStrategyInterface) – Retry strategy instance

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

from requestforge import ExponentialBackoffRetryStrategy

strategy = ExponentialBackoffRetryStrategy(max_retries=5)
builder.with_retry_strategy(strategy)
with_retry(max_retries=3, base_delay=1.0, max_delay=60.0)

Configure exponential backoff retry.

Parameters:
  • max_retries (int) – Maximum retry attempts

  • base_delay (float) – Initial delay in seconds

  • max_delay (float) – Maximum delay cap in seconds

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_retry(
    max_retries=3,
    base_delay=1.0,
    max_delay=60.0
)

Connection Pool Configuration

with_pool_connection(pool_connection=10)

Set connection pool size.

Parameters:

pool_connection (int) – Pool connection size

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_pool_connection(20)
with_pool_maxsize(pool_maxsize=20)

Set maximum pool size.

Parameters:

pool_maxsize (int) – Maximum pool size

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_pool_maxsize(50)

Authentication Configuration

with_auth_hook(auth_hook)

Set authentication hook.

Parameters:

auth_hook (AuthHookInterface) – Authentication hook

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

from requestforge import TokenAuthHook

builder.with_auth_hook(TokenAuthHook(token_manager))
with_token_auth(token_manager, auth_retry_strategy=None, auth_header_name='Authorization', auth_header_prefix='Bearer', excluded_paths=None, excluded_path_patterns=None)

Configure token-based authentication with automatic refresh.

Parameters:
  • token_manager (TokenManagerInterface) – Token manager instance

  • auth_retry_strategy (AuthRetryStrategyInterface) – Auth retry strategy

  • auth_header_name (str) – Header name for auth token

  • auth_header_prefix (str) – Token prefix (e.g., ‘Bearer’)

  • excluded_paths (set) – Paths to exclude from auth

  • excluded_path_patterns (list) – Path patterns to exclude

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

from requestforge import TokenManager, SimpleAuthRetryStrategy

builder.with_token_auth(
    token_manager=token_manager,
    auth_retry_strategy=SimpleAuthRetryStrategy(max_retries=1),
    excluded_paths={'/health', '/public'},
    excluded_path_patterns=['/docs/*']
)
with_api_key_auth(api_key, header_name='X-API-Key', excluded_paths=None)

Configure API key authentication.

Parameters:
  • api_key (str) – API key value

  • header_name (str) – Header name

  • excluded_paths (set) – Paths to exclude from auth

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_api_key_auth(
    api_key='your-key',
    header_name='X-API-Key',
    excluded_paths={'/public'}
)
with_basic_auth(username, password, excluded_paths=None)

Configure HTTP Basic authentication.

Parameters:
  • username (str) – Username

  • password (str) – Password

  • excluded_paths (set) – Paths to exclude from auth

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_basic_auth(
    username='user',
    password='pass',
    excluded_paths={'/login'}
)

Hooks Configuration

with_request_hook(hook)

Add request hook.

Parameters:

hook (RequestHookInterface) – Request hook

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

from requestforge import CorrelationIdHook

builder.with_request_hook(CorrelationIdHook())
with_response_hook(hook)

Add response hook.

Parameters:

hook (ResponseHookInterface) – Response hook

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

from requestforge import LoggingResponseHook

builder.with_response_hook(LoggingResponseHook())
with_error_hook(hook)

Add error hook.

Parameters:

hook (ErrorHookInterface) – Error hook

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

from requestforge import LoggingErrorHook

builder.with_error_hook(LoggingErrorHook())
with_logging(log_headers=False, log_body=False, sensitive_keys=None)

Enable logging hooks.

Parameters:
  • log_headers (bool) – Log request/response headers

  • log_body (bool) – Log request/response bodies

  • sensitive_keys (set) – Header keys to mask in logs

Returns:

Self for chaining

Return type:

HttpClientConfigBuilder

Example:

builder.with_logging(
    log_headers=True,
    log_body=False,
    sensitive_keys={'authorization', 'x-api-key'}
)

Building Configuration

build()

Build the configuration.

Returns:

Immutable configuration instance

Return type:

HttpClientConfig

Raises:

ValueError – If configuration is invalid

Example:

config = builder.build()

Complete Examples

Basic Configuration

from requestforge import HttpClientConfigBuilder

config = (
    HttpClientConfigBuilder()
    .with_base_url('https://api.example.com')
    .with_timeout(30.0)
    .with_header('User-Agent', 'MyApp/1.0')
    .build()
)

Production Configuration

from requestforge import (
    HttpClientConfigBuilder,
    ExponentialBackoffRetryStrategy
)

config = (
    HttpClientConfigBuilder()
    # Base settings
    .with_base_url('https://api.example.com')
    .with_timeout(30.0)
    .with_verify_ssl(True)

    # Headers
    .with_header('User-Agent', 'MyApp/1.0')
    .with_header('Accept', 'application/json')

    # Retry with exponential backoff
    .with_retry(
        max_retries=5,
        base_delay=1.0,
        max_delay=60.0
    )

    # Connection pooling
    .with_pool_connection(20)
    .with_pool_maxsize(50)

    # Logging
    .with_logging(
        log_headers=True,
        log_body=False,
        sensitive_keys={'authorization'}
    )

    .build()
)

With Authentication

from requestforge import (
    HttpClientConfigBuilder,
    TokenManager,
    ClientCredentialsTokenProvider,
    InMemoryTokenStorage,
    SimpleAuthRetryStrategy
)

# Setup token provider
provider = ClientCredentialsTokenProvider(
    token_url='https://auth.example.com/oauth/token',
    client_id='your-client-id',
    client_secret='your-client-secret',
    service_name='example-api'
)

# Create token manager
token_manager = TokenManager(
    provider=provider,
    storage=InMemoryTokenStorage()
)

# Build config
config = (
    HttpClientConfigBuilder()
    .with_base_url('https://api.example.com')
    .with_token_auth(
        token_manager=token_manager,
        auth_retry_strategy=SimpleAuthRetryStrategy(max_retries=1),
        excluded_paths={'/health', '/public'}
    )
    .with_retry(max_retries=3)
    .with_logging()
    .build()
)

Custom Hooks

from requestforge import (
    HttpClientConfigBuilder,
    LoggingRequestHook,
    LoggingResponseHook,
    CorrelationIdHook
)

config = (
    HttpClientConfigBuilder()
    .with_base_url('https://api.example.com')

    # Request hooks
    .with_request_hook(CorrelationIdHook('X-Request-ID'))
    .with_request_hook(LoggingRequestHook(log_headers=True))

    # Response hooks
    .with_response_hook(LoggingResponseHook(log_body=False))

    .build()
)

Environment-Specific Configuration

import os
from requestforge import HttpClientConfigBuilder

def create_config():
    env = os.getenv('ENVIRONMENT', 'development')

    builder = HttpClientConfigBuilder()

    if env == 'production':
        return (
            builder
            .with_base_url('https://api.production.com')
            .with_timeout(30.0)
            .with_retry(max_retries=5)
            .with_pool_connection(50)
            .with_verify_ssl(True)
            .build()
        )
    elif env == 'staging':
        return (
            builder
            .with_base_url('https://api.staging.com')
            .with_timeout(30.0)
            .with_retry(max_retries=3)
            .with_logging(log_headers=True)
            .build()
        )
    else:  # development
        return (
            builder
            .with_base_url('http://localhost:8000')
            .with_timeout(60.0)
            .with_retry(max_retries=1)
            .with_logging(log_headers=True, log_body=True)
            .with_verify_ssl(False)
            .build()
        )

config = create_config()

See Also