DEV Community

Cover image for Python Requests Proxy Setup: HTTP, HTTPS & SOCKS5 Guide
Arpita Raval
Arpita Raval

Posted on Edited on

Python Requests Proxy Setup: HTTP, HTTPS & SOCKS5 Guide

Sooner or later, every Python developer who calls external websites at scale hits the same wall: rate limits, geo-restricted content, or an IP that has been flagged. Proxies are the standard answer, and Python’s requests library makes them easy to use once you understand a few details that trip people up.

In this guide, you’ll learn how to:

  • Configure HTTP, HTTPS, and SOCKS5 proxies in requests
  • Authenticate with a username and password (and handle special characters)
  • Use sessions, environment variables, timeouts, and retries
  • Rotate proxies and handle the errors you’ll actually see in production.

All examples use placeholder addresses from the documentation range (203.0.113.x). Swap in your own proxy details.

Prerequisites

You need Python 3.8+ and requests. SOCKS support is an optional extra that installs PySocks:

pip install "requests[socks]"
Enter fullscreen mode Exit fullscreen mode

1. The basics: the proxies dictionary

The core of proxy support in requests is a dictionary that maps a target URL scheme to a proxy URL:

import requests

proxies = {
    'http': 'http://203.0.113.10:8080',
    'https': 'http://203.0.113.10:8080',
}

response = requests.get(
    'https://api.ipify.org?format=json',
    proxies=proxies,
    timeout=10,
)
print(response.json())  # should show the proxy’s IP, not yours
Enter fullscreen mode Exit fullscreen mode

This is the number one source of confusion, so it’s worth being precise:

  • The dictionary key (http or https) is the scheme of the website you are requesting.
  • The value is the proxy address, and its scheme describes how you talk to the proxy.

That’s why the https key above still points to an http:// proxy URL. For HTTPS targets, requests asks the proxy to open a tunnel with the CONNECT method, and the TLS session runs end to end between you and the target site. The proxy can’t read your encrypted traffic.

Always run a quick sanity check like the one above (an IP-echo endpoint) before building anything on top of a new proxy.

2. Proxy authentication

Most paid proxies require credentials. Put them in the proxy URL:

PROXY = 'http://username:password@203.0.113.10:8080'

proxies = {'http': PROXY, 'https': PROXY}
response = requests.get('https://api.ipify.org', proxies=proxies, timeout=10)
Enter fullscreen mode Exit fullscreen mode

If your password contains characters like @, :, or /, the URL will break. Percent-encode the credentials first:

from urllib.parse import quote

user = quote('my.user', safe='')
password = quote('p@ss:word/123', safe='')

PROXY = f'http://{user}:{password}@203.0.113.10:8080'
Enter fullscreen mode Exit fullscreen mode

Some providers also support IP whitelisting, where you authorize your server’s IP in a dashboard and then connect with no credentials. That’s simpler and keeps passwords out of your code, but only works when your outbound IP is stable.

3. Use a Session

If you make more than one request, set the proxy on a Session. You get connection reuse, cookies, and a single place to configure everything:

import requests

session = requests.Session()
session.proxies.update({
    'http': PROXY,
    'https': PROXY,
})
session.headers.update({'User-Agent': 'my-app/1.0 (+https://example.com/contact)'})

for page in range(1, 4):
    r = session.get(f'https://example.com/items?page={page}', timeout=15)
    print(page, r.status_code)
Enter fullscreen mode Exit fullscreen mode

4. Environment variables

The requests library reads the standard proxy environment variables automatically:

export HTTP_PROXY='http://username:password@203.0.113.10:8080'
export HTTPS_PROXY='http://username:password@203.0.113.10:8080'
export NO_PROXY='localhost,127.0.0.1,.internal.example.com'
Enter fullscreen mode Exit fullscreen mode

This is handy for containers and CI, because you can change proxies without touching code. Two things to remember:

  • An explicit proxies= argument overrides environment settings for that request.
  • If env variables are causing surprises, disable them with session.trust_env = False.

5. SOCKS5 proxies

With requests[socks] installed, SOCKS5 is just a different URL scheme:

SOCKS = 'socks5h://username:password@203.0.113.20:1080'

proxies = {'http': SOCKS, 'https': SOCKS}
response = requests.get('https://api.ipify.org', proxies=proxies, timeout=10)
Enter fullscreen mode Exit fullscreen mode

Notice socks5h rather than socks5. The difference matters:

Scheme Who resolves the domain name?
socks5:// Your machine (DNS lookup happens locally)
socks5h:// The proxy (DNS lookup happens remotely)

Use socks5h:// by default. With plain socks5://, your local resolver still sees every hostname you visit, which defeats part of the purpose and can leak your real location.

HTTP vs SOCKS5 in practice: For ordinary web requests with requests, both work well. HTTP/HTTPS proxies are more widely supported by tools and give clearer error messages. SOCKS5 is protocol-agnostic and handy when you also need non-HTTP traffic from the same proxy.

6. Timeouts and retries

Proxies add a network hop, and free or overloaded ones can hang indefinitely. Never make a proxied request without a timeout. Use a tuple to set connect and read timeouts separately:

response = session.get(url, timeout=(5, 20))  # 5s to connect, 20s to read
Enter fullscreen mode Exit fullscreen mode

For transient failures, mount a retry policy on the session:

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

def build_session(proxy_url: str) -> requests.Session:
    session = requests.Session()
    session.proxies.update({'http': proxy_url, 'https': proxy_url})

    retry = Retry(
        total=3,
        backoff_factor=1,  # waits 1s, 2s, 4s between attempts
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=['GET', 'HEAD'],  # only retry idempotent requests
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session
Enter fullscreen mode Exit fullscreen mode

Retrying only GET and HEAD is deliberate. Unthinkingly retrying POST requests can create duplicate orders, comments, or form submissions.

7. Rotating proxies

There are two ways to rotate IPs.

Client-side rotation

You hold a list of proxies and pick one per request. If one fails, you move to the next:

import random
import requests
from requests.exceptions import ProxyError, ConnectTimeout, ReadTimeout

PROXY_POOL = [
    'http://user:pass@203.0.113.10:8080',
    'http://user:pass@203.0.113.11:8080',
    'http://user:pass@203.0.113.12:8080',
]

def fetch(url: str, attempts: int = 3) -> requests.Response:
    last_error = None
    candidates = random.sample(PROXY_POOL, k=min(attempts, len(PROXY_POOL)))

    for proxy in candidates:
        try:
            return requests.get(
                url,
                proxies={'http': proxy, 'https': proxy},
                timeout=(5, 15),
            )
        except (ProxyError, ConnectTimeout, ReadTimeout) as exc:
            last_error = exc  # try the next proxy

    raise RuntimeError(f'All proxy attempts failed for {url}') from last_error

print(fetch('https://api.ipify.org?format=json').json())
Enter fullscreen mode Exit fullscreen mode

This gives you full control and works well with static proxies (such as dedicated IPv4 or ISP addresses) where each IP is a separate entry.

Provider-side rotation

Many residential and mobile proxy services expose a single gateway endpoint and rotate the exit IP for you, either on every request, on a timer, or never within a “sticky” session. From your code, it looks like one proxy:

GATEWAY = 'http://user:pass@gateway.example.com:8000'
proxies = {'http': GATEWAY, 'https': GATEWAY}

for _ in range(3):
    print(requests.get('https://api.ipify.org', proxies=proxies, timeout=15).text)
Enter fullscreen mode Exit fullscreen mode

If rotation is per request, you’ll see a different IP each time. How you request a sticky session (a parameter in the username, a different port, etc.) is provider-specific, so check your provider’s documentation.

Rule of thumb: Use sticky sessions for anything that involves logins, carts, or multi-step flows, and per-request rotation for independent page fetches.

8. Errors you’ll actually see

Symptom Likely cause What to do
ProxyError / Max retries exceeded Proxy is down, wrong host or port, or tunnel refused Verify address, test with curl -x, rotate to another proxy
ConnectTimeout Proxy unreachable or overloaded Lower connect timeout, fail over
ReadTimeout Target is slow or the proxy is throttling Raise read timeout moderately, retry with backoff
HTTP 407 Proxy authentication failed Check credentials, URL-encoding, or whitelisted IP
HTTP 403 Target blocked the IP or the request looks automated Check headers, slow down, try a different IP type
HTTP 429 Rate limit Back off, reduce concurrency, spread requests over more IPs
SSLError Often a misconfigured scheme or a MITM proxy Re-check URL schemes; do not blanket-disable verification

A quick way to isolate whether the problem is your Python code or the proxy itself is to test outside Python:

curl -x http://user:pass@203.0.113.10:8080 https://api.ipify.org
Enter fullscreen mode Exit fullscreen mode

If curl fails too, the issue is the proxy or credentials, not your script.

9. A note on httpx

If you prefer httpx (especially for async code), the idea is the same, but recent versions take a single proxy argument instead of a dictionary:

import httpx

with httpx.Client(proxy='http://user:pass@203.0.113.10:8080', timeout=15) as client:
    print(client.get('https://api.ipify.org').text)
Enter fullscreen mode Exit fullscreen mode

For SOCKS support, install httpx[socks]. Older httpx releases used a proxies= argument, so check the version you have installed.

10. Pitfalls checklist

  • Always set a timeout. requests has none by default and will wait forever.
  • Don’t hard-code credentials. Read them from environment variables or a secrets manager.
  • Don’t set verify=False to “fix” SSL errors. It turns off certificate validation and hides real problems.
  • Prefer socks5h:// so DNS resolves through the proxy.
  • Match the proxy type to the job. Datacenter IPs are fast and cheap, residential and ISP IPs look more like real users, and mobile IPs carry the highest trust but cost more.
  • Be a good citizen. Respect robots.txt and the target’s terms of service, rate-limit your requests, and only collect data you’re allowed to collect.

Wrapping up

Here’s the short version:

  1. Keys in proxies are the target scheme; values are the proxy URL.
  2. Encode special characters in credentials, or allow your IP instead.
  3. Use a Session, always set timeouts, and retry only idempotent requests.
  4. Use socks5h:// for SOCKS5 so DNS isn’t resolved locally.
  5. Rotate on the client or let the provider’s gateway do it, and use sticky sessions for stateful flows.

Have a proxy edge case that isn’t covered here? Drop it in the comments, and I’ll add it to the guide.

Top comments (3)

Collapse
 
taj_shai_694f78c2277b923d profile image
BoltGrab •

Helpful breakdown! One small gotcha worth keeping in mind with SOCKS5 in Python Requests is socks5:// vs socks5h://—using socks5h:// ensures DNS resolution happens on the proxy side rather than leaking local DNS queries.

Collapse
 
arpitaraval profile image
Arpita Raval •

Thanks, glad it helped! 🙌 You're right about socks5h://, and it's the one I'd flag first for SOCKS5. That's why the guide uses it in the example and lists it in the pitfalls checklist. With plain socks5://, the local resolver still sees every hostname you visit, which can leak your location and partly defeats the point of using a proxy. Appreciate you calling it out for anyone skimming. 🙂

Collapse
 
arpitaraval profile image
Arpita Raval •

The point that the proxies dict key is the target scheme while the value describes how you talk to the proxy is the thing that trips up most people, and you explained it clearly.

The socks5:// vs socks5h:// table was also useful. I've seen DNS leaks from that exact mistake, and socks5h is rarely the default in tutorials.

One thing I'd add: when you rotate client-side, it helps to drop a failing proxy from the pool for a short cooldown instead of picking it again at random. That saves a lot of wasted timeouts on large crawls.