How to Use a Proxy with Python Requests (Auth, Sessions, Rotation, Errors)

Short answer: pass a proxies dictionary to requests.get() with the URL http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT} for both http and https. Always set a timeout, reuse a Session when requests belong together, and retry on 429, 502, 503 and 504 with backoff.

This guide covers the basics, authentication, sessions, rotation, retries and the errors you are most likely to see. It is part of our guide to proxies for web scraping.

Use proxies for public data only: market research, price monitoring, ad verification, SEO checks and QA. Respect each site’s terms and robots.txt.

Prerequisites

  • Python 3.8 or newer
  • The requests library: pip install requests
  • Proxy credentials from your dashboard: username, password, host and port. If these terms are new, read what a proxy host and port are.

Basic proxy request

import requests

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
proxies = {"http": PROXY_URL, "https": PROXY_URL}

resp = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=30)
print(resp.status_code)
print(resp.json())

The origin field in the response should show the proxy’s IP, not yours. Note that the proxy URL uses http:// even for HTTPS targets. That is normal: the connection to the proxy is plain HTTP, and requests then opens a tunnel (CONNECT) to the HTTPS site.

Not sure the proxy itself works? Run through how to test proxies first.

Special characters in the password

If your password contains characters such as @, : or /, the proxy URL breaks. URL-encode the credentials:

from urllib.parse import quote

user = quote("USERNAME", safe="")
password = quote("PASSWORD", safe="")
PROXY_URL = f"http://{user}:{password}@{{PROXY_HOST}}:{{PORT}}"

The doubled braces in the f-string keep the {PROXY_HOST} and {PORT} placeholders literal. In real code, replace them with your values and use single braces for your own variables.

Use a Session

A Session reuses connections and keeps cookies, which is what you want when several requests belong to one visit.

import requests

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"

session = requests.Session()
session.proxies.update({"http": PROXY_URL, "https": PROXY_URL})
session.headers.update({"User-Agent": "my-data-collector/1.0 (contact: you@example.com)"})

for url in ["https://httpbin.org/ip", "https://httpbin.org/headers"]:
    r = session.get(url, timeout=30)
    print(url, r.status_code)

Identifying your client honestly in the User-Agent, with a contact address, is good practice for public-data collection.

Environment variables

requests also reads standard proxy variables, so you can leave the code unchanged:

export HTTP_PROXY="http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
export HTTPS_PROXY="http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
python scraper.py

An explicit proxies= argument or session.proxies setting takes priority over these variables. To ignore the environment completely, set session.trust_env = False. The same variables work with curl, see using curl with a proxy server.

SOCKS proxies

For SOCKS, install the extra and use the socks5h scheme so DNS is resolved through the proxy:

pip install "requests[socks]"
PROXY_URL = "socks5h://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"
proxies = {"http": PROXY_URL, "https": PROXY_URL}

Use the host and port that your dashboard lists for SOCKS. They can differ from the HTTP ones.

Rotate between several proxies

Some plans give you one gateway that rotates IPs for you, so you can keep a single proxy URL. If you have a list of endpoints, rotate them yourself:

import itertools
import requests

PROXY_URLS = [
    "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}",
    "http://USERNAME:PASSWORD@{PROXY_HOST_2}:{PORT_2}",
]
pool = itertools.cycle(PROXY_URLS)

def get(url):
    proxy = next(pool)
    return requests.get(url, proxies={"http": proxy, "https": proxy}, timeout=30)

for page in range(1, 4):
    r = get(f"https://httpbin.org/anything?page={page}")
    print(page, r.status_code)

For stateful flows, keep one proxy per Session instead of changing it mid-visit. How rotating and sticky sessions work depends on the plan, so check your dashboard for the exact settings. For the trade-offs, see rotating vs static residential proxies.

Retry with backoff

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

PROXY_URL = "http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}"

retry = Retry(
    total=4,
    backoff_factor=1.0,
    status_forcelist=[429, 502, 503, 504],
    allowed_methods=["GET", "HEAD"],
    respect_retry_after_header=True,
)

session = requests.Session()
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
session.proxies.update({"http": PROXY_URL, "https": PROXY_URL})

r = session.get("https://httpbin.org/status/200", timeout=30)
print(r.status_code)

Do not retry a 407. It means the credentials are wrong, and retrying will not fix it.

Common errors and fixes

ErrorLikely causeFix
ProxyError: 407 Proxy Authentication RequiredWrong username or password, unencoded special characters, or IP not whitelistedCheck the credentials, URL-encode them, check the whitelist if your plan uses one
ProxyError ... Max retries exceededWrong host or port, or the proxy is unreachableVerify {PROXY_HOST} and {PORT}, test from the terminal
ConnectTimeout / ReadTimeoutSlow target or networkRaise the timeout, retry with backoff, lower concurrency
HTTP 429Too many requests to the targetAdd delays, reduce concurrency, honor Retry-After
SSLErrorInterception or outdated certificatesUpdate certifi and Python. Do not disable verification in production
InvalidSchema: Missing dependencies for SOCKS supportSOCKS extra not installedpip install "requests[socks]"

Next steps

Once a single request works, scale up slowly: add concurrency in small steps and watch your error rate. For the bigger picture, including choosing between residential, mobile and ISP proxies and estimating cost, read proxies for web scraping. For a full project, follow our Python web scraping tutorial.

Need proxies to test with? Compare residential proxies (billed per GB) and USA 4G/5G mobile proxies (billed per day, unlimited bandwidth), or see the pricing page. Every plan comes with a 24-hour money-back guarantee.

See residential plans

FAQ

How do I set a proxy in Python requests?

Pass a dictionary to the proxies argument, for example requests.get(url, proxies={"http": PROXY_URL, "https": PROXY_URL}, timeout=30). You can also set it once on a Session with session.proxies.update(...).

How do I use a proxy with a username and password in requests?

Put the credentials in the proxy URL: http://USERNAME:PASSWORD@{PROXY_HOST}:{PORT}. If the password contains special characters, URL-encode it with urllib.parse.quote.

Why do I get a 407 error with requests?

A 407 means the proxy rejected your credentials. Check the username and password, URL-encode special characters, and confirm that your IP is whitelisted if your plan uses IP authentication.

Why does requests use an http:// proxy URL for HTTPS sites?

The scheme describes how you talk to the proxy, not the target. requests connects to the proxy over HTTP and asks it to open a tunnel to the HTTPS site, so the traffic to the target stays encrypted.

How do I rotate proxies in requests?

Either use a rotating gateway from your provider, so one proxy URL gives you new IPs, or keep a list of proxy URLs and cycle through them. Use one proxy per Session when requests must share an IP.

Can I use SOCKS proxies with requests?

Yes. Install requests[socks] and use a socks5h:// proxy URL so that DNS lookups also go through the proxy.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.