The basic setup
requests sends traffic through a proxy when you pass a proxies dictionary. The keys are the schemes of the URLs you request, and the values are the proxy URL to use:
import requests
PROXY = "http://USERNAME:PASSWORD@HOST:823"
proxies = {"http": PROXY, "https": PROXY}
r = requests.get("https://api.ipify.org", proxies=proxies, timeout=30)
print(r.text) # the proxy's IP, not yoursThe proxy URL still starts with http:// even for HTTPS sites. For an HTTPS target, requests asks the proxy to open a tunnel with the CONNECT method, and your TLS connection runs end to end through it, so the proxy cannot read the page.
Always set a timeout. Without one, a stalled connection can hang your script indefinitely.
Authentication and special characters
Put the username and password in the URL. If either contains characters such as @, : or /, URL-encode them first, or requests will misread the URL:
from urllib.parse import quote
user = quote("USERNAME", safe="")
password = quote("p@ss:word", safe="")
PROXY = f"http://{user}:{password}@HOST:823"The alternative is IP allowlisting: add your server's public IPv4 address in the dashboard (up to five) and connect without credentials, using http://HOST:823. That keeps secrets out of your code and logs.
Use a Session for many requests
A Session reuses connections and keeps settings in one place:
import requests
session = requests.Session()
session.proxies.update({"http": PROXY, "https": PROXY})
session.headers.update({"User-Agent": "PriceMonitor/1.0 (+https://example.com/bot)"})
for url in ["https://example.com/a", "https://example.com/b"]:
r = session.get(url, timeout=30)
print(url, r.status_code)Reused connections matter with a rotating gateway: the IP changes per connection, so a kept-alive connection may send several requests from the same IP. If you need a new IP for every request, close the session between requests or send Connection: close.
Proxies from environment variables
requests also reads the standard HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables:
export HTTPS_PROXY="http://USERNAME:PASSWORD@HOST:823"
export HTTP_PROXY="$HTTPS_PROXY"
python script.pyA proxies argument passed in code takes priority. To make requests ignore the environment entirely, set session.trust_env = False.
SOCKS5 proxies
requests supports SOCKS through an optional extra:
pip install "requests[socks]"SOCKS = "socks5h://USERNAME:PASSWORD@HOST:824"
r = requests.get("https://api.ipify.org", proxies={"http": SOCKS, "https": SOCKS}, timeout=30)Use socks5h:// rather than socks5://. With the h, the proxy resolves hostnames, so your local DNS server never sees which sites you visit, and geo-targeted DNS answers match the proxy's location. See SOCKS5 proxies for when SOCKS5 is the better choice.
Rotating, sticky and country-targeted IPs
With a rotating gateway, rotation happens on the proxy side. Each new connection to the rotating port gets a different IP, so there is no list to manage in Python. Session and location options go in the username:
BASE = "HOST:823"
rotating = f"http://USERNAME:PASSWORD@{BASE}" # new IP per connection
german = f"http://USERNAME__cr.de:PASSWORD@{BASE}" # rotating German IPs
sticky = f"http://USERNAME__sessid.job42:PASSWORD@{BASE}" # one IP for about 30 minutes
sticky_de = f"http://USERNAME__cr.de;sessid.job42:PASSWORD@{BASE}" # bothUse sticky sessions for multi-step flows, such as a search followed by pagination, and rotating IPs for independent requests. Rotating proxies explains the trade-offs, and location targeting lists every parameter.
If your provider gives you individual static IPs instead, such as ISP proxies, keep them in a list and pick one per job.
Retries that respect rate limits
Network errors and rate limits happen. Mount an HTTPAdapter with a urllib3 Retry so requests retries automatically with backoff. Retry honours the Retry-After header on 429 and 503 responses by default:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=4,
backoff_factor=1, # waits 1 s, 2 s, 4 s ... between attempts
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET", "HEAD"],
)
session = requests.Session()
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
session.proxies.update({"http": PROXY, "https": PROXY})
r = session.get("https://example.com/products", timeout=30)A 429 Too Many Requests means the site wants you to slow down. Retrying through a new IP without slowing down is not a fix: lower your concurrency instead.
Concurrent requests
For many independent URLs, a thread pool keeps several requests in flight. Keep the number of workers per target site small:
from concurrent.futures import ThreadPoolExecutor
import requests
proxies = {"http": PROXY, "https": PROXY}
def fetch(url: str) -> tuple[str, int]:
r = requests.get(url, proxies=proxies, timeout=30)
return url, r.status_code
urls = [f"https://example.com/products?page={n}" for n in range(1, 21)]
with ThreadPoolExecutor(max_workers=4) as pool:
for url, status in pool.map(fetch, urls):
print(status, url)Each thread opens its own connection, so with a rotating gateway each one exits from a different IP.
Common errors and fixes
| Error | Likely cause | Fix |
|---|---|---|
407 Proxy Authentication Required | Wrong credentials, or special characters not encoded | Check the username and password; URL-encode them; or use IP allowlisting |
ProxyError: Cannot connect to proxy | Wrong host or port, or a firewall blocking outbound traffic | Check the host and port in your dashboard; allow outbound connections to the gateway |
ConnectTimeout / ReadTimeout | Slow route or target, common for distant countries | Raise the timeout; retry with backoff |
SSLError | An HTTPS-intercepting proxy or an outdated CA bundle | Update certifi; do not disable verification on production code |
InvalidSchema: Missing dependencies for SOCKS support | The SOCKS extra is not installed | pip install "requests[socks]" |
| Requests ignore the proxy | Only the http key is set, or NO_PROXY matches the host | Set both http and https; check NO_PROXY |
The same thing with httpx
If you use httpx, pass the proxy to the client:
import httpx
with httpx.Client(proxy=PROXY, timeout=30) as client:
print(client.get("https://api.ipify.org").text)Next steps
- Proxies for web scraping: choosing a proxy type, sizing traffic and a full example with backoff.
- Is web scraping legal?: what you may and may not collect.
- Getting started: your connection details and first request in curl, Python and Node.js.
Use proxies only for public data and within each site's terms and robots.txt. FuseProxy's acceptable use policy lists what is not allowed.