Skip to content

How to use a proxy with Python requests

Python requests takes a proxies dictionary on every call. This guide shows how to send requests through an authenticated residential proxy, choose between rotating and sticky IPs, target a country or city, use SOCKS5, and handle proxy errors properly.

Updated 9 November 2026

Prerequisites

  • Python 3.10 or newer (current requests 2.3x releases need it).
  • pip install requests, plus pip install "requests[socks]" if you want SOCKS5.
  • A proxy login from the dashboard under Logins. Below it appears as USER and PASS.

The examples use public test endpoints. Use proxies for work you are allowed to do: collecting public data, QA from other regions, ad and price monitoring.

Basic HTTP proxy

Map both the http and https keys to the same proxy URL. The key is the scheme of the target URL, not of the proxy, so the proxy URL itself stays http:// even for HTTPS sites. requests tunnels HTTPS through the proxy with CONNECT, so the TLS connection stays end to end between you and the site.

python
import requests

proxy = "http://USER:PASS@gw.hyperproxy.io:8888"
proxies = {"http": proxy, "https": proxy}

r = requests.get("https://api.ipify.org", proxies=proxies, timeout=30)
print(r.text)  # the exit IP

Authentication

Put the username and password in the proxy URL as USER:PASS@host:port. requests turns them into a Proxy-Authorization header. If the password has characters such as @, : or /, encode it with urllib.parse.quote(password, safe="") first.

You can also set HTTP_PROXY and HTTPS_PROXY environment variables; requests reads them by default. Be aware that environment variables take precedence over Session.proxies (but not over the proxies= argument on a call), which is a common source of confusion. Passing proxies= per request, as in this guide, avoids that.

Rotating vs sticky IPs

The gateway rotates per connection: every new connection gets a fresh exit. requests.get() opens a new connection each call, so it rotates. A requests.Session keeps connections alive, so requests to the same host may reuse one exit until the connection closes.

For logins, carts and paginated flows you want one IP on purpose. Add a session id to the username. Use letters and digits only; a slice of a UUID hex works well. Sessions last 5 minutes by default; set ttl up to 120 minutes.

import requests

proxy = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"
proxies = {"http": proxy, "https": proxy}

# requests.get() opens a new connection each call, so each call gets a new exit
for _ in range(3):
    print(requests.get("https://api.ipify.org", proxies=proxies, timeout=30).text)

Country and city targeting

Targeting is part of the username, as -key-value pairs. See Targeting for every option.

GoalUsername
Any US exitUSER-cc-us
New YorkUSER-cc-us-city-new_york
CaliforniaUSER-cc-us-region-california
A specific networkUSER-cc-de-asn-3320
Any exit in EuropeUSER-cont-eu
City, falling back to the countryUSER-cc-us-city-houston-strict-false

Build the username from parts so options are never repeated; a repeated or misspelled option fails with 407.

SOCKS5

The same port speaks SOCKS5. Install the socks extra (it pulls in PySocks) and use socks5h://, which resolves hostnames on the proxy side. With plain socks5:// your machine does the DNS lookup, which can leak lookups and pick an address that is wrong for the exit's region.

python
# pip install "requests[socks]"
import requests

proxy = "socks5h://USER-cc-de:PASS@gw.hyperproxy.io:8888"
proxies = {"http": proxy, "https": proxy}

print(requests.get("https://api.ipify.org", proxies=proxies, timeout=30).text)

Concurrency

requests is synchronous, so run it in a thread pool. Give each worker its own Session (sessions are not guaranteed to be thread-safe) and decide per task whether it needs a sticky IP. Keep the pool size reasonable and respect the target site's rate limits. For high concurrency, an async client is usually a better fit: see the httpx and aiohttp guides.

python
import uuid
from concurrent.futures import ThreadPoolExecutor
import requests

def fetch(url: str) -> str:
    # one sticky IP per task; drop "-session-..." for a fresh IP per request
    proxy = f"http://USER-cc-us-session-{uuid.uuid4().hex[:12]}:PASS@gw.hyperproxy.io:8888"
    with requests.Session() as s:
        r = s.get(url, proxies={"http": proxy, "https": proxy}, timeout=30)
        r.raise_for_status()
        return r.text

urls = [f"https://example.com/page/{i}" for i in range(50)]
with ThreadPoolExecutor(max_workers=10) as pool:
    for body in pool.map(fetch, urls):
        print(len(body))

Error handling and retries

For HTTPS targets the gateway answers the CONNECT request, so its status arrives as a requests.exceptions.ProxyError rather than as a response. For plain HTTP targets you get a normal response with that status code. The codes are listed in Errors:

StatusMeaningWhat to do
407Wrong credentials, invalid option, no balance or disabled loginFix and stop; do not retry
404No exit matches your targetingWiden targeting or add strict-false
403Target not allowedDo not retry
400Malformed requestCheck the proxy URL and scheme
429Too many requestsBack off, then retry
502 / 504The exit could not reach the target, or did not answer in timeRetry; a retry gets a new exit
python
import time
import requests

PROXY = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"
PROXIES = {"http": PROXY, "https": PROXY}
RETRYABLE = {429, 502, 504}

def get(url: str, attempts: int = 4) -> requests.Response:
    for attempt in range(attempts):
        try:
            r = requests.get(url, proxies=PROXIES, timeout=30)
        except requests.exceptions.ProxyError as e:
            # HTTPS targets: the gateway status arrives in the CONNECT reply,
            # e.g. "Tunnel connection failed: 407 Proxy Authentication Required"
            msg = str(e)
            if any(code in msg for code in ("407", "403", "404", "400")):
                raise  # fix credentials, options or targeting; retrying won't help
            error = e
        except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
            error = e
        else:
            if r.status_code not in RETRYABLE:
                return r
            error = requests.HTTPError(f"status {r.status_code}")
        time.sleep(2 ** attempt)  # without a session, each retry gets a new exit
    raise error

Always set a timeout. Without one, a stalled connection can block a worker indefinitely.

Verify the exit IP

Request https://api.ipify.org through the proxy, as in the first example; it returns the address the site sees. Use ?format=json for JSON. Run the rotating example and the IP should change each time; run the sticky example and it should stay the same.

Troubleshooting

  • ProxyError with 407: check the login in the dashboard, your balance, and that each targeting option is spelled right and used once.
  • The IP doesn't change: you are reusing a kept-alive connection through a Session, or your username has a session id.
  • The proxy seems ignored: you only set the http key, or an environment variable overrides Session.proxies.
  • "Missing dependencies for SOCKS support": install requests[socks].
  • 404 with city targeting: check the city spelling (lowercase, spaces as _) or add strict-false.

FAQ

Should the https key use an https:// proxy URL?

No. The dictionary key is the target scheme. The proxy URL is http:// for both keys; HTTPS traffic is still encrypted end to end inside the CONNECT tunnel.

How do I get a new IP for every request?

Leave out the session option and make sure each request uses a new connection, for example plain requests.get(). Every new connection gets a new exit.

How long does a sticky IP last?

5 minutes by default, up to 120 with ttl. If the exit goes offline, the session continues on a new IP. See Sessions.

Does this work with Scrapy or async code?

The same proxy URL works everywhere. See the Scrapy, httpx and aiohttp guides, and more snippets in Examples.

Try it on your own workload

Sign up with GitHub or Google, create a proxy login and send your first request in a minute.

More proxy integration guides

  • Python httpx — Sync and async httpx through a residential proxy with the proxy= argument and SOCKS5.
  • Python aiohttp — High-concurrency aiohttp requests through rotating or sticky residential IPs.
  • Scrapy — Route Scrapy spiders through residential proxies with request.meta and a middleware.
  • Playwright — Run Playwright through residential proxies, per browser or per context, with sticky sessions.
  • Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
  • Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
  • Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
  • Node.js fetch & undici — Use Node's built-in fetch with undici ProxyAgent or NODE_USE_ENV_PROXY.
  • Go net/http — Configure Go's http.Transport for HTTP and SOCKS5 residential proxies.
  • curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.