← all guides

Httpx and requests proxy mounts in Python

Two clients, two different ideas of where a proxy lives

Most Python scrapers that talk to a proxy do it through one of two libraries. The older one is requests, which almost everyone learned first. The newer one is httpx, which looks like requests on the surface and then quietly disagrees with it about where proxy settings belong.

That disagreement is the whole reason this piece exists. In requests, a proxy is something you can hand to each individual call. In httpx, a proxy belongs to the client and its transports, and a single request can’t pick its own. If you port a scraper from one to the other by swapping the import and fixing the obvious errors, the code usually runs. Whether it still sends traffic where you think it does is a separate question, and the library won’t tell you.

We run proxy infrastructure and production scrapers, and the support conversations that start with “the proxy isn’t working” very often end with “the proxy was never in the path.” The provider sees nothing, because nothing arrived. The scraper sees success, because the target answered. The only thing that changed is which address the target saw, and that’s the one thing nobody printed.

So this is a practical tour. Per-session and per-request settings in requests, the mounts system in httpx and how it routes by scheme and host, where credentials go and how they break, and the short list of gotchas that send a request out of your own network card instead of through the exit you paid for. It sits next to our pieces on Scrapy behind a rotating pool and on proxy environment variables, and it tries not to repeat them. Scrapy wraps its own downloader. This is about the two clients people reach for when they write the loop themselves.

One note on versions before anything else. Httpx changed its proxy arguments during the 0.2x releases, and some of what you’ll find in older answers online no longer runs. Where it matters below, the current shape is described, with a pointer to what it replaced.

What a proxy dictionary in requests actually means

In requests, the proxy setting is a plain dictionary, and the keys confuse people more than anything else about it.

proxies = {
    "http": "http://user:[email protected]:8000",
    "https": "http://user:[email protected]:8000",
}
r = requests.get("https://example.com/", proxies=proxies, timeout=30)

The keys describe the target. The values describe the proxy. So "https" on the left means “use this for requests whose URL starts with https”, and http:// on the right means “talk to the proxy itself in plain HTTP.” Those are two different facts about two different connections, and mixing them up produces the most common mistake in the whole topic.

For an https target through an ordinary HTTP proxy, requests opens a plain connection to the proxy, sends a CONNECT for the target host and port, and then runs TLS end to end inside that tunnel. The proxy never sees the page. It sees a hostname and a byte count. That’s why the right-hand value is http:// for most providers even when every target you scrape is https.

If you write https:// on the right, you’re asking for TLS to the proxy itself, before the CONNECT. Modern urllib3 (the layer underneath requests) supports that, and a few providers offer it. Most gateways don’t expect it, so the handshake fails and the error message mentions SSL, which sends people off debugging certificates on the target when the problem is one letter in the proxy URL.

The other half of the trap is leaving a key out. If the dictionary has "http" and no "https", then every https request finds no matching entry and goes direct. There’s no warning. Most of the web is https now, so a dictionary with only an http key is a dictionary that proxies almost nothing.

Keys that match a host as well as a scheme

The dictionary can be more specific than a scheme. Requests looks up the proxy for a URL in a fixed order and takes the first hit: the scheme plus the exact host, then the bare scheme, then all plus the host, then plain all.

proxies = {
    "https://api.example-target.com": "http://user:[email protected]:8000",
    "https": "http://user:[email protected]:8000",
    "all": "http://user:[email protected]:8000",
}

With that dictionary, calls to one API host use one gateway and everything else uses another. It’s a small routing table, and for a job that touches two or three domains it’s often all the routing you need.

The lookup is by exact hostname. https://example-target.com doesn’t match www.example-target.com, and it doesn’t match a subdomain the site’s pages redirect you to. Wildcards aren’t part of this scheme. If you need to catch a family of hosts, requests leaves you to do the matching yourself before the call, or to move the logic into a transport adapter. That’s where httpx mounts start to look attractive, and we’ll get there.

There’s also no key that means “send this host direct.” To exclude a host, you either don’t pass proxies for that call, or you rely on the NO_PROXY environment variable, which has its own behaviour covered below. People sometimes set a value to None and expect it to disable proxying for that key. Treat that as unreliable across versions and test it before you depend on it, because the merge with environment settings can put a proxy straight back.

Per request versus per session in requests

Requests lets you set proxies in two places. You can pass proxies= on each call, or you can set session.proxies once and let every call on that session inherit it. The second looks tidier, and it has a documented catch that bites people every week.

The requests documentation says it plainly: values set on session.proxies may be overwritten by environmental proxies, the ones urllib picks up from variables like HTTPS_PROXY. When a request is sent, the session merges environment settings in, and depending on the version and the exact combination, the environment can win. The advice in the docs is to pass proxies= explicitly on each request if you need to be sure.

In practice that means a scraper that behaves on your laptop, where no proxy variables are set, can start using a different proxy entirely on a server or CI runner where someone exported HTTPS_PROXY for package installs. The session code didn’t change. The environment did.

There are two clean ways out. One is to pass proxies= on every call, usually through a thin wrapper function so it can’t be forgotten:

def fetch(session, url, proxy_url):
    p = {"http": proxy_url, "https": proxy_url}
    return session.get(url, proxies=p, timeout=30)

The other is to turn the environment off for that session with session.trust_env = False. That stops requests reading proxy variables, and it also stops it reading .netrc credentials and a couple of other environment-sourced defaults, so check nothing else depended on them.

Per-request proxies are also how rotation works in plain requests. Each call can carry a different proxy URL, which is fine for stateless fetches. But the session still pools connections by proxy and host, so switching proxies every call means new TCP and TLS handshakes every call. Rotation has a cost in latency and in bandwidth you pay for, and our piece on rotating without losing your session covers when that cost is worth it.

Httpx starts from the client, not the call

Httpx took a different path. There’s no per-request proxy argument on a client’s get or post. The proxy is decided when the client is built, and every request through that client follows the client’s routing.

The simplest form looks like this in current versions:

client = httpx.Client(proxy="http://user:[email protected]:8000", timeout=30)
r = client.get("https://example.com/")

That single proxy= argument covers both http and https targets. Older code you’ll find online uses proxies=, either as a single string or as a dictionary keyed by URL patterns. That argument was deprecated when proxy= and mounts= arrived, and it was later removed, so copying an older snippet into a fresh environment raises a TypeError. That’s the good outcome. The bad one is a pinned old version in one environment and a new one in another, where the same code behaves differently.

The top-level helpers, httpx.get() and friends, do accept a proxy= argument, because each of those calls builds and throws away a client. That’s handy in a quick script and wasteful in a scraper, since you lose connection reuse and pay for a fresh handshake on every call.

Because the proxy lives on the client, per-request rotation in httpx means one of three designs: a small pool of clients, one per exit, that you pick from for each request; a rotating gateway from the provider, where one proxy URL hands out different exits on its side; or a custom transport that makes the choice itself. The first is the most common and the easiest to reason about. A client per exit also keeps cookies and connection pools separated per exit, which is usually what you want anyway.

What a mount is and how httpx picks one

Under the hood, an httpx client sends every request through a transport. A mount is a rule that says “requests whose URL matches this pattern use that transport.” The proxy= argument is just a shortcut for mounting one proxied transport on everything.

Written out by hand, the same routing looks like this:

proxied = httpx.HTTPTransport(proxy="http://user:[email protected]:8000")
client = httpx.Client(mounts={
    "http://": proxied,
    "https://": proxied,
})

The pattern keys have a small grammar. "all://" matches every scheme. "https://" matches one scheme. "https://example.com" matches one host on one scheme. "all://example.com" matches one host on any scheme. "all://*example.com" matches the domain and anything ending in it, and "all://*.example.com" matches subdomains only. You can add a port to be stricter still.

When more than one pattern matches, httpx picks the most specific. A host pattern beats a scheme pattern, and a pattern with a port beats one without. So you can write a broad rule and then carve exceptions out of it, which is the part requests never quite gave you.

If no pattern matches a URL, the request goes through the client’s default transport. And the default transport has no proxy unless you gave the client one. Hold on to that sentence, because it’s the root of half the direct-traffic surprises in httpx.

Routing by scheme and by host in one client

Mounts earn their keep on jobs that touch more than one kind of destination. A common shape in scraping is this: public pages go through a rotating residential gateway, one partner API goes through a static datacenter exit because the partner allowlisted that address, and an internal metrics endpoint shouldn’t go through any proxy at all.

resi = httpx.HTTPTransport(proxy="http://user:[email protected]:8000")
static = httpx.HTTPTransport(proxy="http://user:[email protected]:9000")
direct = httpx.HTTPTransport()

client = httpx.Client(mounts={
    "all://": resi,
    "https://api.partner-example.com": static,
    "all://*.internal.example": direct,
})

Reading it top to bottom: everything defaults to the residential gateway, the partner API host is pinned to the static exit, and anything under the internal domain goes out through a plain transport with no proxy. The explicit "all://" catch-all is what stops unmatched URLs from falling through to an unproxied default.

That last point deserves repeating. If you write only host-specific mounts and leave out a catch-all, every URL you didn’t think of goes direct. A redirect from www.example-target.com to m.example-target.com, an asset on a CDN hostname, a login step on an identity subdomain: none of those match a mount for the main host, so they leave from your own address.

Mounted transports also carry their own connection pools, and they take their own settings for things like retries on connection failure and local address binding. That’s useful. It also means a setting you put on the client may not be the setting a mounted transport uses, so if you customise transports, put the options on the transports.

The async side mirrors all of this with httpx.AsyncClient and httpx.AsyncHTTPTransport. Don’t mount a sync transport on an async client. Httpx will complain, which is kinder than most failures in this area.

Credentials in the URL and what breaks them

Both libraries accept proxy credentials in the userinfo part of the URL: http://user:pass@host:port. That’s the convention almost every provider documents, and it works until the username or password contains a character that has a meaning in URLs.

Provider usernames are often long and structured. Many providers encode session and targeting options into the username with separators, something like a customer id, then a country code, then a session token. Passwords generated by a dashboard often contain @, :, /, # or %. Any of those in the raw URL changes how it’s parsed. An @ in the password makes the parser think the host starts early. A # turns the rest into a fragment. A / ends the authority section.

The symptom is rarely a clean parse error. More often the library connects to the wrong host, or to the right host with the wrong credentials, and you get a 407 from the proxy or a DNS failure for a hostname that’s half of your password.

The fix is to percent-encode each part before assembling the URL:

from urllib.parse import quote
proxy_url = f"http://{quote(user, safe='')}:{quote(password, safe='')}@{host}:{port}"

Httpx also accepts credentials through its URL handling, and requests has an HTTPProxyAuth helper, but encoding the pieces yourself is the approach that behaves the same in both libraries and in every tool the URL gets passed to later.

The other thing a URL with credentials does is travel. It lands in exception messages, debug logs, and tracebacks that get pasted into chat. Keeping those credentials out of logs is a topic of its own, so here it’s enough to say that the URL form is convenient and leaky, and any logging you add around a request should strip the userinfo before it prints anything.

Telling a proxy failure from a target failure

When a proxied request fails, the first job is working out which hop failed. The two libraries give you different exception types for this, and a scraper that catches everything under one broad except clause throws that information away.

In requests, a failure to reach or negotiate with the proxy surfaces as requests.exceptions.ProxyError, which is a subclass of ConnectionError. A proxy that answers but refuses your credentials usually shows up as a 407 status wrapped in that same error during the CONNECT step. Timeouts are split into connect and read timeouts, and a connect timeout on a proxied call usually means the gateway itself didn’t answer.

In httpx, the equivalent is httpx.ProxyError, alongside httpx.ConnectError and the timeout family. A 407 from the proxy on an https target arrives during the tunnel setup, before any response from the target exists.

Everything after the tunnel is up belongs to the target. A 403, a 429, or a challenge page are the site’s answer, delivered through the exit. Retrying those on a new exit straight away is usually the wrong move, because the target is telling you about pace or permission, and a fresh address doesn’t change either.

So split the handling. Proxy-side errors are an infrastructure problem: count them per exit, back off, and alert when one exit keeps failing. Target-side responses are a behaviour signal: slow down for that host and look at what the site is saying. Logging the two separately also makes support conversations with a provider far shorter, because you can show them connect failures by gateway rather than a pile of mixed errors.

SOCKS and where the DNS lookup happens

Both libraries speak SOCKS5 through an optional extra. For requests it’s pip install "requests[socks]", which pulls in PySocks. For httpx it’s pip install "httpx[socks]", which pulls in a different SOCKS implementation. Without the extra installed, a socks5:// URL fails with an error about missing dependencies, which at least is loud.

The part that isn’t loud is DNS. In requests, socks5:// means your machine resolves the target hostname locally and sends the proxy an IP address. socks5h:// means the hostname goes to the proxy and the proxy resolves it. The traffic goes through the proxy either way. The lookup doesn’t.

That matters for two reasons. The first is geography: a local resolver near your server may hand back a CDN edge address that’s close to you, while the exit is on another continent. The target then serves a page from an edge that doesn’t match the exit’s country, and localised content comes back wrong for reasons that look like a proxy problem. The second is that your resolver, or your cloud provider’s, sees a record of every hostname the job touches, which you may or may not care about.

For httpx, check the documentation for the version you’ve installed before assuming socks5h:// behaves the same way, because SOCKS support in httpx has changed across releases. The safe habit with either library is to decide deliberately where resolution should happen and then confirm it, rather than relying on a letter in the scheme you copied from a forum.

Our piece on DNS inside a SOCKS tunnel goes deeper into the resolver side. For the purposes of client config, the rule is short: pick the scheme that puts the lookup where you want it, and don’t assume the two libraries spell it the same way.

The environment variables both libraries read

Both clients read proxy settings from the environment by default. Requests does it through urllib’s getproxies() when trust_env is on, which it is unless you turn it off. Httpx does it when the client is created with trust_env=True, which is also the default.

The variables are the usual set: HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY, in upper or lower case. Our piece on proxy environment variables covers how they leak across processes. The client-level detail worth knowing is how each library combines them with what you passed in code.

In httpx, environment-derived routes are built as mounts and then your own mounts= are layered on top. Where your pattern and the environment’s pattern are the same key, yours wins. Where they differ, both can survive. So a client where you mounted only "https://" can still send plain http requests through whatever HTTP_PROXY happened to say. If you want a client whose routing is exactly what’s written in the code, build it with trust_env=False.

In requests, the merge happens per request, and as covered above, the environment can override what’s on the session. Passing proxies= per call, or setting trust_env = False, puts the code back in charge.

NO_PROXY is the one that sends traffic direct on purpose. It’s a list of hosts or domains that should skip the proxy. Somebody sets it to cover localhost and an internal domain, then adds a broad entry like a whole top-level domain to fix a package mirror, and now a target on that domain is being fetched from the server’s own address. Both libraries honour NO_PROXY when they trust the environment. Neither tells you it did.

The quiet ways traffic ends up going direct

Pulling the threads together, here are the ways a Python scraper ends up sending requests from its own address while the code looks proxied. None of them raise an error.

  • A requests dictionary with an "http" key and no "https" key.
  • A NO_PROXY entry, set for some other reason, that happens to cover the target’s domain.
  • An httpx client built only with host-specific mounts and no "all://" catch-all, so redirects, CDN assets and subdomains fall through to the default transport.
  • A second client or session created somewhere else in the code, often by a helper or a vendor SDK, that never received your proxy settings at all.
  • A retry path or a fallback that catches a proxy error and tries again “without the proxy to see if that helps”, which somebody added during debugging and never removed.
  • Headless browser steps or file downloads that run through a different library, since the proxy you gave requests means nothing to them.

The SDK case is worth a word. Many API client libraries build their own requests session or httpx client internally. Some expose a way to pass one in, or accept a proxy argument, and some just read the environment. If a job mixes your own fetches with an SDK’s calls, check how the SDK builds its client, because the answer decides where half your traffic goes.

The retry case is worse than it sounds. A job that falls back to direct on proxy errors will look healthy in every dashboard, with a success rate that never drops, right up until someone asks why the target has your server’s address in its logs.

Proving the route before the job runs

Every one of those failure modes is invisible from inside the response. A 200 from the target looks the same whether it came through the exit or not. So the only reliable check is to ask something outside what address it saw, using the exact same client object the job will use.

The pattern is simple: point the same session or client at an IP echo endpoint, one you run yourself or a public one you trust, and compare the answer with your server’s own public address.

def assert_proxied(client, own_ip, echo_url):
    seen = client.get(echo_url, timeout=20).text.strip()
    if seen == own_ip:
        raise RuntimeError("request left from our own address")
    return seen

Run that once per client at startup, and once per mounted transport if you route by host, by aiming it at an echo endpoint whose URL matches that mount’s pattern. A check against an http URL tells you nothing about the https route, and a check against one host tells you nothing about a mount for another.

It’s also worth logging the exit address, without credentials, alongside the first few results of each run. When something looks wrong later, being able to see which exit served a batch saves a lot of guessing. Our curl versus browser automation piece shows the same idea from the command line, where a working curl test and a failing script usually mean the script isn’t using the settings the curl test used.

What this check can’t tell you is whether the target treats that exit well. It confirms the route, which is all it’s meant to do. How a given site responds to a given address is a separate question, and no client setting answers it.

Choosing between them for a scraping job

For a small, synchronous job with a single gateway, requests is fine. It’s everywhere, its behaviour is well understood, and per-call proxies make simple rotation easy. The price is remembering the environment-override caveat and passing proxies explicitly.

Httpx is the better fit when the job needs async concurrency, HTTP/2 to targets that support it, or routing that differs by host. Mounts make the routing readable in one place, and the client-level model pushes you toward one client per exit, which keeps cookies and connection pools from mixing between exits. The price is that there’s no per-call proxy, and a missing catch-all mount fails silently.

We’d push back on one habit either way: treating the HTTP client as the place to solve blocking. Changing clients doesn’t change how a target judges your traffic in any way you can count on. A site that’s rate limiting a job is responding to volume and pacing, and the durable fix is to slow down, cache, and respect whatever the site publishes about automated access. The client’s job is to put requests on the route you chose and to fail loudly when it can’t.

If you’re choosing now, it’s worth writing the choice down in the repo, with the version pinned. A lot of the confusing proxy behaviour in Python comes from two environments running the same code on different library versions.

What to do before your next run

If you have a Python scraper running against a proxy right now, a short audit covers most of what’s above.

Open the code and find every place a session or client gets created, including inside helpers and SDKs. For each one, write down where its proxy comes from: an explicit argument, the environment, or nowhere.

For requests, check that every proxies dictionary has both an http and an https key, and that the right-hand values use the scheme your provider actually expects. If you rely on session.proxies, either switch to per-call proxies= or set trust_env = False.

For httpx, check that any client with host-specific mounts also has an "all://" catch-all, and decide whether it should trust the environment at all. Search for any remaining proxies= argument, which will break on current versions.

Percent-encode every credential you put in a URL, and strip userinfo from anything you log.

Then run the echo check through each client and each mount, compare against your server’s own address, and keep that check in the startup path so it runs every time rather than once.

None of that makes a scraper harder to block or easier to hide. It makes it do what you configured, which is the thing you can actually control.

If you want the rest of our proxy setup guides, from rotation to provider testing, they’re all on Proxy Scraping.

Get new guides and videos first — join the Telegram channel.

proxies
Need proxies that survive the block wall?

Singapore Mobile Proxy runs real 4G/5G mobile IPs on rotating SIMs — the carrier-grade addresses most of these targets still trust.

see plans →
read on
More scraping guides

The rest of the field manual: target-site playbooks, library walkthroughs, provider reviews, and anti-bot troubleshooting.

browse all guides →