Python Requests Proxy Setup, with httpx and aiohttp
Set a proxy in Python requests, httpx and aiohttp, then fix what breaks: the http:// scheme, SOCKS5, sessions, trust_env, encoding, errors.
Every Python client takes the same proxy URL, http://USERNAME:PASSWORD@HOST:PORT, copied from the Connect card on the dashboard's Proxies page, and it starts with http:// even when the target is https://. Find your client below, then read the details that cause real failures: environment variables that outrank a session's proxy settings, credentials that break URL parsing, timeouts, retries, and the check that proves traffic is leaving through the proxy. If you whitelist your source IP instead of using credentials, drop USERNAME:PASSWORD@ and the rest holds. If your stack is Node rather than Python, see Node.js proxy setup.
requests
import requests
proxies = {
"http": "http://USERNAME:PASSWORD@HOST:PORT",
"https": "http://USERNAME:PASSWORD@HOST:PORT",
}
r = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30))
print(r.text)The keys name the scheme of the target URL; the values name the proxy. The value under "https" still begins with http://, because your client speaks plain HTTP to the Node4 endpoint: for an https:// destination the library asks the proxy for a CONNECT tunnel and performs the TLS handshake with the destination through it, so the destination's certificate is verified by your machine as usual and the proxy relays encrypted bytes it cannot read. Write https:// there and the library attempts a TLS handshake against a socket that answers in plaintext; requests raises a ProxyError whose message says "Your proxy appears to only use HTTP and not HTTPS", wrapping an SSLError with "wrong version number".
For anything longer than a one-off script, use a Session, which reuses connections. Behind a proxy that matters twice over: each new connection pays for the hop to the proxy, a CONNECT round trip and a TLS handshake before your request moves.
import requests
session = requests.Session()
session.proxies = {
"http": "http://USERNAME:PASSWORD@HOST:PORT",
"https": "http://USERNAME:PASSWORD@HOST:PORT",
}
r = session.get("https://api.ipify.org", timeout=(10, 30))
print(r.text)
session.close()requests chooses the proxy for each request when it sends it. Assigning session.proxies takes effect on the next call, including to a host the session already reached directly: the adapter keeps direct connections and proxied ones in separate pools, so an open direct socket is never reused for a request that names a proxy. Set the proxy when you create the session anyway, so the first request takes the same route as the rest. What does carry over is session state: cookies collected on direct calls are sent through the proxy afterwards. If proxied traffic should not share that state, use a new session rather than editing the old one. A per-request proxies= argument overrides both the session setting and the environment for one call, which is useful for an occasional exception and less useful as the primary mechanism.
The proxy environment variables HTTP_PROXY and HTTPS_PROXY outrank session.proxies: requests merges them into each call before it looks at the session, so a stray HTTPS_PROXY in a CI runner or container silently replaces the proxy you configured in code. Set session.trust_env = False right after creating the session if the code should be the only source of proxy settings. The environment variables section below covers the rest.
SOCKS5 with requests
requests has no SOCKS support of its own. Install the extra, which pulls in PySocks:
pip install "requests[socks]"Without it, a socks5:// or socks5h:// proxy URL raises InvalidSchema: Missing dependencies for SOCKS support. With it, the same proxies dictionary takes a SOCKS URL:
import requests
proxies = {
"http": "socks5h://USERNAME:PASSWORD@HOST:PORT",
"https": "socks5h://USERNAME:PASSWORD@HOST:PORT",
}
r = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30))
print(r.text)Write socks5h, not socks5, in both entries. With socks5h the hostname goes to the proxy and is resolved at the exit; with socks5 your machine resolves it locally first, so every hostname you visit is looked up by your own resolver, and DNS-based load balancing picks a server near you rather than near the exit. The port differs from the HTTP one; SOCKS5 proxy setup shows where to find it and which Node4 products offer SOCKS5 (every paid product does; the free tier is HTTP(S) only).
When a requests call fails
The exception type usually names the layer at fault:
ProxyErrorsaying "Your proxy appears to only use HTTP and not HTTPS", or anSSLErrorwith "wrong version number". Almost alwayshttps://at the start of the proxy URL; it must behttp://, as explained above. Node4 relays the TLS session through aCONNECTtunnel without opening it, so the destination's certificate is the only one your client checks. Do not "fix" this withverify=False: it hides the real cause and removes the check that protects the connection.ProxyErrorwith407 Proxy Authentication Required. The proxy rejected the credentials. For anhttps://target the 407 arrives while the tunnel is being opened, so requests raises it as an exception rather than returning a response. Work through the 407 guide.- A 401 response. The destination wants its own login. That is separate from the proxy layer, and changing proxy credentials will not fix it.
ProxyErrorwith "connection refused", orConnectTimeout. The client never reached the proxy: check the host and port against the Connect card.
When a script behaves differently on another machine or in CI, check what requests sees before reading the code: env | grep -i proxy on Linux or macOS lists every proxy variable in play.
httpx
The same request API in sync and async form, with the proxy fixed in the client constructor:
import httpx
proxy = "http://USERNAME:PASSWORD@HOST:PORT"
timeout = httpx.Timeout(30.0, connect=10.0)
with httpx.Client(proxy=proxy, timeout=timeout) as client:
print(client.get("https://api.ipify.org").text)import asyncio
import httpx
async def main() -> None:
async with httpx.AsyncClient(proxy="http://USERNAME:PASSWORD@HOST:PORT") as client:
r = await client.get("https://api.ipify.org")
print(r.text)
asyncio.run(main())Older examples pass a proxies= dictionary shaped like the requests one. httpx deprecated that argument in 0.26 in favor of the single proxy= URL and removed it in 0.28, where proxies= raises a TypeError. For different routing per destination (one internal origin direct, everything else proxied), mounts= maps URL patterns to transports:
client = httpx.Client(
mounts={
"all://": httpx.HTTPTransport(proxy="http://USERNAME:PASSWORD@HOST:PORT"),
"all://internal.example.com": httpx.HTTPTransport(),
}
)The proxy is fixed when the client is constructed, so changing route means building a new client.
aiohttp
The ClientSession owns the connection pool, but the proxy is an argument to each request. aiohttp has no SOCKS support of its own, and it does not reject a socks5:// URL up front: it speaks HTTP to the SOCKS port and fails with a confusing response or connection error. SOCKS5 needs a different connector, covered in SOCKS5 proxies with aiohttp.
import asyncio
from urllib.parse import quote
import aiohttp
PROXY = f"http://{quote('USERNAME', safe='')}:{quote('p@ss:w/rd', safe='')}@HOST:PORT"
async def main() -> None:
timeout = aiohttp.ClientTimeout(total=60, connect=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get("https://api.ipify.org", proxy=PROXY) as resp:
print(await resp.text())
asyncio.run(main())Put the credentials in the proxy URL, percent-encoded as the next section explains; aiohttp sends them on plain http:// requests and on HTTPS tunnels alike. The older proxy_auth=aiohttp.BasicAuth(...) argument still works, but aiohttp 3.14 marks it deprecated, and the replacement its warning suggests, a Proxy-Authorization entry in proxy_headers, is sent only when opening an HTTPS tunnel: a plain http:// request made that way reaches the proxy without credentials and gets a 407. Keep http:// as the proxy URL's scheme, because the Node4 endpoint speaks plain HTTP.
Create one ClientSession per application and reuse it; a session per request throws away the pool. Because the proxy is per request, a call that omits it goes direct silently; a small wrapper that always injects proxy is cheap insurance.
Credentials that survive URL parsing
Credentials inside the proxy URL are parsed as URL parts, so a reserved character in a password changes what the URL means: depending on the character, requests refuses the URL with InvalidURL, or a different password reaches the proxy and it answers 407. Fixing 407 errors covers that failure and the invisible whitespace a copy-paste drags in. Prevention is one function call:
from urllib.parse import quote
username = quote("USERNAME", safe="")
password = quote("p@ss:w/rd", safe="")
proxy = f"http://{username}:{password}@HOST:PORT"Pass safe="" explicitly; the default leaves / unescaped because quote usually encodes paths. Encode each half separately and then assemble the URL, so the separators stay separators.
Timeouts
A proxied request has more places to stall than a direct one: the connection to the proxy, the tunnel, the upstream connection and the target's response. requests has no default timeout, aiohttp allows five minutes per request by default, and httpx defaults to five seconds. Set both phases explicitly: in requests the timeout is a (connect, read) tuple, httpx has a structured httpx.Timeout, and aiohttp's ClientTimeout carries total and connect. Values depend on your targets; what matters is that a hung request becomes an exception after a bounded wait rather than a stalled worker.
Retries and backoff
Transient failures are part of using any proxy pool: an exit leaving rotation mid-request, a target throttling an address, an upstream timeout. requests inherits a retry engine from urllib3; mount it once per session:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
session.proxies = {
"http": "http://USERNAME:PASSWORD@HOST:PORT",
"https": "http://USERNAME:PASSWORD@HOST:PORT",
}
retry = Retry(
total=3,
backoff_factor=1.5,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "HEAD"],
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)allowed_methods restricts retries to idempotent verbs, so a POST is not replayed because a hop timed out. backoff_factor spaces the attempts, which matters because a 429 retried instantly from the same address rarely goes better.
On a rotating gateway the exit belongs to the connection. A plain-HTTP request gets its own pick from the pool (which can repeat an earlier address), but an HTTPS request travels inside a tunnel, and a Session keeps that tunnel open: a status-code retry goes out through the same tunnel and the same exit. If a retry should come from a different address, send it on a new connection, for example from a fresh Session, rather than relying on the retry adapter. When you want the opposite (one exit held across a sequence), that is a session question, covered in sticky vs rotating sessions; the products are on the rotating proxies page.
httpx retries connection failures if asked (httpx.HTTPTransport(retries=3)) but not on status codes; pair it with tenacity for that. aiohttp ships no retry mechanism; aiohttp-retry or a loop around asyncio.sleep both work.
HTTPAdapter also sizes the connection pool. Its defaults (pool_connections=10, pool_maxsize=10) are fine for a sequential script; if several threads share one session, pass pool_maxsize matching your concurrency, for example HTTPAdapter(max_retries=retry, pool_maxsize=20), or the surplus connections are opened and then discarded instead of reused.
Cycling a list of dedicated proxies in requests
A rotating gateway does the rotation for you behind one hostname. With a list of dedicated proxies, your code does it. The simplest form takes the next proxy for each request:
import itertools
import requests
proxy_pool = itertools.cycle([
"http://USERNAME:PASSWORD@HOST1:PORT",
"http://USERNAME:PASSWORD@HOST2:PORT",
"http://USERNAME:PASSWORD@HOST3:PORT",
])
for url in urls_to_fetch:
proxy = next(proxy_pool)
r = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=(10, 30))That loop has no idea whether a proxy is failing. Beyond a throwaway script, catch requests.exceptions.ProxyError, ConnectionError and Timeout per proxy, count consecutive failures, and set a proxy aside for a cooldown once it crosses a small threshold instead of retrying it immediately. Log which proxy handled each request, with its latency, so a slow one shows up before it fails outright.
When a task needs one address throughout (a login, a cart, an account), cycling breaks it. Give each proxy its own session instead and assign each task to one session, so cookies and exit stay together:
sessions = {}
for proxy in proxy_list:
s = requests.Session()
s.trust_env = False
s.proxies = {"http": proxy, "https": proxy}
sessions[proxy] = sEnvironment variables
All three libraries can read the standard proxy variables:
export HTTP_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export HTTPS_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export NO_PROXY="localhost,127.0.0.1,.internal"requests also reads ALL_PROXY (one proxy for every scheme), and accepts the lowercase spellings. requests and httpx read them by default: requests re-checks per request, and HTTP_PROXY and HTTPS_PROXY take precedence over the matching session.proxies entry (though not over a per-request proxies= argument), so disable them with session.trust_env = False when code should decide; httpx captures them when the client is constructed, and a proxy= argument replaces them. aiohttp ignores them unless you opt in with ClientSession(trust_env=True). NO_PROXY keeps listed destinations off the environment's proxy, which you want for localhost health checks and internal services; in requests it does not cancel a proxy set in code.
Environment configuration keeps credentials out of source control and lets the same code run proxied in production and direct in development. Its weakness is that a missing variable fails silently and traffic goes direct, which is why the final check matters.
Check the egress address
End every integration with the same egress check: ask an IP-echo service who you are, both ways. Accept only a 200 whose whole body is an IP address; an error page that merely differs from your own address is not a proxied exit. The check raises an explicit exception rather than using assert, which python -O strips out.
import ipaddress
import requests
PROXY = "http://USERNAME:PASSWORD@HOST:PORT"
def egress_ip(url, **kwargs):
r = requests.get(url, **kwargs)
body = r.text.strip()
if r.status_code != 200:
raise RuntimeError(f"HTTP {r.status_code}: {body[:80]}")
try:
ipaddress.ip_address(body)
except ValueError:
raise RuntimeError(f"not an IP address: {body[:80]}") from None
return body
direct = egress_ip("https://api.ipify.org", timeout=10)
proxied = egress_ip("https://api.ipify.org", proxies={"http": PROXY, "https": PROXY}, timeout=(10, 30))
print(f"direct: {direct}")
print(f"proxied: {proxied}")
if direct == proxied:
raise RuntimeError("traffic is not leaving through the proxy")Run it at deploy time, not only during development. It proves the route to the echo service goes through the proxy; it does not prove that any particular target accepts the proxy. It catches an expired credential and a proxy that is not being applied. If your application takes its proxy from environment variables or a configured session, run the check through that same configuration instead of the explicit proxies= shown here, which outranks both. On a rotating gateway, two proxied calls on separate connections may print different addresses; that is the product working.
To confirm the credentials themselves, send one authenticated request to a plain http:// URL such as http://api.ipify.org: the proxy answers a bad credential with a readable 407 status instead of the tunnel exception an https:// target produces, and a 200 means it accepted them. Echo services cannot help here: Proxy-Authorization is consumed by the proxy and never reaches a page such as httpbin.org/headers.
If the check fails, walk back through this guide: the scheme on the https key, environment variables overriding the session, credentials encoded. If the proxied call returns a 407 instead, the 407 guide works the causes in order of likelihood.
Scrapy is not covered here: its downloader middleware wraps these primitives in project-level machinery with its own conventions, in Scrapy proxy middleware. If your Python code drives a headless browser rather than an HTTP client, Chromium refuses credentials where every library above accepts them; Puppeteer and Playwright proxies explains the mechanism that replaces them. For choosing which product this code should point at (shared datacenter for volume, residential for targets that classify datacenter ranges), the pricing page lays the options side by side.
Runnable versions of these patterns (requests, httpx, aiohttp, SOCKS5, sticky sessions, retries and a static proxy checker) are in the Python folder of our examples repository on GitHub.