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:
Attributes
Properties
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:
- Returns:
TokenData instance
- Return type:
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
HttpClientConfigBuilderto 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.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.
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:
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:
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:
Example:
builder.with_verify_ssl(True)
- with_redirects(allow=True, max_redirects=10)
Configure redirect behavior.
- Parameters:
- Returns:
Self for chaining
- Return type:
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:
Example:
builder.with_headers({ 'User-Agent': 'MyApp/1.0', 'Accept': 'application/json' })
- with_header(name, value)
Add a single default header.
- Parameters:
- Returns:
Self for chaining
- Return type:
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:
Example:
builder.with_bearer_token('your-api-token')
- with_api_key(api_key, header_name='X-API-Key')
Add API key header.
- Parameters:
- Returns:
Self for chaining
- Return type:
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:
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:
- Returns:
Self for chaining
- Return type:
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:
Example:
builder.with_pool_connection(20)
Authentication Configuration
- with_auth_hook(auth_hook)
Set authentication hook.
- Parameters:
auth_hook (AuthHookInterface) – Authentication hook
- Returns:
Self for chaining
- Return type:
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:
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:
- Returns:
Self for chaining
- Return type:
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:
- Returns:
Self for chaining
- Return type:
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:
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:
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:
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:
- Returns:
Self for chaining
- Return type:
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:
- 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
Client API Reference - HTTP client API
Retry Strategies API Reference - Retry strategies
Hooks API Reference - Lifecycle hooks
Token Manager API Reference - Token management