HTTPX Proxy Setup: AsyncClient, Authentication and TLS
Configure HTTPX, see which IP your request uses, and diagnose proxy failures before adding concurrency.

The practical answer
- For one gateway, give AsyncClient a proxy object with separate credentials. Keep the gateway scheme supplied by the provider, even for an HTTPS target.
- Start with the downloadable IP check. Then compare the result from the same worker, not a different browser or laptop.
- Reuse one client per account or session. Limit pending tasks as well as connections, and handle rotation between sessions.
Start with the gateway and the runtime
HTTPX accepts a proxy on the client. For an async worker, that means httpx.AsyncClient(proxy=...). The gateway receives the proxy credentials; the destination receives its own request. A destination API key and a proxy password serve different purposes.
For an HTTPS URL through an HTTP gateway, HTTPX opens a CONNECT tunnel, then negotiates TLS with the destination through that tunnel. Therefore http://gateway:port can be correct when the target begins with https://. Changing the gateway scheme to HTTPS only works if that listener itself supports TLS. See HTTPX proxy configuration.
Use an isolated environment so the installed version is unambiguous:
python3.12 -m venv .venv
. .venv/bin/activate
python -m pip install 'httpx==0.28.1'
python -c 'import httpx; print(httpx.__version__)'
This pins the version exercised below. It is a reproducibility choice, not a claim that future versions should be avoided. If an older tutorial passes proxies= and your installed release rejects it, use the documented proxy= interface; for separate routes, configure transports and mounts deliberately.
An existing synchronous application may be simpler with Requests. Choose aiohttp when the surrounding worker already uses its session model.
Run the complete example and read its output
Replace the three placeholders below with the scheme, host, port and credentials shown for your connection. The gateway URL contains no username or password. These are POSIX-shell commands; use your deployment secret store for a hosted worker.
export PROXY_URL='http://proxy.example:8080'
export PROXY_USER='YOUR_PROXY_USERNAME'
export PROXY_PASSWORD='YOUR_PROXY_PASSWORD'
export TARGET_URL='https://api.ipify.org?format=json'
The default diagnostic destination is ipify, which returns the public address it sees. You can set TARGET_URL to a small endpoint you control instead. A successful transport response alone does not establish a country: use the returned IP in the location checks.
"""One diagnostic GET; set PROXY_URL, PROXY_USER and PROXY_PASSWORD privately."""
import asyncio
import os
import ipaddress
import json
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://api.ipify.org?format=json"))
print(f"HTTP {response.status_code}")
response.raise_for_status()
print(f"Received {len(response.content)} bytes")
try:
address = ipaddress.ip_address(response.json()["ip"])
except (ValueError, KeyError, TypeError):
return # A non-IP test endpoint can still verify HTTP transport.
print(f"Observed exit IP: {address}")
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)
Save the complete script as httpx-proxy.py, then run python httpx-proxy.py. Success reports HTTP 200, a byte count and Observed exit IP: followed by the address returned by the endpoint. If the response is HTML instead of JSON, you get the transport status and byte count but no IP line. That distinction catches captive portals and unexpected diagnostic pages.
Keep the printed IP private when it identifies a customer session. To compare a direct request, run a separate client with no proxy and trust_env=False from the same worker. Compare the direct and proxied IPs from that worker. If they match, inspect the client settings and gateway logs before changing the connection.
The sample uses a verified TLS context and reads only a small diagnostic response. For a private CA, set SSL_CERT_FILE to the trusted bundle; the script passes it into Python SSL explicitly. HTTPX documents custom SSL contexts. Do not turn verification off to hide a certificate failure.
Control environment proxies and SOCKS explicitly
A container image or shell can set proxy variables before your code runs. HTTPX reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY by default. The complete example sets trust_env=False so that its explicit gateway owns the route. It still reads our application-specific PROXY_URL, PROXY_USER and PROXY_PASSWORD fields.
If your organization manages routing through environment variables, use a separate configuration: omit the explicit proxy, allow environment trust, and test a proxied host and a NO_PROXY host. Print variable names or a boolean indicating presence when debugging; printing the full environment can disclose the password.
SOCKS is a different protocol. Install the optional extra and use the SOCKS endpoint provided for your connection:
python -m pip install 'httpx[socks]==0.28.1'
Then set PROXY_URL to its socks5:// address. This optional path is documented by HTTPX; the downloadable lab tests HTTP forwarding and CONNECT, not a SOCKS server. If your problem is specifically remote DNS resolution, confirm that behavior for the chosen transport instead of inferring it from the IP returned by an HTTP request.
Reuse the client without creating an unlimited task queue
Open the client at worker startup or at the start of an account session, reuse it, and close it when that scope ends. Creating one inside every request loop throws away the connection pool. The HTTPX async lifecycle guide explains why the client should outlive an individual request.
Two limits do different jobs. max_connections=2 caps open connections. It does not prevent a producer from creating thousands of tasks waiting for those connections. For a small job, process a finite list in batches; for a long-running collector, use a bounded queue and a fixed worker count. Start with the lowest concurrency that meets the job deadline and measure it against your own destination.
A small batch pattern inside the configured client's context is:
# urls is a finite list of authorized destinations.
for offset in range(0, len(urls), 2):
batch = urls[offset:offset + 2]
responses = await asyncio.gather(*(client.get(url) for url in batch))
for response in responses:
response.raise_for_status()
# Parse or store each small response here.
This pattern schedules at most two requests at a time. It is a source-reviewed integration sketch; the single-request download is the script exercised by the lab. For large bodies, stream to a bounded sink instead of retaining whole responses. See connection pool settings for the separate keep-alive and connection limits.
The example's timeout values are phase limits: 10 seconds to connect, 5 seconds waiting for a pool slot, and 20 seconds for other phases. A read timeout is not a total job deadline. Use the timeout definitions to decide which phase is actually failing before increasing a number.
Treat rotation as a session boundary
Suppose one account uses a sticky proxy credential and a cookie-bearing client. Rotating the exit while requests remain in flight can leave the job with requests on different connections and unclear results. Pause that session's producer, finish or cancel in-flight work, close its client, perform the provider-supported rotation, and verify the next exit before resuming.
A different proxy URL does not clear cookies, and a new client does not guarantee a different mobile IP. Treat account state, connection pooling and carrier allocation as separate controls. The mobile rotation guide explains the product side. For a stable destination allowlist, review which IP is authorized before choosing a rotating connection.
Diagnose the failure before retrying
Start with the exception class and whether any HTTP response arrived. The HTTPX exception hierarchy distinguishes a proxy error from pool, connection and read timeouts. Our sample prints the class while leaving credential-bearing exception details out of ordinary logs.
Use the table to choose one controlled next test. If the neutral IP endpoint works and only the intended site returns 403, changing the proxy password is unlikely to address the refusing layer. If a pool timeout begins only after concurrency rises, reduce the pending work and inspect response cleanup before buying another endpoint.
| Symptom | Likely boundary | Next test |
|---|---|---|
| ProxyError / 407 during CONNECT | Gateway authentication or CONNECT policy | Verify the purchased endpoint and credential; make one neutral HTTPS request. |
| ConnectTimeout or ConnectError | DNS, listener, firewall or TLS connection | Check the gateway host/port and scheme from the same worker. |
| PoolTimeout | Local connection pool | Reduce active work; ensure response bodies are consumed or closed. |
| ReadTimeout | Response stream | Compare a small diagnostic response with the destination; keep a job deadline. |
| HTTP 403 / 429 | Destination response | Inspect target permissions or rate limits; do not retry unchanged requests in a loop. |
Give the HTTP tool a configured client
A model does not choose the route by describing a proxy in a prompt. The Python function making the request needs the configured client. Create that client in the application's startup context and inject it into the tool handler; keep endpoint secrets outside model-visible tool arguments and traces.
For a retrieval worker, allow the required destinations and apply the same task, body-size and timeout limits as any other application. If the tool launches a browser, configure that browser independently with Playwright proxy settings. A successful HTTPX test does not configure a browser subprocess.
For mobile proxy scraping workflows, choose the country and session behavior required by the job before increasing concurrency. US carrier options and the mobile proxy overview explain the product choices; the observed exit check verifies the connection you actually received.
Reproduce the transport checks
The scripts were rerun on October 15, 2026 with Python 3.12.14, HTTPX 0.28.1, aiohttp 3.14.5, Node.js 22.23.1 and Undici 8.12.1. The lab runs an authenticated proxy and two origins on loopback. It checks the origin request count, missing proxy credentials at the origin, process exit status and reported output.
There are seven checks for each of the three clients, plus two checks for native Node environment routing. Download the lab ZIP, follow its README, and compare the recorded JSON results. The IP 203.0.113.42 is a documentation address returned by the fixture; it is not a Coronium exit or a measured location.
These are transport tests. They do not measure carrier speed, geographic coverage or success against a particular website. For a purchased port, repeat the single-request example from the machine running your job, then test the authorized destination and session lifetime you need.
| Check | Observed result | What it verifies |
|---|---|---|
| Authenticated HTTP and HTTPS CONNECT | Each reaches the local origin once | Proxy transport works with credentials containing reserved characters. |
| JSON IP response | The script prints 203.0.113.42 | The diagnostic reads the returned IP, rather than guessing from the gateway. |
| Wrong proxy password | Nonzero exit; origin never reached | Authentication failure cannot silently fall back to a direct request. |
| Untrusted TLS certificate | Nonzero exit; origin never reached | Certificate verification stays enabled. |
| HTTP 302 redirect | 302 reported; redirect not followed; nonzero exit | The first response remains visible for diagnosis. |
| HTTP 429 rate limit | One origin request; nonzero exit | The sample does not immediately retry or rotate. |
Sources and review scope
Sources reviewed October 15, 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.
Where to get a dedicated line
A Coronium mobile proxy is one physical device with its own SIM, rented to one customer. It connects over HTTP or SOCKS5, the IP changes by dashboard button, API link or timer, and data is not metered on dedicated lines. Brazil lines are the exception: 20 GB of data a month and a new IP on request only, with no timer. Stock and prices differ by country and carrier.