HTTPX Proxy Guide: HTTP, SOCKS5 and Async Python Examples
Set an HTTPX proxy with httpx.Client(proxy=...) or httpx.AsyncClient(proxy=...) in Python. Test one request against a destination you control before sending a batch. The examples show proxy authentication, HTTPS through CONNECT and SOCKS5. Upgrading to HTTPX 0.28? Replace the old proxies= argument and check which route HTTPX will use if the process also sets proxy variables.
If you are choosing a Python client, the Python proxies overview explains the broader options. For the synchronous Requests library, use the separate Python Requests proxy tutorial.
Install HTTPX and keep configuration outside code
python -m pip install "httpx>=0.28,<0.29"
python -c "import httpx; print(httpx.__version__)"
Read BP_PROXY_HOST, BP_PROXY_PORT, BP_PROXY_USER, BP_PROXY_PASSWORD, and BP_TARGET_URL from your process environment. These are application-specific variable names: HTTPX does not automatically interpret them. Set the target to a diagnostic endpoint you control before using your normal workload. Supply credentials through your deployment’s secret mechanism, and avoid putting a password in command history.
Copy the host and port from your BuyProxies connection details. A copied host:port pair still needs a URL scheme; the proxy formatter helps identify format differences. Keep a stable label such as proxy-a for diagnostics rather than displaying the complete authenticated URL.
Configure proxy authentication in httpx.Client
Build the URL from separate components. Encoding the username and password with quote(..., safe="") prevents characters such as @, /, and # from changing URL structure. Encode each credential once, before joining it into the URL. Proxy authentication is different from destination authentication: auth= on a request is not the place for your proxy password. See the HTTPX sync and async test results to compare the proxy modes used with each client.
import os
from urllib.parse import quote
import httpx
user = quote(os.environ["BP_PROXY_USER"], safe="")
password = quote(os.environ["BP_PROXY_PASSWORD"], safe="")
host = os.environ["BP_PROXY_HOST"]
port = int(os.environ["BP_PROXY_PORT"])
proxy = f"http://{user}:{password}@{host}:{port}"
timeout = httpx.Timeout(20.0, connect=5.0, pool=5.0)
with httpx.Client(proxy=proxy, timeout=timeout,
trust_env=False, follow_redirects=False) as client:
response = client.get(os.environ["BP_TARGET_URL"])
response.raise_for_status()
print("status", response.status_code)
The context manager closes the client and its connections. Reuse it for several requests when possible. This example disables automatic redirects so the first response is visible during diagnosis; a redirect requires your own decision about the next destination. See the proxy authentication guide for username/password versus IP authorization.
Fix the removed proxies= argument in HTTPX 0.28
If upgrading to HTTPX 0.28 gives you TypeError: Client.__init__() got an unexpected keyword argument 'proxies', check the argument in your client constructor. The HTTPX 0.28 release notes document the removal. If you passed a single proxy URL, change httpx.Client(proxies=proxy) to httpx.Client(proxy=proxy). The same change applies to httpx.AsyncClient.
import os
import httpx
with httpx.Client(proxy=os.environ["BP_PROXY_URL"], timeout=10.0) as client:
response = client.get(os.environ["BP_TARGET_URL"])
response.raise_for_status()
print(response.status_code)
If the old value was a dictionary with separate routes for HTTP and HTTPS destinations, build one transport per destination scheme. Set BP_HTTP_PROXY_URL and BP_HTTPS_PROXY_URL to your full proxy URLs, then set BP_TARGET_URL to the destination you want to test.
import os
import httpx
routes = {
"http://": httpx.HTTPTransport(proxy=os.environ["BP_HTTP_PROXY_URL"]),
"https://": httpx.HTTPTransport(proxy=os.environ["BP_HTTPS_PROXY_URL"]),
}
with httpx.Client(mounts=routes, trust_env=False, timeout=10.0) as client:
response = client.get(os.environ["BP_TARGET_URL"])
response.raise_for_status()
print(response.status_code)
Those keys match the destination scheme. An https:// destination can still use a proxy whose URL starts with http://. For an async client, use httpx.AsyncHTTPTransport in the mapping and async with httpx.AsyncClient(mounts=routes, trust_env=False).
Why an HTTPS destination often uses an HTTP proxy URL
In https://your-target.example/, the scheme describes the destination. In http://proxy.example:8080, it describes the connection to the proxy. For an HTTPS destination, an HTTP proxy can create a tunnel with CONNECT; HTTPX then negotiates TLS with the destination through that tunnel. Changing the proxy URL to https:// means requesting TLS to the proxy itself and requires a compatible endpoint. It is not required merely because your target uses HTTPS. HTTPX’s proxy documentation explains both forwarding and tunnelling.
Leave certificate verification enabled. A certificate error deserves a check of the trust chain, target hostname, and runtime certificates. Treat changing the scheme as a protocol choice, not a certificate workaround.
Use SOCKS5 when the endpoint supports it
python -m pip install "httpx[socks]>=0.28,<0.29"
For a SOCKS5 endpoint, construct the same credential-safe URL with socks5:// instead of http://, then pass it to Client(proxy=...) or AsyncClient(proxy=...). The extra installs HTTPX’s optional SOCKS dependency. Installing it does not convert an HTTP-only endpoint into a SOCKS service; confirm the protocol and port supplied for your proxy.
Keep protocol tests separate. A working HTTP connection to one port does not establish that SOCKS5 works on another. Verify a single request before adding scheduling, rotation, or retries.
Limit concurrent proxy requests with httpx.AsyncClient
The following block reuses the already constructed proxy and timeout. Each task waits for a semaphore slot, while the connection limit places a second bound on the client. Four is an example starting value, not a measured optimum. Increase it only after observing your endpoint’s capacity and the destination’s rate limits.
import asyncio
async def fetch_many(urls):
gate = asyncio.Semaphore(4)
limits = httpx.Limits(max_connections=4, max_keepalive_connections=4)
async with httpx.AsyncClient(proxy=proxy, timeout=timeout,
limits=limits, trust_env=False) as client:
async def fetch(url):
async with gate:
response = await client.get(url)
response.raise_for_status()
return response.status_code
return await asyncio.gather(*(fetch(url) for url in urls))
Creating a fresh client inside every task loses connection reuse. For a large input, feed a bounded worker queue instead of creating one task per URL. The downloadable example handles errors inside each task; the compact block above lets an error propagate to its caller. HTTPX’s async guide describes client lifetime and cleanup.
Set timeouts and identify the failing stage
The example gives connect and pool acquisition five seconds, with twenty seconds for read and write operations. HTTPX timeouts cover individual stages; they are not a single total deadline for an entire multi-request batch. A PoolTimeout can indicate local contention rather than an unreachable proxy. The timeout reference and connection limits explain those controls.
| Signal | First check |
|---|---|
ProxyError or CONNECT rejection |
Endpoint scheme, credentials, and permitted destination port. |
| HTTP 407 | Proxy authentication; for HTTPS, rejection may surface as a proxy exception. |
ConnectTimeout or ConnectError |
Proxy reachability, address, port, DNS, and firewall. |
PoolTimeout |
Concurrent work and whether responses/connections are being released. |
| HTTP 403 or 429 | Response source, destination policy, and request rate before deciding to retry. |
Catch HTTPStatusError for unsuccessful HTTP responses and RequestError for request failures. Log the exception class, status, attempt count, and a proxy label. Avoid logging str(exc), request headers, complete URLs, or response bodies by default. The exception hierarchy helps keep these cases distinct; our proxy error reference provides a broader diagnosis sequence.
HTTP_PROXY, NO_PROXY and trust_env in HTTPX
Decide whether the process or your client configuration should select the proxy. Both Client and AsyncClient use these rules.
- Proxy set in the process environment. With the default
trust_env=Trueand no explicit proxy, setHTTP_PROXYfor HTTP,HTTPS_PROXYfor HTTPS orALL_PROXYas a fallback. SetNO_PROXYto a comma-separated list of destinations that should use a direct connection, such aslocalhost,127.0.0.1. - Proxy configured on the client.
Client(proxy=proxy_url, trust_env=False)uses the supplied proxy. In HTTPX 0.28.1 an explicitproxy=takes precedence overNO_PROXYeven whentrust_env=True. - Direct comparison. Where a direct connection is allowed, make one request to the same diagnostic URL with
Client(trust_env=False), withoutproxy=. Compare the public IP reported by the endpoint. An HTTP 200 alone cannot show which route was used.
trust_env=False also disables SSL_CERT_FILE and SSL_CERT_DIR from the environment. If your deployment needs a custom CA, pass the intended SSL context via verify= and keep certificate verification enabled. HTTPX environment variables.
We checked these routes with local HTTP and CONNECT endpoints using HTTPX 0.28.1, with both the sync and async clients.
What HTTPX PoolTimeout looks like
The client used max_connections=1 and pool=0.20. The local HTTP proxy held the first response open. The second request waited for that connection slot and raised PoolTimeout before reaching the proxy. Once the first response closed, the same second request returned HTTP 200.

Check how many requests enter the client together and whether each streamed response leaves its context or calls aclose(). Compare the application queue with the HTTPX pool timeout before tuning the proxy connection timeout. If you use aiohttp, see how to confirm that its connection timeout occurred in the queue.
Download and verify the example
Download the HTTPX sync/async example. Its --check mode validates configuration without opening a connection. Run python -B httpx-proxy-examples.py --check, then remove --check for one real request. Add --async for a four-request batch or --scheme socks5 for a verified SOCKS endpoint. A successful status alone does not prove routing: compare the egress reported by your controlled endpoint, and use the proxy tester as a separate endpoint check.
Frequently asked questions
Can I pass the proxy argument to client.get()?
Configure the proxy when creating a Client or AsyncClient. Top-level httpx.get() accepts it, but a client’s request method does not use the same configuration signature.
Does HTTPX rotate proxies automatically?
No. Assign work to clients configured for your chosen endpoints. Track failures per endpoint and preserve one endpoint for a session that needs a stable egress address.
Does async make a blocked request succeed?
Concurrency changes scheduling. It does not change credentials, destination permissions, or a server’s response policy.
Which guide should I use for another async library?
The aiohttp guide covers sessions and proxy headers; the Scrapy guide covers crawler middleware. Browse the developer proxy examples for other clients.
For a stable endpoint to configure in your application, review the BuyProxies dedicated proxy plans and match the supplied protocol and authentication method to your workload.
Official sources
- HTTPX proxy configuration
- HTTPX async support
- HTTPX timeouts
- HTTPX resource limits
- HTTPX environment variables
- HTTPX exceptions
- HTTPX 0.28 release notes
- Python URL quoting
Technical references reviewed October 2, 2026. See our editorial policy and testing methodology.
