Outbound requests from async applications
An async web application needs to call external HTTP services without blocking its event loop.
HTTPX · Class
AsyncClient is HTTPX’s reusable asynchronous client for making HTTP requests. It provides connection pooling and related client features and can be shared between tasks.
AsyncClient provides asynchronous request methods together with connection pooling and reusable client configuration. Use it as an async context manager so its connections are closed automatically, or call aclose() explicitly when managing its lifetime yourself.
httpx.AsyncClient(*, auth=None, params=None, headers=None, cookies=None, verify=True, cert=None, http1=True, http2=False, proxy=None, mounts=None, timeout=Timeout(timeout=5.0), follow_redirects=False, limits=Limits(max_connections=100, max_keepalive_connections=20, keepalive_expiry=5.0), max_redirects=20, event_hooks=None, base_url='', transport=None, trust_env=True, default_encoding='utf-8')An asynchronous HTTP client instance; its request methods yield HTTPX Response objects when awaited.
import asyncio
import httpx
async def main():
async with httpx.AsyncClient() as client:
response = await client.get("https://example.org")
print(response.status_code)
asyncio.run(main())Creates an asynchronous client, sends a GET request, and closes the client automatically when the context ends.
An async web application needs to call external HTTP services without blocking its event loop.
Several requests target the same services during one operation or task group.
Tests need to send requests directly to an ASGI application.
The application needs shared defaults such as headers, cookies, a base URL, or transport behavior.
AsyncClient is HTTPX's asynchronous client for issuing requests with methods such as get(), post(), request(), and send(). Its methods return asynchronously, so callers must await them.
Follow-up: How should its lifetime be managed? Use async with httpx.AsyncClient() for automatic cleanup, or await aclose() when managing the instance manually.
The client supports connection pooling, redirects, cookie persistence, and HTTP/2, and it can be shared between tasks. Reusing one instance avoids recreating client state for each request.
Follow-up: How would you scope it safely? Create it around the group of operations that should share the client and let the async context manager close it afterward.
AsyncClient accepts client configuration such as a transport and an HTTP/2 setting. For direct transport construction in asynchronous code, use httpx.AsyncHTTPTransport.
Follow-up: What must custom asynchronous transports implement? They should implement the low-level transport API for sending one request and returning its response, commonly by subclassing AsyncBaseTransport.
AsyncHTTPTransportAsyncBaseTransportClientResponseRequest