Aiohttp Transport for HTTPX
httpx-aiohttp provides an aiohttp-powered transport layer for HTTPX, allowing users to leverage aiohttp's robust asynchronous HTTP capabilities within the familiar HTTPX API. It is currently at version 0.1.12 and is actively maintained with frequent minor releases addressing compatibility and bug fixes.
Warnings
- deprecated When providing Basic Authentication credentials to `httpx.Client` or `httpx.AsyncClient`, passing a `(username, password)` tuple directly is deprecated in favor of using `httpx.BasicAuth`. This applies even when using `httpx-aiohttp` as the transport.
- gotcha Versions prior to 0.1.9 might not properly close the underlying `aiohttp` response after reading content, potentially leading to resource leaks or unreleased connections in long-running applications.
- gotcha Early versions (prior to 0.1.11/0.1.12) had compatibility issues with Python 3.8, specifically related to the usage of the `|` operator for type hinting. Users on Python 3.8 might encounter syntax errors or unexpected behavior.
- gotcha Versions prior to 0.1.8 might incorrectly include a `Content-Type` header in HTTP GET requests even when no request body is present. This could cause issues with servers that are strict about request header correctness.
- gotcha The `aiohttp` library, which this transport leverages, does not inherently support HTTP/2. Therefore, when using `httpx-aiohttp`, any HTTP/2 features expected from a standard `httpx` client will not be available. The transport will revert to HTTP/1.1 communication.
Install
-
pip install httpx-aiohttp
Imports
- HttpxAiohttpTransport
from httpx_aiohttp import HttpxAiohttpTransport
Quickstart
import asyncio
import httpx
from httpx_aiohttp import HttpxAiohttpTransport
async def main():
# Initialize the aiohttp-powered transport
transport = HttpxAiohttpTransport()
# Create an httpx AsyncClient using the custom transport
async with httpx.AsyncClient(transport=transport) as client:
try:
response = await client.get("https://httpbin.org/get")
response.raise_for_status() # Raise an exception for HTTP errors
print(f"Status Code: {response.status_code}")
print(f"Response JSON: {response.json()}")
except httpx.HTTPStatusError as e:
print(f"HTTP error occurred: {e}")
except httpx.RequestError as e:
print(f"An error occurred while requesting: {e}")
if __name__ == "__main__":
asyncio.run(main())