How to Use a Proxy with Python httpx (Sync, Async, Auth and Errors)

Short answer: create the client with httpx.Client(proxy="http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}", timeout=30). The same proxy= argument works for httpx.AsyncClient. Older tutorials use proxies=, which was deprecated and then removed, so if you get a TypeError, check your httpx version.

This guide covers sync and async clients, authentication, routing different hosts through different proxies, SOCKS, retries and common errors. It is part of our guide to proxies for web scraping. Other tools: Python requests proxy and Scrapy proxy setup.

Use proxies for public data and legitimate testing only: market research, price monitoring, ad verification, SEO checks and QA. Respect each site’s terms and robots.txt.

Prerequisites

  • Python 3.8 or newer and httpx: pip install httpx
  • Proxy credentials from your dashboard: username, password, host and port. New to these terms? Read what a proxy host and port are.

Basic proxy request

import httpx

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"

with httpx.Client(proxy=PROXY_URL, timeout=30) as client:
    r = client.get("https://httpbin.org/ip")
    print(r.status_code, r.json())

The returned origin should be the proxy’s IP, not yours. For other ways to check a proxy, see how to test proxies.

proxy= vs proxies=

Recent httpx versions take a single proxy= argument on Client and AsyncClient. The older proxies= argument (a dict) was deprecated in 0.26 and removed later. Check what you have installed:

pip show httpx

If you must support an old version, pin it in requirements.txt, or upgrade and switch to proxy=. For per-scheme or per-host routing on new versions, use mounts (below).

Async client

import asyncio
import httpx

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
URLS = [f"https://httpbin.org/anything?page={n}" for n in range(1, 6)]


async def main():
    limits = httpx.Limits(max_connections=5, max_keepalive_connections=5)
    async with httpx.AsyncClient(proxy=PROXY_URL, timeout=30, limits=limits) as client:
        sem = asyncio.Semaphore(5)  # keep concurrency low

        async def fetch(url):
            async with sem:
                r = await client.get(url)
                return url, r.status_code

        for url, status in await asyncio.gather(*(fetch(u) for u in URLS)):
            print(status, url)


asyncio.run(main())

Reuse one client for many requests instead of creating a client per request. It keeps connections open and is faster. A small semaphore is kinder to the target and cheaper on per-GB plans.

Special characters in the password

If the password contains characters such as @, : or /, URL-encode the credentials:

from urllib.parse import quote

user = quote("USERNAME", safe="")
password = quote("PASSWORD", safe="")
PROXY_URL = f"http://{user}:{password}@{{PROXY_HOST}}:{{PORT}}"

The doubled braces keep the {PROXY_HOST} and {PORT} placeholders literal. In real code, replace them with your values and use single braces for your own variables.

Environment variables

httpx reads HTTP_PROXY, HTTPS_PROXY and ALL_PROXY by default (trust_env=True):

export HTTPS_PROXY="http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
python scraper.py

An explicit proxy= argument takes priority. To ignore the environment completely, create the client with trust_env=False. Never commit real credentials to a repository. The same variables work with curl, see using curl with a proxy server.

Route different hosts through different proxies

With mounts, you can send some URLs through a proxy and others directly:

import httpx

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"

mounts = {
    "all://*.example.com": httpx.HTTPTransport(proxy=PROXY_URL),
    "all://": httpx.HTTPTransport(),  # everything else goes direct
}

with httpx.Client(mounts=mounts, timeout=30) as client:
    print(client.get("https://httpbin.org/ip").json())      # direct
    print(client.get("https://www.example.com/").status_code)  # via proxy

Use httpx.AsyncHTTPTransport with AsyncClient. The pattern keys follow httpx’s routing rules, so check the httpx documentation for the version you use. This is useful when internal APIs must not go through the proxy.

SOCKS proxies

pip install "httpx[socks]"
import httpx

PROXY_URL = "socks5://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"

with httpx.Client(proxy=PROXY_URL, timeout=30) as client:
    print(client.get("https://httpbin.org/ip").json())

Use the host and port that your dashboard lists for SOCKS. They can differ from the HTTP ones.

HTTP/2

httpx supports HTTP/2 when you install the extra and enable it on the client:

pip install "httpx[http2]"
with httpx.Client(proxy=PROXY_URL, http2=True, timeout=30) as client:
    r = client.get("https://httpbin.org/get")
    print(r.http_version)

HTTP/2 is negotiated with the target site, while the connection to an HTTP proxy is a tunnel. If you see unexpected errors, turn http2 off to isolate the problem.

Rotation

If your plan gives you a rotating gateway, one proxy URL is enough, and new IPs appear on the schedule or per connection that you set. USA 4G/5G proxies rotate every 5, 10 or 30 minutes depending on your setting. Check your dashboard for the exact options.

If you have a list of endpoints, keep one client per proxy and cycle through them:

import itertools
import httpx

PROXY_URLS = [
    "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}",
    "http://USERNAME:PASSWORD@{PROXY_HOST_2}:{PORT_2}",
]
clients = [httpx.Client(proxy=u, timeout=30) for u in PROXY_URLS]
pool = itertools.cycle(clients)

try:
    for page in range(1, 4):
        r = next(pool).get(f"https://httpbin.org/anything?page={page}")
        print(page, r.status_code)
finally:
    for c in clients:
        c.close()

Creating the clients once avoids reconnecting on every request. When several requests must share one IP, use one client for the whole flow, or a sticky session or static IP. For trade-offs, see rotating vs static residential proxies.

Retry with backoff

httpx’s transport retries option only retries failed connection attempts, not bad status codes. For 429 and 5xx, write the loop yourself:

import random
import time

import httpx

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"


def fetch(client, url, retries=4):
    for attempt in range(retries):
        try:
            r = client.get(url)
            if r.status_code == 407:
                raise RuntimeError("407: check USERNAME/PASSWORD")
            if r.status_code in (429, 502, 503, 504):
                time.sleep(2 ** attempt + random.random())
                continue
            r.raise_for_status()
            return r
        except (httpx.ConnectError, httpx.TimeoutException, httpx.ProxyError):
            time.sleep(2 ** attempt + random.random())
    raise RuntimeError(f"Failed after {retries} attempts: {url}")


transport = httpx.HTTPTransport(proxy=PROXY_URL, retries=2)  # connection retries only
with httpx.Client(transport=transport, timeout=30) as client:
    print(fetch(client, "https://httpbin.org/ip").json())

Do not retry a 407. It means the credentials are wrong, and retrying will not fix it. For HTTPS targets, a 407 during the tunnel may raise httpx.ProxyError instead of returning a response, so the loop above would retry it. If you want to fail fast, inspect the exception message and re-raise when it mentions 407.

Timeouts

httpx has a default timeout of 5 seconds, which is short for proxied requests. Set it explicitly, and use the detailed form when you need to:

timeout = httpx.Timeout(30.0, connect=10.0)
client = httpx.Client(proxy=PROXY_URL, timeout=timeout)

Common errors and fixes

SymptomLikely causeFix
TypeError: ... unexpected keyword argument 'proxies'Old tutorial code on a new httpx versionUse proxy=, or mounts for routing
httpx.ProxyError mentioning 407Wrong credentials, unencoded special characters, or IP not whitelistedCheck username and password, encode them, check the whitelist
httpx.ConnectErrorWrong host or port, or proxy unreachableVerify {PROXY_HOST} and {PORT}, test with curl
httpx.ConnectTimeout / ReadTimeoutSlow target, heavy page, or a firewallRaise the timeout, lower concurrency, retry with backoff
ImportError about socksio or h2Extra not installedpip install "httpx[socks]" or "httpx[http2]"
Your own IP is shownProxy not applied: wrong client, or mounts pattern did not matchCheck that requests go through the client you configured
HTTP 429Too many requests to the targetLower concurrency, add delays, honor Retry-After

Exact error names and messages vary between httpx versions, so log the full exception once to see what yours produces. A fuller breakdown is in proxy errors: what each one means and how to fix it.

Next steps

Load one page through the proxy, confirm the exit IP, then scale gradually and watch your error rate and bandwidth. For choosing between residential, mobile and ISP proxies and estimating cost, read proxies for web scraping.

Need proxies to test with? Compare residential proxies (per GB), USA 4G/5G mobile proxies (per day, unlimited bandwidth) and static ISP proxies (30-day plans), or see the pricing page. Every plan comes with a 24-hour money-back guarantee.

See residential plans

FAQ

How do I set a proxy in httpx?

Pass proxy="http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}" to httpx.Client or httpx.AsyncClient. The proxy applies to every request made with that client.

Why do I get a TypeError about “proxies” in httpx?

The proxies argument was deprecated and later removed. Use proxy= for a single proxy, or mounts with httpx.HTTPTransport(proxy=...) for routing rules.

How do I use a proxy with username and password in httpx?

Put the credentials in the proxy URL. If the password contains special characters, URL-encode it with urllib.parse.quote first.

How do I use different proxies for different hosts in httpx?

Use mounts, mapping URL patterns to transports. For example, route all://*.example.com through a proxy transport and everything else through a plain transport.

Does httpx support SOCKS proxies?

Yes. Install httpx[socks] and use a socks5:// proxy URL. Use the host and port that your dashboard lists for SOCKS.

Should I retry a 407 error in httpx?

No. A 407 means the proxy rejected your credentials or your IP. Fix the username, password or whitelist instead of retrying.

Copiat

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.