How to Use HTTPX with Proxies: 2026 Complete Guide
TL;DR
HTTPX 0.28.1 uses proxy=, not the removed proxies= argument. Use mounts= when HTTP and HTTPS destinations need different transports.
A persistent Client or AsyncClient is usually better than repeated top-level calls. Clients reuse connections, centralize timeouts, and have an explicit cleanup boundary.
Authenticated proxy URLs must encode the username and password. Reserved characters such as spaces, @, and : otherwise change URL parsing.
HTTPX reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY by default. Set trust_env=False when application configuration must ignore machine-level proxy settings.
Proxy rotation needs a bounded client pool and acceptance checks. Random selection alone does not detect a dead route, an error page with status 200, or unexpected data.
What Is an HTTPX Proxy?
An HTTPX proxy is an intermediary configured in the HTTPX Python client so requests reach a destination through another network endpoint. The official HTTPX proxy documentation supports a single proxy through proxy= and advanced routing through a dictionary of mounted transports.
HTTPX is a general-purpose Python HTTP client with synchronous and asynchronous APIs. Proxy configuration changes the network path; HTTPX still owns connection pooling, timeouts, redirects, TLS validation, response streaming, and status handling. A managed route such as Nstproxy Residential Prime Proxies can therefore attach through standard HTTPX settings without changing the parsing or business logic that consumes the response.
Use an HTTPX proxy for authorized price monitoring, localization checks, public-page testing, controlled corporate egress, or isolating independent jobs. A proxy does not authorize access to a destination, correct an invalid selector, or prove the response contains the intended content.
HTTPX Proxy API Changes You Need to Know
HTTPX 0.28 removed the deprecated proxies= argument, so current code must use proxy= or mounts=. The official HTTPX release history identifies 0.28.1 as the latest release at the time of testing and records the removal in the 0.28 line.
Use these mappings when updating older examples:
Older pattern
HTTPX 0.28.1 pattern
Use case
httpx.Client(proxies=proxy_url)
httpx.Client(proxy=proxy_url)
One endpoint for all requests
httpx.get(url, proxies=...)
httpx.get(url, proxy=...)
One isolated request
Proxy dictionary passed as proxies=
mounts={"http://": HTTPTransport(...), ...}
Different routing by destination scheme
The scheme on a mount key describes the destination URL. The scheme inside the proxy URL describes the connection to the proxy. For many HTTP gateways, both the http:// and https:// destination mounts correctly use an http://proxy-host:port endpoint because HTTPS targets are tunneled with CONNECT.
Prerequisites
The examples were executed with Python 3.12.13 and HTTPX 0.28.1. Install the pinned version in a virtual environment:
python -m pip installhttpx==0.28.1
Prepare an authorized target and keep proxy secrets in a protected runtime configuration. The examples use PROXY_URL, TARGET_URL, PROXY_USERNAME, PROXY_PASSWORD, and PROXY_URLS. Do not commit a complete credential-bearing URL or include it in application logs.
Each example sets an explicit timeout. HTTPX distinguishes connect, read, write, and pool timeouts; tune them from observed latency rather than removing the limit. Keep TLS verification enabled and install an approved CA certificate when a legitimate inspection proxy requires one.
Route HTTPX Requests Through Nstproxy
Create an authenticated endpoint, attach it to an HTTPX client, and verify the returned route.
You can use HTTPX with proxies through five current patterns: one client-level endpoint, encoded authentication, an asynchronous client pool, environment variables, or mounted transports. All Python blocks below ran against purpose-built local endpoints. The responses returned non-secret route markers, which verified that traffic crossed the intended proxy instead of merely confirming that HTTPX returned a response.
Method 1: Use One Proxy with a Synchronous Client
Use a synchronous Client when sequential requests share one endpoint. trust_env=False makes the explicit route authoritative, while the context manager closes pooled connections after the job.
The test printed route: basic-18480 and preserved the absolute target URL received by the proxy. Replace the fixed route value with a marker your diagnostic endpoint or provider session can verify.
Top-level httpx.get(..., proxy=...) is valid for a one-off call, but repeated top-level calls cannot reuse one client pool. Prefer a client for multi-page jobs. Nstproxy's Python web scraping project guide explains where response validation fits in a larger extraction pipeline.
Method 2: Configure an Authenticated HTTPX Proxy
Use an authenticated proxy by percent-encoding each credential component before building the URL. Encoding prevents reserved characters from being interpreted as delimiters.
The live check used a username containing a space and a password containing @ and :. The proxy rejected missing credentials with 407, then returned authenticated: True and route auth-18481 after HTTPX supplied the encoded values.
Do not print proxy_url: it contains recoverable credentials. Log a route ID, status, latency, and failure class instead. A repeated 407 is a configuration failure, not a reason for an unlimited retry loop.
Method 3: Rotate Reusable AsyncClient Instances
Use a bounded AsyncClient pool when independent requests can run through multiple endpoints. One client per endpoint preserves connection reuse and makes the route-to-client relationship explicit.
import asyncio
import itertools
import os
import httpx
asyncdeffetch(client: httpx.AsyncClient, target_url:str)->dict: response =await client.get(target_url) response.raise_for_status() data = response.json()if"route"notin data:raise ValueError("Response did not contain a route marker")return data
asyncdefmain()->None: proxy_urls =[value.strip()for value in os.environ["PROXY_URLS"].split(",")if value.strip()]iflen(proxy_urls)<2:raise ValueError("PROXY_URLS must contain at least two endpoints") clients =[ httpx.AsyncClient(proxy=proxy_url, timeout=10.0, trust_env=False)for proxy_url in proxy_urls
]try: client_cycle = itertools.cycle(clients) tasks =[fetch(next(client_cycle), os.environ["TARGET_URL"])for _ inrange(4)] results =await asyncio.gather(*tasks)print([result["route"]for result in results])finally:await asyncio.gather(*(client.aclose()for client in clients))asyncio.run(main())
The output alternated basic-18480, rotate-18482, basic-18480, and rotate-18482. Round-robin selection is observable and avoids accidental repeat choices, but it is not a health policy. Add a concurrency limit, failure counter, cooldown, and maximum retry budget before using a larger pool. The Python proxy rotation guide covers endpoint selection at a broader application level.
Do not automatically replay a state-changing request through another route unless the operation is idempotent or carries an application idempotency key. For stateful browsing, keep the same client, cookies, and sticky route together.
Method 4: Use Proxy Environment Variables
HTTPX reads proxy environment variables by default, which is useful for platform-managed routing. The official HTTPX environment-variable documentation defines HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY.
The executed program returned basic-18480 without a proxy argument in Python. Check NO_PROXY when a destination unexpectedly goes direct. If the program must ignore host settings, construct a client with trust_env=False; that choice also ignores other environment-derived configuration such as certificate paths.
Method 5: Route with HTTPTransport Mounts
Use mounts= when routing depends on the destination scheme or a subset of URLs. This is the current replacement for old proxy dictionaries.
The HTTP mount produced basic-18480 in the local run. Keep mount keys specific and test every scheme the application uses. HTTPX also offers optional SOCKS support through the httpx[socks] extra; install that extra and use the documented SOCKS URL only when the endpoint actually speaks SOCKS.
How to Verify an HTTPX Proxy
Verify an HTTPX proxy in three layers: network route, response semantics, and extracted output. Begin with an authorized IP-reflection or diagnostic endpoint and confirm the observed exit or session marker. Then require an acceptable status, content type, and recognizable page field. Finally validate the records your application intends to keep.
raise_for_status() rejects 4xx and 5xx responses, but HTTP 200 can still contain a proxy error page, consent screen, login page, or alternate locale. Test stable semantic fields and reject an empty or implausible result. The official HTTPX exception hierarchy helps separate timeouts, transport failures, proxy errors, and status failures for bounded retry rules.
Retries should target transient connect, timeout, and gateway failures. Do not retry 401, 403, 407, or invalid content indefinitely. Nstproxy's proxy server error guide provides a practical taxonomy for route-level troubleshooting.
Choosing an Nstproxy Route for HTTPX
Nstproxy Residential Prime Proxies provide standard authenticated endpoints for HTTPX workloads that need residential routing, selectable locations, and rotating or sticky sessions on the current product surface. The fit is strongest when your Python code already handles HTTP requests and validation while the network route must remain configurable outside application logic. Package and pay-per-use billing models let teams choose an operating model after measuring accepted traffic rather than rewriting the HTTPX integration. Use the product for authorized localization checks, price monitoring, ad verification, and public-data workflows; test the exact target and session behavior before increasing volume.
Standard client integration: Attach the generated endpoint through proxy= or a mounted HTTPTransport; no provider-specific Python SDK is required for basic routing.
Session-aware routing: Choose rotating behavior for independent requests or a sticky session for cookie-dependent flows.
Proxy routing does not perform parsing, deduplication, or schema validation. Keep those acceptance rules in the application, and monitor cost per accepted record rather than request count alone.
Common HTTPX Proxy Errors and Fixes
Symptom
Likely cause
Practical fix
TypeError mentions proxies
Code targets an older HTTPX API
Replace one endpoint with proxy=; use mounts= for advanced routing.
407 Proxy Authentication Required
Missing or malformed credentials
Encode username/password separately and verify the host and port without logging the URL.
ProxyError or ConnectTimeout
Endpoint is unreachable or uses the wrong protocol
Confirm scheme, DNS, port, and network reachability; retry only transient failures.
Direct IP appears
NO_PROXY matched or the explicit client was not used
Inspect environment variables and set trust_env=False when explicit configuration must win.
HTTPS fails through an HTTP proxy
CONNECT or CA trust is misconfigured
Confirm the gateway supports tunneling and install the approved CA; do not disable TLS checks.
Async sockets accumulate
Clients are created without cleanup
Reuse bounded clients and always call aclose() or use async with.
Status 200 but wrong data
The response is an alternate or soft-error page
Validate content type, a stable marker, and the final extracted schema.
Conclusion
A production HTTPX proxy setup uses the modern proxy= or mounts= API, protected credentials, explicit timeouts, reusable clients, and response acceptance tests. Use one synchronous client for a stable route, encode authenticated endpoints carefully, and rotate a bounded pool of AsyncClient instances only when independent work requires multiple routes.
Start with one authorized target and verify its route and semantic response. Add rotation after failures are classified and cleanup is proven; consider Nstproxy Proxy Manager later if endpoint health, pools, and routing rules outgrow application-level selection.
Experience Nstproxy β Start Your Free Trial Today
Q: Does HTTPX still support the proxies= argument?
No. HTTPX 0.28 removed proxies=; use proxy= for one endpoint and mounts= with proxy transports for more complex routing.
Q: Can HTTPX use a proxy with AsyncClient?
Yes. Pass proxy= to httpx.AsyncClient, reuse the client for its assigned endpoint, and close it with async with or aclose().
Q: Why does an HTTP proxy URL still start with http:// for an HTTPS target?
The proxy URL scheme describes the connection to the proxy, while the destination uses HTTPS through a CONNECT tunnel. An HTTP gateway can therefore serve HTTPS destinations without an https:// proxy URL.
Q: How do I disable environment proxy settings in HTTPX?
Create a Client or AsyncClient with trust_env=False. HTTPX will then ignore proxy and related configuration inherited from the process environment.
Q: Should I create a new AsyncClient for every request?
No. Reuse a bounded set of clients so HTTPX can pool connections, and associate each client with one endpoint or session policy.
Q: Can HTTPX use SOCKS5 proxies?
Yes. Install the official optional dependency with httpx[socks] and configure a socks5:// or supported SOCKS URL for an endpoint that actually implements that protocol.
Marcus Chen
Aug. 20th 2026
110M+ real IPs with 99.9% access success
Blazing-fast average response ~0.5s for high-concurrency tasks
From only $0.1/GB
Get immediate access to premium residential, datacenter, IPv6 and ISP proxy pools.