Python Requests Proxy: Setup, Auth, SOCKS5 and Rotation

Working proxy code for Python requests and httpx: sessions, authentication, HTTP_PROXY and NO_PROXY, SOCKS5, rotation, retries, and fixes for 407 and SSL.

To use a proxy with Python requests, pass a proxies dictionary that maps each target scheme to the proxy URL. The proxy URL starts with http:// even when the target is https://, so both entries use the same URL:

import requests

proxy = "http://USERNAME:PASSWORD@HOST:PORT"
proxies = {"http": proxy, "https": proxy}

r = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30))
print(r.text)

If you whitelist your source IP instead of using credentials, drop USERNAME:PASSWORD@ from the URL.

The script prints the proxy's exit address instead of your own. That one line of output is the proof that the request left through the proxy.

What you need: Python 3 with pip install requests, and a proxy URL. On Node4, copy it from the Connect card on the dashboard's Proxies page. A free account is enough for every HTTP example on this page: it includes 3 shared datacenter proxies and 1 GB of traffic a month. SOCKS5 and the rotating gateways need a paid plan, noted where they appear. If you whitelist your IP instead of using credentials, drop USERNAME:PASSWORD@ and everything else holds.

You want toUse
Proxy one requestrequests.get(url, proxies=proxies)
Proxy every request and reuse connectionssession.proxies = proxies on a requests.Session
Configure the proxy outside the codeHTTP_PROXY and HTTPS_PROXY environment variables
Skip the proxy for some hostsNO_PROXY
Use SOCKS5pip install "requests[socks]", then a socks5h:// URL
Change IP on every requestA rotating gateway, or cycle a list in code
Use async codehttpx.AsyncClient(proxy=...), or aiohttp

How the proxies dictionary works

The keys name the scheme of the target URL. The values name the proxy. requests looks up the key that matches each request, so:

  • Set both keys. With only "http" present, an https:// request finds no entry and goes direct, with no warning. The same happens when an http:// URL redirects to https://.
  • Keep http:// in the value under "https". Your client speaks plain HTTP to the proxy, asks it for a CONNECT tunnel, and performs the TLS handshake with the destination through that tunnel. The destination's certificate is still verified by your machine, and the proxy relays encrypted bytes it cannot read.

Writing https:// as the proxy scheme tells requests to open TLS to the proxy itself. Against an HTTP proxy endpoint that raises ProxyError, with the hint "Your proxy appears to only use HTTP and not HTTPS" wrapped around an SSLError that says "wrong version number". The fix is the scheme, never verify=False.

Python requests proxy authentication

Put the username and password in the proxy URL. requests turns them into a Proxy-Authorization header on plain HTTP requests and on the CONNECT that opens an HTTPS tunnel.

Passwords with reserved characters break URL parsing: a / or # makes requests raise InvalidURL. Percent-encode each half before building the URL:

from urllib.parse import quote

import requests

username = quote("USERNAME", safe="")
password = quote("p@ss:w/rd#1", safe="")

proxy = f"http://{username}:{password}@HOST:PORT"
proxies = {"http": proxy, "https": proxy}

r = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30))
print(r.text)

Pass safe="" explicitly. The default leaves / unescaped, because quote is usually applied to paths.

Two things that look like proxy authentication and are not:

  • auth=("user", "pass") sends credentials to the destination site, not to the proxy.
  • requests.auth.HTTPProxyAuth adds the header to the request itself. That works for http:// targets, but for https:// the header travels inside the tunnel, the CONNECT goes out without credentials, and the proxy answers 407. Use URL credentials.

On Node4, one credential works on every product your account has an active plan for. The alternative is IP whitelisting under Auth & IP Access in Account Settings: register your address and connect with no username or password. Whitelisting works on every product, but a whitelisted connection carries no username, so its exit is untargeted: country, city and session targeting need the credential. Authentication covers both.

Use a Session for more than one request

A Session keeps connections open and reuses them. Through a proxy that saves a TCP connection to the proxy, a CONNECT round trip and a TLS handshake on every request after the first.

import requests

proxy = "http://USERNAME:PASSWORD@HOST:PORT"

session = requests.Session()
session.trust_env = False
session.proxies = {"http": proxy, "https": proxy}

for path in ("/", "/?format=json"):
    r = session.get(f"https://api.ipify.org{path}", timeout=(10, 30))
    print(r.status_code, r.text)

session.close()

session.trust_env = False is deliberate. By default requests merges proxy environment variables into every call, and they outrank session.proxies. A stray HTTPS_PROXY in a CI runner or container silently replaces the proxy you set in code. Turning trust_env off makes the code the only source.

A session also keeps cookies. Cookies collected on direct requests are sent through the proxy afterwards, so give proxied work its own session when that state should not be shared.

Proxy environment variables: HTTP_PROXY, HTTPS_PROXY, NO_PROXY

requests reads the standard variables with no code changes:

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.example.com"

On Windows PowerShell the form is $env:HTTPS_PROXY = "http://USERNAME:PASSWORD@HOST:PORT". Lowercase names work too, and ALL_PROXY sets one proxy for every scheme.

When several sources disagree, this is the order requests 2.34 applies:

SettingWins overLoses to
proxies= on the callEnvironment and session.proxiesNothing
HTTP_PROXY / HTTPS_PROXYsession.proxiesproxies= on the call
session.proxiesNothing, unless trust_env = FalseBoth of the above
NO_PROXYThe environment's proxy for listed hostsA proxy set in code

NO_PROXY takes a comma-separated list of hostnames, domain suffixes and IP addresses. It only cancels a proxy that came from the environment. A proxy set through proxies= or session.proxies still applies to a listed host, so to bypass the proxy for one call in code, use a separate session without proxies.

Environment configuration keeps credentials out of source control and lets the same code run proxied in production and direct on a laptop. Its weakness is that a missing variable fails silently and traffic goes direct, which is why the egress check at the end of this page belongs in your deploy.

Python requests SOCKS5 proxy

requests has no SOCKS support of its own. Install the extra, which adds PySocks:

pip install "requests[socks]"

Without it, a SOCKS URL raises InvalidSchema: Missing dependencies for SOCKS support. With it, the same dictionary takes a SOCKS URL:

import requests

proxy = "socks5h://USERNAME:PASSWORD@HOST:SOCKS_PORT"
proxies = {"http": proxy, "https": proxy}

r = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30))
print(r.text)

Write socks5h, not socks5, in both entries:

SchemeWho resolves the hostnameEffect
socks5h://The proxyLookups happen at the exit. Your resolver never sees the target's name
socks5://Your machineEvery hostname is looked up locally first: a DNS leak, and geo-aware DNS answers for your location instead of the exit's

On Node4, SOCKS5 uses the same host and credentials as HTTP on a different port, shown when you switch the Connect card to SOCKS5. Every paid product has it. The free tier is HTTP(S) only, and a free account's credential is refused on the SOCKS5 port. SOCKS5 proxy setup has the per-product ports, and HTTP vs SOCKS5 helps you decide whether you need it: for ordinary web requests the target sees the same exit address either way.

Rotating proxies with Python requests

There are two ways to change the exit address between requests. Choose a gateway if you want rotation without managing addresses. Choose a list if you bought specific IPs and want to control which request uses which.

Rotation by gateway: one URL, a pool behind it

A rotating gateway is a single hostname that picks an exit from a pool for each connection. The code is the basic example with a different URL:

import requests

gateway = "http://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:8083"
proxies = {"http": gateway, "https": gateway}

for _ in range(3):
    r = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30))
    print(r.text)

This prints three addresses. A later pick can repeat an earlier one, so expect variety, not a strict no-repeat sequence.

The exit belongs to the connection, which matters for how you write the loop:

  • requests.get(...) opens a new connection per call, so each call gets its own pick.
  • A Session keeps its HTTPS tunnel open, so requests to the same host keep the same exit until that connection closes. For a new address on each request, call requests.get directly or send headers={"Connection": "close"}.
  • To hold one address on purpose (a login, a cart, a paginated crawl), add a session id to the username: USERNAME-session-task81f3. Every connection carrying that id uses the same exit for up to 30 minutes. Sticky vs rotating sessions covers the details.
import requests

sticky = "http://USERNAME-session-task81f3:PASSWORD@gw-rotating_datacenter.node4.io:8083"

session = requests.Session()
session.trust_env = False
session.proxies = {"http": sticky, "https": sticky}

print(session.get("https://api.ipify.org", timeout=(10, 30)).text)
print(session.get("https://api.ipify.org", timeout=(10, 30)).text)

Both lines print the same address.

Node4 sells this gateway two ways, on the same pool with exits in the US, Italy and Spain. Rotating Datacenter is billed per gigabyte, from $5.90/month for 10 GB ($0.59/GB). Rotating Unmetered has no byte meter and is priced by concurrent connections, from $29.00/month for 250 connections ($0.116 per connection), on gw-rotating_unmetered.node4.io port 8084. Pay by the gigabyte if you use a little, by concurrency if you use a lot: rotating pricing and unmetered pricing list every tier. The free tier does not reach the gateways.

Rotation in code: cycle a proxy list

With a list of static proxies, your code decides. This version cycles the list, sets a failing proxy aside for a cooldown, and moves on:

import itertools
import time

import requests

PROXIES = [
    "http://USERNAME:PASSWORD@HOST1:PORT",
    "http://USERNAME:PASSWORD@HOST2:PORT",
    "http://USERNAME:PASSWORD@HOST3:PORT",
]
COOLDOWN = 60  # seconds a failing proxy sits out

pool = itertools.cycle(PROXIES)
resting = {}  # proxy -> time it may be used again


def fetch(url, attempts=3):
    last_error = None
    for _ in range(attempts):
        proxy = next(pool)
        if resting.get(proxy, 0) > time.monotonic():
            continue
        try:
            r = requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=(10, 30))
            r.raise_for_status()
            return r
        except (requests.exceptions.ProxyError, requests.exceptions.ConnectionError,
                requests.exceptions.Timeout) as exc:
            resting[proxy] = time.monotonic() + COOLDOWN
            last_error = exc
    raise RuntimeError(f"no proxy could fetch {url}") from last_error


for url in ["https://api.ipify.org", "https://api.ipify.org?format=json"]:
    print(fetch(url).text)

An HTTP error from the target (raise_for_status) is not caught, so a 404 does not bench a healthy proxy.

When a task needs one address throughout, cycling breaks it. Create one Session per proxy and assign each task to one session, so cookies and exit stay together. Shared datacenter proxies and dedicated datacenter proxies are the list products, and how to rotate proxy IPs compares the mechanisms in more depth.

Timeouts, retries and backoff

requests has no default timeout. A proxied request can stall at the connection to the proxy, the tunnel, or the target's response, and without a timeout a stalled request holds its worker forever. Pass timeout=(connect, read) on every call: the first number bounds reaching the proxy, the second bounds each wait for data.

For retries, mount urllib3's Retry on the session once:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

proxy = "http://USERNAME:PASSWORD@HOST:PORT"

retry = Retry(
    total=4,
    backoff_factor=1,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["GET", "HEAD"],
    respect_retry_after_header=True,
)
adapter = HTTPAdapter(max_retries=retry, pool_maxsize=20)

session = requests.Session()
session.trust_env = False
session.proxies = {"http": proxy, "https": proxy}
session.mount("http://", adapter)
session.mount("https://", adapter)

r = session.get("https://api.ipify.org", timeout=(10, 30))
print(r.status_code, r.text)
  • backoff_factor=1 doubles the wait after each failed attempt, so retries do not hammer a target that is already throttling you.
  • allowed_methods limits retries to idempotent verbs. A POST is not replayed because a hop timed out.
  • respect_retry_after_header waits as long as a 429 or 503 asks.
  • Mount the adapter on both prefixes, or plain http:// URLs get no retries.
  • pool_maxsize should match the number of threads sharing the session. The default is 10, and surplus connections are opened and discarded instead of reused.

On a rotating gateway, a status-code retry inside a Session goes back out through the same open tunnel and the same exit. If a retry should come from a different address, send it on a new connection: catch the failure yourself and retry with requests.get, as the list example above does.

Python requests proxy errors and fixes

What you seeCauseFix
ProxyError ... Tunnel connection failed: 407 Proxy Authentication RequiredThe proxy rejected the credentials while opening an HTTPS tunnelCheck username, password, encoding and whitespace. The 407 guide works the causes in order
A response with status_code == 407Same rejection on a plain http:// target, where it arrives as a responseSame fix
ProxyError ... Your proxy appears to only use HTTP and not HTTPS, SSLError ... wrong version numberThe proxy URL starts with https://Change the proxy scheme to http://
SSLError ... CERTIFICATE_VERIFY_FAILEDThe destination's certificate failed verification on your machine. A CONNECT proxy does not replace certificatesUpdate certifi, check the system clock, check for TLS-inspecting software. Do not set verify=False
ProxyError ... Connection refused, or ConnectTimeoutThe client never reached the proxyCheck host and port against the Connect card, and your outbound firewall
ReadTimeoutConnected, but the target was slow to answerRaise the read timeout, retry, or try another exit
InvalidURL: Failed to parseA reserved character in the passwordPercent-encode with quote(value, safe="")
InvalidSchema: Missing dependencies for SOCKS support.PySocks is not installedpip install "requests[socks]"
ConnectionError ... 0x02: Connection not allowed by rulesetSOCKS5 refusal: wrong credentials, a free account on the SOCKS5 port, or a Rotating Unmetered plan at its connection limitCheck credentials and plan. See connection limits
A 401 responseThe destination wants its own loginNot a proxy problem. Proxy credentials will not fix it
The script prints your own IPThe proxy is not applied: a missing dictionary key, or an environment variable replacing your settingSet both keys, set trust_env = False, and list the proxy variables in your shell environment

A request that succeeds through the proxy and still gets a 403 or a CAPTCHA from the target is not a configuration error: the target is judging the address or the request. Why is my IP getting blocked covers that side.

httpx proxy setup

httpx takes one proxy= URL on the client, for sync and async code:

import asyncio

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)


async def main() -> None:
    async with httpx.AsyncClient(proxy=PROXY, timeout=TIMEOUT) as client:
        r = await client.get("https://api.ipify.org")
        print(r.text)


asyncio.run(main())

What differs from requests:

  • proxies= is gone. httpx deprecated the dictionary argument in 0.26 and removed it in 0.28, where it raises TypeError: Client.__init__() got an unexpected keyword argument 'proxies'. Use proxy=.
  • The proxy is fixed at construction. To change route, build a new client. For per-destination routing, mounts= maps URL patterns to transports:
import httpx

client = httpx.Client(
    mounts={
        "all://": httpx.HTTPTransport(proxy="http://USERNAME:PASSWORD@HOST:PORT"),
        "all://internal.example.com": httpx.HTTPTransport(),
    }
)
  • Environment variables are read once, when the client is created, and an explicit proxy= replaces them. httpx.Client(trust_env=False) ignores them.
  • SOCKS5 needs pip install "httpx[socks]", then proxy="socks5h://USERNAME:PASSWORD@HOST:SOCKS_PORT". httpx sends the hostname to the proxy under both socks5:// and socks5h://.
  • A default timeout exists (five seconds), unlike requests. Raise the read phase for slow targets.
  • Retries cover connection failures only: httpx.HTTPTransport(retries=3, proxy=...). For status-code retries, wrap calls with a library such as tenacity.
  • A 407 on an HTTPS target raises httpx.ProxyError: 407 Proxy Authentication Required.

aiohttp, Scrapy and browsers

aiohttp sets the proxy per request with session.get(url, proxy=...), ignores proxy environment variables unless you opt in, and needs a separate connector for SOCKS5. It has its own page: aiohttp proxy setup.

Scrapy wraps proxying in downloader middleware with its own conventions: see Scrapy proxy middleware and the Scrapy proxies page. If your Python code drives a headless browser, Chromium refuses credentials in the proxy URL, and Puppeteer and Playwright proxies explains what replaces them. For Node rather than Python, see Node.js proxy setup.

Check that traffic leaves through the proxy

End every integration with the same check: ask an IP echo service who you are, direct and proxied, and fail loudly if the answers match.

import ipaddress

import requests

PROXY = "http://USERNAME:PASSWORD@HOST:PORT"


def egress_ip(**kwargs):
    r = requests.get("https://api.ipify.org", **kwargs)
    body = r.text.strip()
    if r.status_code != 200:
        raise RuntimeError(f"HTTP {r.status_code}: {body[:80]}")
    ipaddress.ip_address(body)  # raises ValueError if the body is not an IP
    return body


direct = egress_ip(timeout=10)
proxied = egress_ip(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")

Expected output is two different addresses. The check accepts only a 200 whose whole body is an IP address, so an error page cannot pass as a proxied exit, and it raises instead of using assert, which python -O strips.

If your application takes its proxy from environment variables or a configured session, run the check through that same configuration, not the explicit proxies= shown here, which outranks both. On a rotating gateway, two proxied calls may print different addresses. That is the product working.

To test the credentials alone, send one request to a plain http:// URL such as http://api.ipify.org: a bad credential comes back as a readable 407 status instead of a tunnel exception.

Not sure which product this code should point at? Which Node4 proxy for which job matches products to workloads, and the pricing page lists every plan. Runnable versions of these patterns are in the Python folder of our examples repository on GitHub.