Back to blog. Article language: BN EN ES FR HI ID PT RU UR VI ZH

Python requests proxy: HTTP, SOCKS5 and rotating proxies

A Python requests proxy is set with the proxies argument: a dict whose http and https keys point to your server URL. SOCKS5 needs one optional package. To confirm the setup, call httpbin.org/ip through that gateway and compare the result with your real IP.

import requests

url = "http://USER:[email protected]:8080"
r = requests.get("https://httpbin.org/ip", proxies={"http": url, "https": url}, timeout=10)

How proxies work in Python requests

The proxies dictionary maps a target URL scheme to the server that carries its traffic.

proxies = {
   "http": "http://proxy.example.com:8080",   # http:// sites
   "https": "http://proxy.example.com:8080",  # https:// sites
}

  • ❌ The keys name the scheme of the site you call, not the protocol of the gateway. Most broken Python request proxy setups skip the https key, so HTTPS traffic goes direct.

A requests proxy URL itself can start with http://, https:// or socks5://.

How to set a proxy for a single request

Pass proxies= to get(), post() or any other method; it applies to that call only. This is the simplest Python requests use proxy pattern.

r = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=10)

  • 💡 Always set a timeout: without it, a dead endpoint can hang the script.

How to use a proxy with requests.Session

A requests Session proxy setting covers every call made through that session and reuses connections.

s = requests.Session()
s.proxies.update(proxies)
s.get("https://httpbin.org/ip", timeout=10)

Environment variables override session.proxies while trust_env is True, the default. Set it to False to rely on your code alone.

Where you can set a proxy and when to use each:

MethodScopeWhen to use
Per-call argumentOne callTests, one-offs
requests.SessionAll session callsCrawlers, API clients
Env variablesWhole processContainers, CI

Proxy authentication in Python requests

Python requests proxy authentication goes inside the server URL as user:pass@. Encode special characters with urllib.parse.quote so @ or : can't break the URL.

import os
from urllib.parse import quote

user = os.environ["PROXY_USER"]
pwd = quote(os.environ["PROXY_PASS"], safe="")
url = f"http://{user}:{pwd}@proxy.example.com:8080"

  • ❌ Never hardcode credentials or commit them to a repo: load them from environment variables or a secrets manager.

How to use a SOCKS5 proxy with Python requests

A Python requests SOCKS5 proxy uses the same dict after one install.

# pip install "requests[socks]"
url = "socks5h://USER:[email protected]:1080"
proxies = {"http": url, "https": url}

The requests[socks] extra pulls in the SOCKS backend.

Without PySocks, the library raises InvalidSchema.

Where each scheme resolves DNS:

SchemeWhere DNS is resolvedWhen to use
socks5Your machineInternal hosts
socks5hRemote serverGeo tests, default
  • 💡 With the h scheme, a Python requests SOCKS5 proxy keeps DNS and exit IP in one location.

How to set or disable proxies with environment variables

Set HTTPS_PROXY and HTTP_PROXY to route a script through a gateway without code changes.

export HTTP_PROXY="http://proxy.example.com:8080"
export HTTPS_PROXY="$HTTP_PROXY"
export NO_PROXY="localhost,127.0.0.1,.internal"

s.trust_env = False  # ignore env settings

For Python requests no proxy cases, list hosts in NO_PROXY or switch off env lookup per session.

How to rotate proxies in Python requests

A Python requests rotating proxy setup either cycles through a pool in code or uses a provider's rotating port that swaps IPs for you. New to scraping? Start with our Python web scraping tutorial, and for large crawls see our Scrapy proxy setup guide.

A Python requests proxy example with retries:

import itertools, time, requests

pool = itertools.cycle([
   "http://USER:[email protected]:8001",
   "http://USER:[email protected]:8002",
])

def fetch(url, tries=3):
   for _ in range(tries):
       p = next(pool)
       try:
           return requests.get(url, proxies={"http": p, "https": p}, timeout=10)
       except requests.RequestException:
           time.sleep(2)
   raise RuntimeError("all endpoints failed")

Two ways to handle proxy rotation: Python pool or provider's rotating port.

ApproachProsCons
Pool in codeFull controlYou track dead IPs
Rotating portOne endpoint, no upkeepLess control per call
  • 💡 Add pauses and rate limits, follow robots.txt and site ToS, and stick to lawful tasks: price monitoring, QA, public data.

How to check that requests go through the proxy

Compare the IP a site sees with and without the gateway.

  1. Call httpbin.org/ip directly and note the origin IP.
  2. Repeat the Python requests with proxy call.
  3. Check the country of the new IP.

print(s.get("https://httpbin.org/ip", timeout=10).json())

If both IPs match, the requests proxy settings were not applied.

What a working setup shows:

What to checkExpected result
origin fieldGateway IP, not yours
CountryThe location you chose
Response timeStable, within your limit

Practice case: an analyst tracks a retailer's public prices in New York, Texas and California, one residential IP per state, hourly with pauses.

Common Python requests proxy errors and fixes

Most failures surface as one of these exceptions:

ErrorCauseFix
❌ ProxyErrorServer unreachableCheck host, port, status
❌ 407 Proxy Authentication RequiredBad credentialsCheck login, encode password
❌ SSLError (CERTIFICATE_VERIFY_FAILED)Unknown CAverify="ca.pem", never False in production
❌ ConnectTimeout / ReadTimeoutSlow or dead endpointRetry with another IP
❌ InvalidSchema: Missing dependencies for SOCKS supportSocks extra missingInstall it with pip

💡 Set time limits, keep credentials in the environment and log which IP served each call.

Which proxy type fits your Python project

Residential suits geo data, static ISP suits long sessions, mobile suits mobile pages. Need a real browser rather than an HTTP client? Use our Selenium proxy setup or Playwright proxy guide.

Typical tasks and the proxy type for each:

TaskTypeWhy
Price monitoringResidentialReal ISP IPs per state
API tests by countryResidentialWide geo coverage
Long sessionsStatic ISPSame IP for hours
Mobile resultsMobileCarrier IPs

Try insocks residential proxies, SOCKS5 plans or mobile proxies: start with a demo, then sign up for full access.

Key takeaways

  • ✅ Dict keys match the target scheme, not the server type.
  • ✅ Use a Session for repeated calls; turn off env lookup when needed.
  • ✅ Install the socks extra and prefer the h scheme.
  • ✅ Keep credentials in env variables; always set time limits.

Frequently asked questions

How do I use a proxy with Python requests?

Pass proxies={"http": url, "https": url} to the call.

How do I use a SOCKS5 proxy with requests?

Install the socks extra, then point both keys to a SOCKS5 URL with the h scheme.

How do I add proxy authentication in requests?

Put user:pass@ before the host in the server URL and URL-encode special characters.

How do I rotate proxies in Python requests?

Cycle through a pool of URLs with itertools.cycle or use a provider's rotating endpoint.

How do I disable the proxy for requests?

List hosts in NO_PROXY or turn off environment lookup on a Session.

Why does requests raise ProxyError?

The gateway could not be reached or refused the connection; check host, port and credentials.

2026-12-01