Overview
HTTPX 0.22, released on January 27, 2022, introduces event hooks for request interception and improves the custom transport API.
Main Features
Event hooks
Event hooks allow intercepting requests and responses to add logging, authentication, or transformations without modifying client code.
python
import httpx
def log_request(request):
print(f'>> {request.method} {request.url}')
def log_response(response):
print(f'<< {response.status_code}')
client = httpx.Client(
event_hooks={
'request': [log_request],
'response': [log_response],
}
)
response = client.get('https://httpbin.org/get')
Transport API
The transport API allows creating custom backends for mocking requests or using alternative protocols.
python
import httpx
# Custom transport for testing
def mock_transport(request):
return httpx.Response(
200,
json={'status': 'ok'},
)
client = httpx.Client(
transport=httpx.MockTransport(mock_transport)
)
response = client.get('https://api.example.com/health')
print(response.json()) # {'status': 'ok'}
