Skip to content
Proxies
ISP Proxies (Static Residential)
from $4.69
Rotating Residential Proxies
from $2.42
Rotating Datacenter Proxies
from $1.21
Rotating Mobile Proxies
from $4.84
Locations
Europe
Asia
Middle East
Africa
North America
South America
Oceania
Learn

How to use a proxy with Python requests

Last updated

Short answer

To use a proxy with Python requests, pass a proxies dictionary that maps the http and https schemes to your proxy URL, including the username and password. For SOCKS5, install requests[socks] and use a socks5h URL. Use a Session to reuse connections, set timeouts on every request, and add retries that honour Retry-After.

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 yours

The 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.py

A 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}"  # both

Use 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

ErrorLikely causeFix
407 Proxy Authentication RequiredWrong credentials, or special characters not encodedCheck the username and password; URL-encode them; or use IP allowlisting
ProxyError: Cannot connect to proxyWrong host or port, or a firewall blocking outbound trafficCheck the host and port in your dashboard; allow outbound connections to the gateway
ConnectTimeout / ReadTimeoutSlow route or target, common for distant countriesRaise the timeout; retry with backoff
SSLErrorAn HTTPS-intercepting proxy or an outdated CA bundleUpdate certifi; do not disable verification on production code
InvalidSchema: Missing dependencies for SOCKS supportThe SOCKS extra is not installedpip install "requests[socks]"
Requests ignore the proxyOnly the http key is set, or NO_PROXY matches the hostSet 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

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.

FAQ

Questions, answered

How do I use a proxy with Python requests?
Pass a dictionary to the proxies argument: `requests.get(url, proxies={"http": PROXY, "https": PROXY})`, where PROXY is a URL such as `http://USERNAME:PASSWORD@HOST:PORT`. The keys are the schemes of the sites you request; the value is the proxy to use for each.
Why do I need both http and https keys?
requests picks the proxy by the scheme of the target URL. If you only set `http`, requests to `https://` sites bypass the proxy. Set both keys, usually to the same proxy URL.
How do I use a SOCKS5 proxy with requests?
Install the extra with `pip install "requests[socks]"`, then use a URL starting with `socks5h://`. The `h` makes the proxy resolve hostnames, so DNS lookups do not leak from your machine.
What does a 407 error mean?
407 Proxy Authentication Required means the proxy rejected your credentials. Check the username and password, URL-encode special characters in them, or use IP allowlisting instead.
How do I rotate proxies in Python requests?
With a rotating gateway you do not rotate anything in code: every new connection exits from a different IP. To keep one IP for a while, add a session parameter to the username. You only need a list of proxies if your provider gives you individual static IPs.

Start with the proxies you need

Create an account, top up and connect in minutes. Every price is on the pricing page.