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]"
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
This is the number one source of confusion, so it’s worth being precise:
- The dictionary key (
httporhttps) 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)
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'
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)
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'
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)
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
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
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())
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)
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
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)
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.
requestshas 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=Falseto “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.txtand 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:
- Keys in
proxiesare the target scheme; values are the proxy URL. - Encode special characters in credentials, or allow your IP instead.
- Use a
Session, always set timeouts, and retry only idempotent requests. - Use
socks5h://for SOCKS5 so DNS isn’t resolved locally. - 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 (15)
Good breakdown, especially the sections on proxy rotation, retries and error handling.
One thing that becomes challenging at scale is not just configuring proxies but maintaining their reliability and managing the associated costs. A setup that works well for a few hundred requests can become quite difficult to maintain when you're processing thousands of requests regularly.
We encountered similar challenges while working with search engine data, which was one of the reasons we started building OrbitScraper.
I'm curious how other developers approach this. Do you prefer maintaining your own proxy infrastructure or using managed APIs when the request volume increases?
Thanks, glad the rotation, retries and error-handling sections were useful.
You're right that configuring a proxy is the easy part. At a few hundred requests, almost any setup works. At thousands a day, the work shifts to keeping the pool healthy (dead IPs, bans, uneven success rates) and keeping the cost per successful request under control. That's why I stressed retries and backoff in the guide, but they only treat the symptoms once the pool itself degrades.
On your question, I don't think it's an either/or. My rule of thumb:
Many teams end up with a hybrid: a managed layer for the difficult targets and their own proxies for everything else.
Search engine data is a good example of where the maintenance burden gets heavy, so I'm curious how OrbitScraper handles it. What request volume does it start making sense at, in your experience?
Thanks, Arpita. I agree with your point about the hybrid approach. Not every scraping use case necessarily requires a managed API.
With OrbitScraper, we're specifically focusing on search engine data, where maintaining proxies, handling CAPTCHAs, retries and blocked requests can quickly become a separate engineering task.
We handle those complexities on our side and provide structured search results through a credit-based API.
Regarding request volume, I don't think there's a fixed threshold. Even at a few hundred requests, a managed API can make sense if the target is difficult to scrape. At thousands of requests per day, infrastructure maintenance, engineering time and cost per successful request become much more important.
Our goal is to make search data collection practical and affordable for both independent developers and teams operating at scale.
I really like your point about measuring the cost per successful request rather than just the cost of proxies. That's an important distinction.
Thanks, that's a fair point. The threshold depends more on how hard the target is than on raw volume, and I'd rather judge it by cost per successful request than by the sticker price of proxies or API credits.
One thing I'd still check before choosing a managed API, especially for search data, is how it bills failures. Some charge per request regardless of outcome, others only charge for successful responses, and that changes the real cost a lot. Credit-based pricing is also easy to compare against a DIY setup if you track success rate, retries and engineering hours side by side.
Appreciate you sharing how OrbitScraper approaches it. Handling CAPTCHAs and blocks for search results is the kind of work most people underestimate until they're maintaining it.
Absolutely, Arpita. That's actually one of the things we considered when designing OrbitScraper's pricing model.
We only charge credits for successful search requests. Failed requests, internal retries and status checks don't consume credits.
I agree that comparing API pricing with a DIY setup should account for success rates, infrastructure maintenance and engineering time rather than just the advertised price per request.
Really appreciate the discussion and your perspective on this.
The
socks5h://vssocks5://DNS distinction is something a lot of people miss, and it's a quiet way to leak your real location. I also liked the point about retrying onlyGET/HEAD, since blindly retrying POST can cause duplicate submissions. Thecurl -xtrick for isolating proxy issues from Python issues is a handy debugging tip too. Bookmarking this as a reference. 🔖Thanks so much! 🙌 Glad those three points were useful. The
socks5h://one catches a lot of people out, because everything still works with plainsocks5://and the DNS leak only shows up when you check for it.The
GET/HEADretry rule matters most in production. A retriedPOSTthat creates a duplicate order is much harder to clean up than a failed request.If you run into a proxy edge case while using the guide, drop it here and I'll add it to the post. 🐍
That's a good point about
socks5://failing silently. Everything works, so there's nothing to tell you the DNS lookups are leaking.I'll run an IP-echo check and a DNS leak test the next time I set up a new proxy. One edge case I'm curious about is
socks5h://combined with provider-side sticky sessions. Does the session parameter go in the username the same way as with HTTP proxies, or does it vary by provider? It might be worth a short note in the guide.Looking forward to any updates! 🚀
Exactly, that's what makes it nasty: the request succeeds, so nothing tells you DNS is leaking. An IP-echo check plus a DNS leak test is a solid habit for any new proxy.
On
socks5h://with sticky sessions: the session parameter usually goes in the username the same way as with HTTP proxies.socks5honly changes where DNS gets resolved (on the proxy side). Authentication is still username and password, so the credential format doesn't change with the protocol.What does vary by provider:
Format: Some use
user-session-abc123, othersuser_session-abc123oruser-sessid-abc123.Endpoint: Some providers use a different port or hostname for SOCKS5 than for HTTP.
Session TTL: How long "sticky" actually lasts depends on the provider.
Here's a quick example:
Check your provider's docs for the exact syntax. You'll also need
pip install requests[socks]for SOCKS support.A short note on this in the guide is a good idea, and I'll add one. Thanks for the suggestion! 🚀
Clear guide, and the explanation of the
proxiesdict keys (target scheme vs. proxy URL) is the part most tutorials get wrong. Thesocks5h://DNS table is a nice touch too.One edge case you could add to the environment variables section: when
HTTP_PROXY/HTTPS_PROXYare set, they can silently overridesession.proxies. Proxies passed per request win over the environment, but proxies set on the Session don't. So if a container hasHTTPS_PROXYexported, a Session configured with a different proxy can still route through the env one. It's a long-standing requests quirk (worth a quick check on your installed version). Passingproxies=on each call, or settingsession.trust_env = False, avoids it. A one-line IP-echo check inside the actual Session catches it fast.Two smaller things that might be worth a mention:
all://as a key (e.g.{'all://': proxy}) is supported by httpx mounts, but plainrequestsonly matcheshttp/https, which trips people up when moving between the two.ProxyErrorfailures are retried by urllib3 before your own failover logic runs. In a rotation setup you may wanttotal=0on the adapter and handle failover yourself, so one dead proxy doesn't eat three attempts.Thanks, glad the proxies dict explanation and the socks5h:// DNS table helped.
The env var point is a good catch.
requestsmerges environment proxies into the request-level settings before it mergessession.proxies, so withtrust_envon, an exportedHTTPS_PROXYcan beat what you set on the Session. This bites a lot in containers and CI. I'll add a short note to the environment variables section with the two fixes you mentioned (proxies=per call, orsession.trust_env = False) and an IP-echo check run through the actual Session.The
all://difference is also worth a mention. Inrequeststhe catch-all key is plainall, andall://as a bare key won't match. That's different from httpx mounts, which is where people get tripped up when switching libraries.On retries, agreed. In a rotation setup,
total=0on the adapter and your own failover logic is cleaner, since otherwise urllib3 retries a dead proxy before your code ever sees the failure. I'll add that to the retry section.Thanks for the detailed feedback!
The
proxiesdictionary explanation is the part most guides get wrong. Calling out that the key is the target scheme and the value is how you talk to the proxy clears up why anhttpskey can point to anhttp://proxy URL. I also liked thesocks5vssocks5htable, since DNS leaks are easy to miss.One question: For client-side rotation, have you tested how
random.samplebehaves once some proxies in the pool go bad? I'm wondering if you'd track failures and drop dead proxies for a cooldown period instead of picking them again on the next request.Thanks, glad the proxies dictionary and the
socks5htable were useful. Those were the two things I most wanted to get right.Good question.
random.samplein the guide is stateless: it pickskdistinct proxies for that one call, so within a singlefetch()you never retry the same dead proxy. But nothing carries over between calls, so a bad proxy can be picked again on the very next request. I kept the example simple, but you're right that it isn't enough for a real pool.What I'd do is track consecutive failures per proxy and bench a proxy for a cooldown once it crosses a threshold, then let it back in and see if it recovers. Something like:
Then
fetch()samples fromhealthy()instead of the full pool. One thing to watch is the failure type.ProxyErrorandConnectTimeoutpoint at the proxy, but a 403 or 429 usually means the target is blocking you, so I wouldn't bench the proxy for those. In production I'd also add a little jitter to the cooldown so the whole pool doesn't come back at once, and a lock if you're using threads.I'll add a section on this to the guide. Thanks for the suggestion!
Helpful breakdown! One small gotcha worth keeping in mind with SOCKS5 in Python Requests is
socks5://vssocks5h://—usingsocks5h://ensures DNS resolution happens on the proxy side rather than leaking local DNS queries.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 plainsocks5://, 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. 🙂