HTTPX Proxy Setup: AsyncClient, Authentication and TLS
Configure an authenticated HTTPX client, verify its route, and keep async requests within the capacity of your proxy connection.
Before running the code
- Use proxy= for a single endpoint. Give each distinct proxy session its own client and reuse that client within the session.
- Set trust_env=False when explicit routing should ignore proxy environment variables. Configure certificate trust separately.
- A successful local CONNECT test proves client configuration. It does not prove a carrier location, clean reputation or access to every website.
Choose the proxy endpoint before the destination
An HTTPX proxy configuration has two addresses: the proxy gateway you connect to and the website the gateway contacts. For an HTTPS destination, an HTTP gateway normally uses CONNECT to carry the destination TLS connection. The gateway URL can therefore start with http:// while the destination starts with https://. Select the scheme supplied for the gateway itself. HTTPX documents these proxy modes.
Copy the host, port and credentials from the connection you purchased. Keep the proxy password separate from the destination's API key. A website login belongs to the origin request; proxy authentication belongs to the gateway. Never put a proxy password into the site's Authorization header.
If you are choosing between Python clients, compare the Requests configuration for synchronous applications and aiohttp setup for an existing aiohttp worker. Changing libraries does not change the mobile carrier or account allocation behind the endpoint.
Run one authenticated request
Install httpx in an isolated Python environment. Set PROXY_URL to the gateway scheme, host and port without credentials; set PROXY_USER and PROXY_PASSWORD through your secret manager or local environment. TARGET_URL defaults to a small public example page. Use a destination you control when checking sensitive integrations.
"""One diagnostic GET; set PROXY_URL, PROXY_USER and PROXY_PASSWORD privately."""
import asyncio
import os
import ssl
import sys
import httpx
async def main():
proxy = httpx.Proxy(
os.environ["PROXY_URL"],
auth=(os.environ["PROXY_USER"], os.environ["PROXY_PASSWORD"]),
)
tls = ssl.create_default_context(cafile=os.environ.get("SSL_CERT_FILE"))
async with httpx.AsyncClient(
proxy=proxy,
verify=tls,
trust_env=False,
follow_redirects=False,
timeout=httpx.Timeout(20.0, connect=10.0, pool=5.0),
limits=httpx.Limits(max_connections=2, max_keepalive_connections=2),
) as client:
response = await client.get(os.environ.get("TARGET_URL", "https://example.com/"))
print(f"HTTP {response.status_code}")
response.raise_for_status()
print(f"Received {len(response.content)} bytes")
if __name__ == "__main__":
try:
asyncio.run(main())
except Exception as error:
# Exception strings can contain request URLs or credentials.
print(f"Request failed: {type(error).__name__}", file=sys.stderr)
sys.exit(1)
Download this Python example. The example reports the HTTP status and byte count, not the response body or credential-bearing exception string. It reads the body into memory, so use it for small diagnostic responses. For large downloads, use streaming and an explicit maximum body size.
SSL_CERT_FILE is optional. The example passes it to Python's certificate context explicitly, rather than assuming HTTPX will read it with trust_env=False. Keep verification enabled and install only a CA you actually trust. HTTPX's SSL documentation explains custom contexts.
Make explicit and environment-based routing separate
HTTPX normally reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY. A container can inherit a value you never set in your application. trust_env=False disables that environment configuration for this client. See HTTPX environment variables.
Our example chooses explicit routing. If your deployment instead uses centrally managed environment proxies, remove the explicit proxy choice deliberately, enable environment trust and test both proxied and bypassed hosts. Do not assume that setting HTTPS_PROXY changes every process in the application.
When a development request works but a queue worker fails, compare the worker's runtime, destination hostname, proxy host and configuration mode. Record whether variables are present without printing their secret values. A successful request in your laptop's browser says nothing about the route used by a remote Python worker.
Bound concurrency and reuse the client
Create the AsyncClient outside the loop that schedules requests and close it when that worker or logical session ends. Recreating it for every URL discards the pool. HTTPX's async guide describes the client lifecycle.
The sample sets a pool of two connections. That is a conservative starting configuration for a test, not a Coronium port limit. A connection limit controls open connections; it does not prevent an application from creating a million pending tasks. Use a bounded work queue or small batches as well. Measure completed requests, errors and elapsed time before increasing concurrency. Resource limits are configured independently of application task limits.
The sample uses a 10-second connect timeout, a 5-second pool wait and 20 seconds for the other timeout phases. Those are phase limits, not a single end-to-end deadline. A slow stream can continue receiving chunks without reaching its read timeout. If the whole job has a deadline, enforce that at the job boundary. HTTPX distinguishes connect, read, write and pool timeouts.
Treat rotation as a session change
Changing a Python object does not instruct a mobile carrier to assign a new exit IP. If the provider exposes a rotation action, finish in-flight work before invoking it, then open a new connection and verify the result. Keep cookies and application state consistent with the session you intended to preserve.
For a list of distinct proxy endpoints, create a client per selected endpoint and limit the number of active clients. Do not rotate endpoints on every failed request automatically: a wrong password, rejected account or application error will remain wrong. Use the mobile IP rotation guide to separate connection lifetime from exit-IP changes.
HTTPX also offers optional SOCKS support through httpx[socks]. Use the documented SOCKS URL and check DNS behavior in the version you deploy. Our fixture below covers HTTP gateways and HTTPS CONNECT; it does not certify SOCKS or UDP support. See the SOCKS5 guide before changing protocols.
Read the failure at the right layer
| Observed failure | Likely layer | Next check |
|---|---|---|
| ProxyError or gateway 407 | Proxy connection or authentication | Confirm endpoint, credentials and permitted client source. |
| ConnectError with certificate failure | TLS trust | Check the certificate chain and hostname; keep verification on. |
| PoolTimeout | Local connection pool | Reduce pending work and check that responses are consumed. |
| HTTP 429 | Destination rate limit | Respect the server delay and reduce workload; do not rotate to evade it. |
First reproduce the problem with one small GET. Preserve the exception class, destination hostname, UTC time and HTTP status when available. Keep secrets out of tickets.
For a proxy or TLS failure, the destination may never receive a request. For a website 403 or 429, a working transport can still have reached an application that refuses the operation. Review its response and retry policy before buying another IP. The proxy error guide covers the broader diagnosis.
Keep AI tool requests on the configured route
An AI workflow can have separate model, retrieval and browser clients. Passing this client to a retrieval tool configures that tool's requests. It does not configure a browser that the same tool launches, nor a model SDK that constructs another client internally.
Create the client in the worker that executes the tool, inject it into the retrieval function, and verify the route from that function. For browser-based collection use the Playwright proxy guide. Keep passwords in the worker's secret store rather than prompts, tool arguments shown to users or model-visible logs. This also makes a deployment change easier to audit.
What we tested on October 14, 2026
The downloadable script was exercised with Python 3.12.14 and HTTPX 0.28.1 against a local authenticated proxy and local HTTP/HTTPS origins. Checks cover successful HTTP forwarding, HTTPS CONNECT, a rejected password, rejection of an untrusted certificate, no automatic redirect follow and no automatic retry of a 429. The origin was checked for leaked proxy credentials.
These are reproducible transport checks using synthetic credentials. They are not measurements of Coronium's network, a speed comparison, a test of third-party access controls or a promise of scraping success. Before production, repeat the route check with your purchased connection and a permitted destination.
Sources and review scope
Sources reviewed October 14, 2026. This guide reviews primary documentation. Code examples illustrate configuration and error handling. Any local fixture checks are described in the article; they are not live-provider performance benchmarks or guarantees of destination access.
Frequently asked questions
Configure another runtime
Use the settings supported by the process making the request, then verify routing and authentication.
Related workflows
Match an authorized collector to its network and session requirements.
Compare available carrier plans when your integration needs a US mobile exit.
Configure server-side JavaScript workers separately from Python tools.
Check which source address a gateway can authorize.