Skip to content

How to use a proxy with Python httpx

httpx is a modern Python HTTP client with the same API for sync and async code. It takes a single proxy= argument. This guide shows how to use it with an authenticated residential proxy: rotating and sticky IPs, country targeting, SOCKS5, concurrency with AsyncClient, and retries mapped to proxy errors.

Updated 9 November 2026

Prerequisites

  • Python 3.9+ and pip install httpx (0.28 or newer); add httpx[socks] for SOCKS5.
  • Version note: httpx 0.26 added proxy= and deprecated proxies=; 0.28 removed proxies=. Older tutorials using proxies={...} fail with a TypeError on current versions.
  • A proxy login from the dashboard under Logins, shown as USER and PASS.

Good fits: API and price monitoring, localized QA, and collecting public data at higher concurrency than requests allows.

Basic HTTP proxy

Pass the proxy URL as proxy= on Client, AsyncClient or a top-level function. It applies to both HTTP and HTTPS targets; HTTPS is tunneled with CONNECT, so TLS stays end to end. Keep the proxy URL's scheme as http://.

import httpx

proxy = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

with httpx.Client(proxy=proxy, timeout=30) as client:
    print(client.get("https://api.ipify.org").text)

Authentication

Credentials go in the proxy URL's userinfo, USER:PASS@host:port, and httpx sends them as Proxy-Authorization. URL-encode a password that contains reserved characters with urllib.parse.quote(pw, safe="").

httpx also reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY when trust_env=True (the default) and no proxy= is given. To route different targets differently, use mounts= with one httpx.HTTPTransport(proxy=...) per URL pattern.

Rotating vs sticky IPs

The gateway gives each new connection a new exit. An httpx client pools connections, so requests to the same host through one client usually share an exit. For a fresh IP per request, use a new client (or a new session id) each time. To keep an IP on purpose, add a session id: same id, same exit, for 5 minutes by default or up to 120 with ttl.

import httpx

proxy = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

# a Client keeps connections alive, so open a new one when you want a new exit
for _ in range(3):
    with httpx.Client(proxy=proxy, timeout=30) as client:
        print(client.get("https://api.ipify.org").text)

Country and city targeting

UsernameExit
USER-cc-usUnited States
USER-cc-us-city-new_yorkNew York
USER-cc-us-region-californiaCalifornia
USER-cc-de-asn-3320A specific German network
USER-cont-euAnywhere in Europe
USER-cc-us-city-houston-strict-falseHouston, or elsewhere in the US

See Targeting for every option and the naming rules (lowercase, _ for spaces).

SOCKS5

Install the socks extra and use a socks5h:// (or socks5://) URL. httpx accepts socks5h as a scheme since 0.28, and it sends the hostname to the proxy for resolution.

python
# pip install "httpx[socks]"
import httpx

with httpx.Client(proxy="socks5h://USER-cc-de:PASS@gw.hyperproxy.io:8888", timeout=30) as client:
    print(client.get("https://api.ipify.org").text)

Concurrency with AsyncClient

httpx shines with asyncio. Cap the number of requests in flight with a semaphore and give each task its own session if it needs a stable IP. If tasks don't need their own IP, share one AsyncClient and tune httpx.Limits(max_connections=...) instead.

python
import asyncio
import uuid
import httpx

ENDPOINT = "gw.hyperproxy.io:8888"
limit = asyncio.Semaphore(10)  # at most 10 requests in flight

async def fetch(url: str) -> int:
    proxy = f"http://USER-cc-us-session-{uuid.uuid4().hex[:12]}:PASS@{ENDPOINT}"
    async with limit, httpx.AsyncClient(proxy=proxy, timeout=30) as client:
        r = await client.get(url)
        return r.status_code

async def main():
    urls = [f"https://example.com/page/{i}" for i in range(100)]
    for status in await asyncio.gather(*(fetch(u) for u in urls)):
        print(status)

asyncio.run(main())

Error handling and retries

When the gateway refuses a CONNECT (HTTPS targets), httpx raises httpx.ProxyError with the status and reason in the message. For plain HTTP targets you get a normal response with that status. Codes, from Errors:

  • 407: wrong login, an invalid or repeated option, or no balance. Don't retry.
  • 404: no exit matches; widen the targeting or add strict-false.
  • 403: the target is not allowed. 400: a malformed request.
  • 429: back off. 502 / 504: retry; without a session each retry gets a new exit.
python
import asyncio
import httpx

RETRYABLE = {429, 502, 504}

async def get(client: httpx.AsyncClient, url: str, attempts: int = 4) -> httpx.Response:
    for attempt in range(attempts):
        try:
            r = await client.get(url)
            if r.status_code not in RETRYABLE:
                return r
        except httpx.ProxyError as e:
            # CONNECT refused by the gateway; the message starts with the status, e.g. "407 ..."
            status = str(e)[:3]
            if status in {"407", "404", "403", "400"}:
                raise  # credentials, targeting or target: fix, don't retry
        except (httpx.ConnectError, httpx.ReadError, httpx.TimeoutException):
            pass
        await asyncio.sleep(2 ** attempt)
    raise RuntimeError(f"gave up on {url}")

# transport-level retries for connection failures only
transport = httpx.AsyncHTTPTransport(proxy="http://USER-cc-us:PASS@gw.hyperproxy.io:8888", retries=2)
client = httpx.AsyncClient(transport=transport, timeout=30)

The transport's retries= only retries failed connection attempts, not error responses, so keep your own loop for status codes.

Verify the exit IP

Request https://api.ipify.org through the client. Run the rotating example to see three IPs and the sticky one to see the same IP three times.

Troubleshooting

  • TypeError: unexpected keyword argument 'proxies': use proxy= (httpx 0.28+).
  • "Using SOCKS proxy, but the 'socksio' package is not installed": pip install "httpx[socks]".
  • Same IP on every request: connection pooling; open a new client or use per-request session ids.
  • ProxyError: 407: check credentials and options in the username.

FAQ

Does httpx support HTTP/2 through a proxy?

Yes. Install httpx[http2] and pass http2=True. HTTP/2 runs inside the CONNECT tunnel.

httpx or aiohttp?

Both work well. httpx has one API for sync and async code; aiohttp is async-only and very fast. See the aiohttp guide.

Can I set the proxy per request?

Not on a client; the proxy is fixed when the client is created. Create one client per username, or use the top-level httpx.get(..., proxy=...) for one-off calls.

Where are more examples?

See Examples and the Scrapy guide.

Try it on your own workload

Sign up with GitHub or Google, create a proxy login and send your first request in a minute.

More proxy integration guides

  • Python requests — Rotating and sticky residential proxies with Python requests, including SOCKS5 and retries.
  • Python aiohttp — High-concurrency aiohttp requests through rotating or sticky residential IPs.
  • Scrapy — Route Scrapy spiders through residential proxies with request.meta and a middleware.
  • Playwright — Run Playwright through residential proxies, per browser or per context, with sticky sessions.
  • Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
  • Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
  • Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
  • Node.js fetch & undici — Use Node's built-in fetch with undici ProxyAgent or NODE_USE_ENV_PROXY.
  • Go net/http — Configure Go's http.Transport for HTTP and SOCKS5 residential proxies.
  • curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.