How to Use a Proxy With Python Requests: Auth and SOCKS5

Published:

16 minute read

Acar Diveroli
Written by: Acar Diveroli
Isometric editor window with a proxies dictionary, the https line in blue, and a dashed EXIT IP card behind it

You add proxies={"http": "http://user:pass@pr.proxynet.io:8000"} to a Python script, run it, and the IP-echo service still prints your own address. There is no error and no warning: Requests simply sent the HTTPS request directly, because the dictionary had no https key. Most proxy problems in Requests look like this one. The code runs, but the request never goes through the proxy, or it fails with an error that hides the real cause.

This guide covers the whole setup in Requests: the proxies dictionary and its keys, per-request vs Session.proxies, the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables, usernames and passwords with special characters, SOCKS5 with socks5 and socks5h, rotating and sticky sessions on a gateway, timeouts, and the errors a proxy produces. We ran every example with Python 3.13 and Requests 2.34.2 against a local test proxy on 127.0.0.1 that asks for a username and password and logs every request, so each claim below was checked against what the proxy actually received.

How does Requests send a request through a proxy?

Requests picks the proxy by the scheme of the target URL, not by the type of proxy. The proxies dictionary maps http and https (the target's scheme) to a proxy URL, and the proxy URL's own scheme says how to talk to the proxy. That is why the common setup has two keys that point to the same http:// address.

  1. You call requests.get("https://httpbin.org/ip", proxies=...). Requests looks up the https key, because the target starts with https://.
  2. For an http:// target, Requests sends the full URL to the proxy (GET http://httpbin.org/ip) with a Proxy-Authorization header built from the username and password.
  3. For an https:// target, Requests first sends CONNECT httpbin.org:443 with the same header. The proxy opens a TCP connection to the site and answers 200 Connection established.
  4. TLS runs inside that tunnel, between your script and the site. The proxy forwards encrypted bytes and cannot read the page; certificate checks still happen against the target's certificate.
  5. The site sees the proxy's exit IP, not yours. With a rotating gateway, the next tunnel may get a different exit.

Step 4 answers a common question: a normal forwarding proxy does not need its own certificate on your machine. Only a proxy that decrypts HTTPS on purpose (a corporate TLS-inspection box, or a debugging tool like Burp) needs its root certificate trusted, which the Requests proxy documentation explains along with REQUESTS_CA_BUNDLE.

How do you set a proxy for one request?

Pass the dictionary to the request method. Keep the credentials out of the code and read them from the environment:

python
import os
import requests

proxy_url = os.environ.get("PROXY_URL", "http://user:pass@pr.proxynet.io:8000")
proxies = {"http": proxy_url, "https": proxy_url}

r = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=(5, 15))
print(r.status_code, r.json())

Three details decide whether this works:

  • Both keys. In our test, a dictionary with only the http key sent an https:// request straight to the site; the proxy log stayed empty.
  • Lowercase keys. {"HTTPS": url} was ignored the same way. The keys are http and https, plus optional host-specific keys such as "https://api.example.com".
  • The scheme in the proxy URL. user:pass@pr.proxynet.io:8000 without http:// raised InvalidProxyURL: Please check proxy URL. It is malformed and could be missing the host. Write the scheme every time.

The proxy URL starts with http:// even under the https key. Writing https://pr.proxynet.io:8000 tells Requests to open TLS to the proxy itself, which a plain HTTP proxy port does not speak. On our test proxy that request hung until the read timeout and ended in ProxyError: … Unable to connect to proxy. Use https:// for the proxy only if your provider gives you a TLS proxy endpoint.

Session.proxies or per-request proxies?

Per-request proxies is the reliable choice, because a value set on Session.proxies can be replaced by proxy environment variables. The Requests documentation warns about this, and our test showed it plainly: with session.proxies pointing at a working proxy and HTTPS_PROXY pointing at a dead port, the session used the dead port and failed with ProxyError. The same session with proxies= passed on the call went through the working proxy.

python
import requests

proxy_url = "http://user:pass@pr.proxynet.io:8000"

# Option 1: pass proxies on every call (environment variables cannot override it)
with requests.Session() as s:
    r = s.get("https://httpbin.org/ip", proxies={"http": proxy_url, "https": proxy_url}, timeout=(5, 15))

# Option 2: session-level proxies, with environment proxies switched off
with requests.Session() as s:
    s.trust_env = False
    s.proxies = {"http": proxy_url, "https": proxy_url}
    r = s.get("https://httpbin.org/ip", timeout=(5, 15))

trust_env = False tells the session to ignore environment settings for proxies (and for a few other things, such as .netrc credentials and REQUESTS_CA_BUNDLE). In our run, option 2 also went through the right proxy while the dead HTTPS_PROXY was still set. Use it when a script must behave the same on every machine, whatever the shell or the operating system has configured.

A Session also keeps the connection open between calls, so several requests share one tunnel and one exit IP. That matters for rotation, which we come back to below.

Where can the proxy come from?

Requests can take the proxy from four places. When a script uses a proxy you did not expect, or ignores the one you set, check them in this order.

SourceHow you set itScopeNotes
proxies= argumentIn the callOne requestWins over the environment
Session.proxiesOn the sessionEvery call in the sessionEnvironment can override it
Environment variablesHTTPS_PROXY, NO_PROXY…Every script in the shellRead only if trust_env is on
System settingsWindows registry, macOSThe whole machineUsed when no variable is set

The last row surprises people on Windows and macOS. Requests reads the environment through Python's urllib.request.getproxies(), which falls back to the Windows registry or the macOS System Configuration when no proxy variable exists. A system-wide proxy turned on in Windows settings can therefore reach a script that never mentions a proxy.

How do you use the HTTP_PROXY and HTTPS_PROXY environment variables?

Environment variables route a script through a proxy without touching its code. Requests reads http_proxy, https_proxy, all_proxy and no_proxy, in lowercase or uppercase; if both forms exist with different values, Python prefers the lowercase one. HTTPS_PROXY is the one most scripts need, since most targets are HTTPS.

On Linux and macOS:

bash
export HTTPS_PROXY="http://user:pass@pr.proxynet.io:8000"
export HTTP_PROXY="$HTTPS_PROXY"
export NO_PROXY="localhost,127.0.0.1,.internal.example"
python app.py

In Windows PowerShell:

powershell
$env:HTTPS_PROXY = "http://user:pass@pr.proxynet.io:8000"
$env:HTTP_PROXY = $env:HTTPS_PROXY
$env:NO_PROXY = "localhost,127.0.0.1"
python app.py

NO_PROXY lists hosts that skip the proxy: a comma-separated list of host names or domain suffixes. In our test, NO_PROXY=httpbin.org sent the request directly even though HTTPS_PROXY was set. To skip the proxy for one call from code, pass proxies={"http": None, "https": None}: a key set to None stops the environment value from filling it in, and our request went out directly with a dead HTTPS_PROXY still in place.

To see what Python reads, print urllib.request.getproxies(). With the variables above it returned {'https': 'http://user:***@127.0.0.1:18080', 'no': 'localhost,127.0.0.1'} on our machine (password masked here). Keep in mind that a password in an environment variable is visible to other processes of the same user and often ends up in shell history; on a shared server, read it from a secrets store instead.

How do you add a username and password to the proxy?

Put them in the proxy URL: http://USERNAME:PASSWORD@pr.proxynet.io:8000. Requests turns them into a Proxy-Authorization: Basic header. The auth= parameter is not for the proxy; it authenticates you to the target site.

The trap is special characters. A password such as p@ss:w#rd/1 breaks the URL, because @, :, # and / all have a meaning there. Our test with the raw password failed before any connection was made:

text
requests.exceptions.InvalidURL: Failed to parse: http://user:p@ss:w#rd/1@127.0.0.1:18080

Encode the username and password separately before you build the URL:

python
import os
from urllib.parse import quote

user = quote(os.environ["PROXY_USER"], safe="")
password = quote(os.environ["PROXY_PASS"], safe="")  # p@ss:w#rd/1 -> p%40ss%3Aw%23rd%2F1

proxy_url = f"http://{user}:{password}@pr.proxynet.io:8000"
proxies = {"http": proxy_url, "https": proxy_url}

With the encoded form, the proxy received the correct password and let the request through. safe="" matters: the default quote() leaves / unencoded.

Use Requests 2.31.0 or newer when the credentials sit in the proxy URL. The Requests release history records that versions 2.3.0 to 2.30.0 could forward the Proxy-Authorization header to the destination server when following an HTTPS redirect, and advises upgrading and rotating the proxy password. Check yours with python -c "import requests; print(requests.__version__)".

The proxy can also accept you without a password. With IP whitelist authentication, you register your server's public IP in the provider's panel (Proxynet allows up to 10 addresses) and the proxy URL becomes http://pr.proxynet.io:8000 with no credentials. That suits fixed servers; for laptops and CI runners whose address changes, username and password is simpler.

How do you use a SOCKS5 proxy with Requests?

Install the SOCKS extra, then use a socks5h:// URL under both keys:

bash
python -m pip install "requests[socks]"
python
import requests

# socks5h: the proxy resolves the host name, so no DNS query leaves your network
socks_url = "socks5h://user:pass@pr.proxynet.io:1080"
proxies = {"http": socks_url, "https": socks_url}

r = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=(5, 15))
print(r.json())

The extra installs PySocks, whose latest release is 1.7.1; Requests has supported SOCKS since version 2.10.0. Without it, a socks5h:// URL fails with InvalidSchema: Missing dependencies for SOCKS support.

The letter h changes where DNS happens. Our SOCKS5 test server logged the address type of each CONNECT: with socks5:// it received an IPv4 address, meaning our machine had already resolved httpbin.org; with socks5h:// it received the name httpbin.org and resolved it itself. Use socks5h:// unless the target is a name only your own DNS knows, such as a host on your internal network. Remote resolution also returns the address that suits the proxy's location, which matters for sites served from many regions.

Two errors are specific to SOCKS. A wrong password came back as ConnectionError: … SOCKS5 authentication failed, not as a 407, because SOCKS has no HTTP status codes. A socks5h:// URL pointed at the HTTP port hung and ended in ConnectTimeout after our 5-second limit; check that the port in the URL is the SOCKS port. A Proxynet SOCKS5 Proxy runs on its own port next to the HTTP port, and its SOCKS5 also carries UDP, which Requests does not use.

How do rotating and sticky sessions work with a gateway?

A gateway is one address in front of a large IP pool: your code always connects to pr.proxynet.io:8000, and the gateway chooses the exit IP. Options travel inside the username. With Proxynet Residential Proxy, the panel's Endpoint Generator builds it from your choices, for example:

python
import uuid

base_user = "user"                         # the account part from the panel
country_user = f"{base_user}-country-us"   # exits in one country
sticky_id = uuid.uuid4().hex[:8]
sticky_user = f"{base_user}-session-{sticky_id}-ttl-600"  # same exit for up to 600 s

proxy_url = f"http://{sticky_user}:pass@pr.proxynet.io:8000"

Copy the exact string from the panel rather than building it from memory. Hyphens and letters need no URL encoding, and our test proxy received the full user-session-ab12cd34-ttl-600 name unchanged. Sticky sessions on residential and mobile proxies hold an exit for 1 to 60 minutes; country and city targeting is available on both, and ASN targeting on residential.

Rotation follows the connection, not the call. Every new tunnel can get a new exit, but a requests.Session keeps its tunnel open, so three s.get() calls usually leave from the same IP. For an IP per request, call requests.get() without a session; for one IP across a login flow, use a session together with a session ID. We measured this tunnel reuse in detail in Web Scraping in Python With Rotating Proxies, which also covers Retry-After handling.

How do you check the exit IP and retry failed requests?

The script below is the check we run before any job that depends on a proxy. It asks an IP-echo service for the address twice, once directly and once through the proxy, retries temporary failures with exponential backoff, and stops at once on a 407, because a wrong password does not fix itself.

python
"""Check that requests leave through the proxy: compare the exit IP, retry with backoff."""
import os
import random
import sys
import time
from urllib.parse import quote

import requests

PROXY_HOST = os.environ.get("PROXY_HOST", "pr.proxynet.io:8000")
PROXY_USER = os.environ["PROXY_USER"]
PROXY_PASS = quote(os.environ["PROXY_PASS"], safe="")  # encodes @ : / # in the password
PROXY_URL = f"http://{PROXY_USER}:{PROXY_PASS}@{PROXY_HOST}"

ECHO_URL = "https://api.ipify.org?format=json"
RETRY_STATUS = {429, 502, 503, 504}
TIMEOUT = (5, 15)  # (connect, read) in seconds


def make_session(proxy_url=None):
    s = requests.Session()
    s.trust_env = False  # ignore HTTP(S)_PROXY and system settings: only what we set here counts
    if proxy_url:
        s.proxies = {"http": proxy_url, "https": proxy_url}
    s.headers["User-Agent"] = "proxy-check/1.0"
    return s


def exit_ip(session, attempts=4, base_delay=1.0):
    for attempt in range(1, attempts + 1):
        try:
            r = session.get(ECHO_URL, timeout=TIMEOUT)
            if r.status_code == 407:
                sys.exit("407: the proxy rejected the username or password")
            if r.status_code in RETRY_STATUS:
                raise requests.HTTPError(f"HTTP {r.status_code}", response=r)
            r.raise_for_status()
            return r.json()["ip"]
        except requests.exceptions.ProxyError as e:
            if "407" in str(e):  # HTTPS targets: the 407 arrives inside the ProxyError
                sys.exit("407: the proxy rejected the username or password")
            error = e
        except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.HTTPError) as e:
            error = e
        if attempt == attempts:
            raise error
        delay = base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.5)
        print(f"attempt {attempt} failed ({type(error).__name__}), retrying in {delay:.1f} s")
        time.sleep(delay)


if __name__ == "__main__":
    with make_session() as direct, make_session(PROXY_URL) as proxied:
        own_ip = exit_ip(direct)
        proxy_ip = exit_ip(proxied)
    print("without proxy:", own_ip)
    print("through proxy:", proxy_ip)
    if own_ip == proxy_ip:
        sys.exit("same address: the request did not go through the proxy")
    print("OK: the proxy is in use")

Run it with the credentials in the environment: PROXY_USER=user PROXY_PASS='…' python check_proxy.py. We tested it against our local proxy set to answer the first two requests with 502 Bad Gateway. The script printed attempt 1 failed (HTTPError), retrying in 1.3 s and attempt 2 failed (HTTPError), retrying in 2.4 s, then returned the proxy's address on the third try. For an HTTPS target, the same 502 arrives during the tunnel setup and shows up as ProxyError, which the script also retries. With a wrong password it stopped after one request with the 407 message.

The order of the except blocks matters: ProxyError is a subclass of ConnectionError, so it has to come first. The random part of the delay keeps many workers that failed together from retrying at the same moment. Requests does not retry on its own; besides a loop like this, it accepts a urllib3.util.Retry object mounted on a Session through an HTTPAdapter.

Which timeout should you set, and what do proxy errors mean?

Always pass timeout, because Requests waits forever by default. A tuple such as (5, 15) gives 5 seconds to connect and 15 seconds between bytes of the answer. A proxy that accepted the connection but never answered our CONNECT raised ReadTimeout after the first value, 3 seconds in that test, rather than ConnectTimeout, so catch requests.exceptions.Timeout, which covers both.

What you seeWhat it meansFirst fix
ProxyError with 407Wrong or missing credentials, HTTPS targetCheck the username and encode the password
Response status 407The same, on an http:// targetSame as above; no exception is raised
ProxyError, connection refusedNothing listens at that host and portCheck the host, port and firewall
ReadTimeout or ConnectTimeoutThe proxy or the exit is not answeringRetry with backoff; check the port
InvalidURL / InvalidProxyURLThe proxy URL cannot be parsedAdd http://, encode special characters
SOCKS5 authentication failedWrong SOCKS credentialsCheck the username and password
InvalidSchema for SOCKSPySocks is not installedpip install "requests[socks]"

The 407 row hides a difference. For an HTTPS target, the proxy refuses the tunnel and Requests raises ProxyError: … Tunnel connection failed: 407 Proxy Authentication Required. For a plain http:// target, the proxy's 407 comes back as an ordinary response, so r.status_code is 407 and nothing is raised unless you call raise_for_status(). Requests wraps most of these in a Max retries exceeded with url line; how to read the Caused by part is explained in Max Retries Exceeded With URL.

Certificate errors are a separate family. An SSLError through a proxy usually means a TLS-inspecting proxy whose root certificate your Python does not trust, or an outdated CA bundle; the causes and safe fixes are in How to Fix Python Requests SSLError. Turning off verification with verify=False only proves the cause during a test; it is not a fix, because it accepts any certificate.

Where is this setup used?

Teams use a proxy in Requests when a script has to reach a service from a specific network or country. A QA team checks how its own API or storefront answers visitors from another market. A monitoring job confirms that a public page loads the same way in several regions. A CI runner inside a company network reaches the internet only through the corporate proxy, which the environment variables cover without code changes. Data teams send collection jobs for public data through a residential pool so the load spreads across many addresses and the jobs keep to each site's limits. In each case the setup is the same few lines; only the username options change.

Common mistakes

  • Only the http key. HTTPS requests go out directly, with no error.
  • https:// in the proxy URL. Requests tries TLS to a plain HTTP proxy port and times out or fails.
  • Raw special characters in the password. @, :, # and / break the URL; use quote(…, safe="").
  • Trusting Session.proxies alone. An HTTPS_PROXY in the environment can replace it; pass proxies= per call or set trust_env = False.
  • socks5:// when you meant socks5h://. DNS is resolved on your machine and may point to the wrong region.
  • No timeout. A silent exit blocks the script indefinitely.
  • Retrying a 407. A wrong password fails the same way every time; stop and fix it.
  • Expecting a new IP from every call in one Session. The open tunnel keeps the same exit.
  • Credentials in the code. Read them from the environment or a secrets store, and keep them out of version control.

Which setup should you choose?

Your situationRecommendation
One script, one proxyproxies= on each call, both keys
Many calls, fixed behaviour on any machineSession with trust_env = False
Existing script, no code changesHTTPS_PROXY and NO_PROXY variables
Password with special charactersurllib.parse.quote(…, safe="")
SOCKS5 proxyrequests[socks] and socks5h://
New IP for each requestRotating gateway, no shared session
Same IP for a login flowSticky session ID and one Session
Fixed server, no password in codeIP whitelist authentication

Frequently asked questions

Why is Python Requests ignoring my proxy?

Usually the dictionary has no https key, or the key is uppercase, so an HTTPS request goes out directly. The other common cause is a Session.proxies value replaced by an HTTPS_PROXY variable. Pass proxies= on each call and compare the exit IP with and without the proxy.

How do I use a proxy with authentication in Python Requests?

Write the credentials into the proxy URL: http://user:pass@host:port, under both the http and https keys. Encode them with urllib.parse.quote(value, safe="") if they contain @, :, # or /. The auth= parameter is for the target site, not the proxy.

Does Requests read the HTTPS_PROXY environment variable?

Yes. Requests reads HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY in either case, and on Windows and macOS it falls back to the system proxy settings when no variable is set. A session with trust_env = False ignores all of them.

What is the difference between socks5 and socks5h in Requests?

With socks5://, your machine resolves the host name and sends the proxy an IP address. With socks5h://, the proxy receives the name and resolves it itself, so no DNS query leaves your network. Both need requests[socks].

How do I bypass the proxy for localhost or one request?

Add the hosts to NO_PROXY, for example localhost,127.0.0.1. For a single call, pass proxies={"http": None, "https": None}, which keeps the environment value from being used for that request.

How do I use Burp Suite as a proxy for Python Requests?

Point both keys at Burp's listener, which by default runs on port 8080 of the loopback interface: http://127.0.0.1:8080. Burp decrypts HTTPS, so pass its CA certificate file to verify= or set REQUESTS_CA_BUNDLE. Avoid verify=False as a shortcut; it hides real certificate problems.

Summary

To use a proxy with Python Requests, pass a proxies dictionary with both http and https keys pointing to an http:// proxy URL, and always set a timeout. Encode special characters in the password, prefer per-request proxies or trust_env = False over a bare Session.proxies, use NO_PROXY for hosts that should skip the proxy, and choose socks5h:// for SOCKS5. Check the exit IP before a job starts and retry only the failures that can recover. Residential, mobile and SOCKS5 endpoints that work with this code are on the Proxynet proxies page.

Ask ChatGPTAsk Claude