How to use proxies with Python requests: auth, SOCKS5 and sessions

Python's requests library supports HTTP proxies out of the box and SOCKS5 with one extra package. This guide covers the proxy URL format, sessions, timeouts and retries, and the mistakes that leak your real IP or DNS.

7 min read · updated November 20, 2026

The basics: the proxies dictionary

requests chooses a proxy by the scheme of the URL you request. Set both the http and https keys, usually to the same proxy, or HTTPS requests will bypass it. The proxy URL itself carries the scheme, credentials, host and port.

HTTP(S) proxypython
import requests

PROXY = "http://USERNAME:PASSWORD@PROXY_HOST:PORT"
proxies = {"http": PROXY, "https": PROXY}

r = requests.get("https://api.ipify.org", proxies=proxies, timeout=15)
print(r.text)  # the proxy's IP

SOCKS5 with remote DNS

Install the SOCKS extra, then use the socks5h scheme. The h means the hostname is resolved by the proxy. With plain socks5, your machine resolves the name first: DNS leaves from your own network and regional sites may answer for the wrong country.

Proxy URL schemes in requests
SchemeProtocol to the proxyDNS resolved by
http://HTTP (CONNECT for HTTPS sites)The proxy
socks5://SOCKS5Your machine
socks5h://SOCKS5The proxy (recommended)
SOCKS5 (socks5h)python
# pip install "requests[socks]"
import requests

PROXY = "socks5h://USERNAME:PASSWORD@PROXY_HOST:PORT"
r = requests.get("https://api.ipify.org",
                 proxies={"http": PROXY, "https": PROXY}, timeout=15)
print(r.text)

Sessions, timeouts and retries

Reuse a Session so connections are pooled, always pass a timeout so a stuck request cannot hang your program, and retry only a few times with backoff. urllib3's Retry handles backoff for you.

Session with retriespython
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

PROXY = "socks5h://USERNAME:PASSWORD@PROXY_HOST:PORT"

session = requests.Session()
session.proxies = {"http": PROXY, "https": PROXY}
retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))

r = session.get("https://example.com/", timeout=(10, 30))  # connect, read
Environment variables (no code change)bash
export HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PORT"
export HTTP_PROXY="$HTTPS_PROXY"
python my_script.py   # requests reads these automatically

Common mistakes

Most proxy problems in requests come from a handful of mistakes. Check these before anything else.

  • Only the http key is set, so HTTPS requests go direct.
  • socks5 instead of socks5h, so DNS is resolved locally.
  • Special characters in the password are not URL-encoded (use urllib.parse.quote).
  • No timeout, so one stalled connection blocks the whole job.
  • Unbounded retries that multiply traffic when a site is refusing requests.

Async requests: httpx and aiohttp

For many requests at once, an async client beats threads around requests. httpx takes the proxy in the client and supports SOCKS5 with the socks extra. aiohttp takes an HTTP proxy per request and needs aiohttp-socks for SOCKS5; rdns=True resolves hostnames through the proxy.

httpx (async, SOCKS5)python
# pip install "httpx[socks]"
import asyncio, httpx

PROXY = "socks5://USERNAME:PASSWORD@PROXY_HOST:PORT"

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

asyncio.run(main())
aiohttp (HTTP and SOCKS5)python
# pip install aiohttp aiohttp-socks
import asyncio, aiohttp
from aiohttp_socks import ProxyConnector

async def main():
    # HTTP proxy: pass it per request
    async with aiohttp.ClientSession() as s:
        async with s.get("https://api.ipify.org", proxy="http://USERNAME:PASSWORD@PROXY_HOST:PORT") as r:
            print(await r.text())
    # SOCKS5: needs a connector
    conn = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@PROXY_HOST:PORT", rdns=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        async with s.get("https://api.ipify.org") as r:
            print(await r.text())

asyncio.run(main())

Rotate proxies and handle errors

Spread requests over several proxies and retry a failed one on another. Catch the proxy errors separately from the target's errors: a ProxyError means the proxy didn't connect, while a 403 or 429 from the site means the request went through and the site refused it.

Errors you'll meet and what they mean
ErrorCauseFix
ProxyErrorCan't connect to or through the proxyCheck host, port and that the proxy is active; retry on another
407 Proxy Authentication RequiredWrong or missing proxy loginCheck the credentials; URL-encode special characters in the password
ConnectTimeout / ReadTimeoutSlow exit or targetRaise the timeout or retry on another proxy
SSLError through the proxySomething intercepts TLS, or an old certificate storeUpdate certifi; don't turn verification off in production
403 or 429 from the siteThe site refused or rate-limited the requestSlow down, rotate IPs, send realistic headers
Rotation with retriespython
import random, requests
from urllib.parse import quote

PROXIES = [
    "http://USERNAME:PASSWORD@PROXY_HOST_1:PORT",
    "http://USERNAME:PASSWORD@PROXY_HOST_2:PORT",
]

def get(url):
    for attempt in range(3):
        proxy = random.choice(PROXIES)
        try:
            return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=20)
        except requests.exceptions.ProxyError:
            continue  # try another proxy
    raise RuntimeError("all proxies failed")

# A password with @, : or / must be URL-encoded first:
password = quote("p@ss:word", safe="")

Proxy authentication, session proxies and skipping the proxy

requests reads the proxy login from the proxy URL: http://USERNAME:PASSWORD@PROXY_HOST:PORT. That works for HTTP and HTTPS sites alike. requests.auth.HTTPProxyAuth only adds a Proxy-Authorization header to plain HTTP requests, so it doesn't help with HTTPS, where the login has to go out with the CONNECT request. Keep the credentials in the URL, built from environment variables rather than written into code you commit.

A proxy set on session.proxies can lose to HTTP_PROXY and HTTPS_PROXY from the environment, because requests merges environment settings into each request. If a script ignores the proxy you set on the session, set session.trust_env = False or pass proxies= on every request.

To skip the proxy for some hosts, list them in NO_PROXY. To skip it for a whole session, use trust_env = False and set no proxies.

Credentials from the environment, session proxy, no proxypython
import os, requests
from urllib.parse import quote

user = os.environ["PROXY_USER"]
password = quote(os.environ["PROXY_PASS"], safe="")
PROXY = f"http://{user}:{password}@PROXY_HOST:PORT"

session = requests.Session()
session.trust_env = False   # ignore HTTP(S)_PROXY from the environment
session.proxies = {"http": PROXY, "https": PROXY}
print(session.get("https://api.ipify.org", timeout=15).text)  # proxy IP

# No proxy at all for this session:
direct = requests.Session()
direct.trust_env = False
print(direct.get("https://api.ipify.org", timeout=15).text)  # your own IP
Skip the proxy for some hostsbash
export HTTPS_PROXY="http://USERNAME:PASSWORD@PROXY_HOST:PORT"
export NO_PROXY="localhost,127.0.0.1,.internal.example.com"
python my_script.py   # these hosts skip the proxy

FAQ

Questions people ask

Why do I get “Missing dependencies for SOCKS support”?
Install the extra: pip install "requests[socks]". It adds PySocks, which requests uses for socks5 and socks5h URLs.
How do I check that requests really uses the proxy?
Request https://api.ipify.org through the proxy and compare the answer with your own IP.
Does httpx work the same way?
Yes, with httpx.Client(proxy=...) and, for SOCKS, the httpx[socks] extra.
How do I authenticate to a proxy in Python requests?
Put the username and password in the proxy URL: http://USERNAME:PASSWORD@PROXY_HOST:PORT, URL-encoding the password. HTTPProxyAuth doesn't work for HTTPS sites.
Why does requests ignore the proxy I set on the session?
HTTP_PROXY or HTTPS_PROXY in the environment can override session.proxies. Set session.trust_env = False, or pass proxies= on each request.
How do I make requests not use a proxy?
Use a session with trust_env = False and no proxies, or list the hosts in NO_PROXY.
How do I use a proxy with aiohttp?
For an HTTP proxy pass proxy="http://user:pass@host:port" to each request. For SOCKS5 install aiohttp-socks and create the session with ProxyConnector.from_url(...).
My password has special characters and requests fails. Why?
Characters like @, : and / break the proxy URL. URL-encode the password with urllib.parse.quote(password, safe="") before putting it in the URL.

Keep reading

Related guides

How to check that your proxy works and which IP it uses

Verify a proxy from a browser or the command line, check the exit IP, location and DNS, and fix the usual reasons a proxy shows your real IP.Read the guide →

HTTP vs SOCKS5 proxy: differences and when to use each

HTTP and SOCKS5 proxies compared: how they work, speed, security, DNS, authentication and app support, with a quick rule for choosing.Read the guide →

Rotating vs sticky proxies: which one do you need?

Rotating and sticky proxy sessions explained: how they differ, which tasks need each, session length, and mistakes that cause blocks.Read the guide →

Try it yourself

Activate a premium or IP-targeted proxy and use it in any browser or app, on Windows, Android or in your own code.