How to Use a Proxy with Python Requests, Step by Step
A practical walk-through of configuring a proxy in Python Requests, from a single call to a reusable session, plus how to verify it works and debug common errors.
9 min readUpdated Nov 13, 2026By XPASS Editorial Team

Python's requests library is the usual choice for small scripts that fetch pages, call APIs or check how a public site responds. Adding a proxy takes only a few lines, but a handful of details decide whether the setup is reliable: which dictionary keys to use, where to put credentials, how to avoid a hung script, and how to confirm that traffic is truly leaving through the proxy. This guide goes step by step, from a single request to a reusable session, and ends with a short troubleshooting table.
Everything here assumes lawful use. Use proxies for work such as website testing, regional page checks and QA, respect the terms of the sites you contact, honour their robots rules, and follow local regulations. A proxy is a routing tool, not permission to ignore a site's rules.
What you need before you start
You need Python 3 with the requests package installed, and the connection details from your proxy provider. Those details usually consist of a host name or IP address, a port, the protocol type (HTTP or SOCKS), and, for most commercial services, a username and password. The plan page and the account dashboard should list them; if something is unclear, check the provider's documentation rather than guessing.
Decide in advance where the credentials will live. Putting them straight into the script is fine for a thirty-second experiment but a poor habit for anything you save. The guide on storing proxy credentials securely covers environment variables and secret managers, and we will use environment variables in the examples below.
It also helps to know whether you are working with a rotating endpoint or a fixed address, because that affects how you test. A fixed address should show the same public IP on every call; a rotating one may change. Your provider's documentation explains which behaviour to expect.

Step 1: a single request through a proxy
The simplest form passes a proxies dictionary to one call.
import requests
proxies = {
"http": "http://USER:PASS@proxy.example.net:8080",
"https": "http://USER:PASS@proxy.example.net:8080",
}
response = requests.get("https://example.com/", proxies=proxies, timeout=15)
print(response.status_code)
The keys describe the scheme of the site you are visiting. The values describe how to reach the proxy. That is why the https key often contains an http:// address: your script speaks plain HTTP to the proxy and asks it to open a tunnel to the HTTPS site, as explained in the MDN article on proxy servers and tunneling. Only change the scheme in the value if your provider tells you the proxy itself expects TLS.
Notice the timeout argument. By default requests waits indefinitely, so a dead proxy can freeze a script. Always set a timeout.
Step 2: keep the credentials out of the code
Replace the literal values with environment variables.
import os
import requests
host = os.environ["PROXY_HOST"]
port = os.environ["PROXY_PORT"]
user = os.environ["PROXY_USER"]
password = os.environ["PROXY_PASS"]
proxy_url = f"http://{user}:{password}@{host}:{port}"
proxies = {"http": proxy_url, "https": proxy_url}
If a password contains characters such as @, :, / or #, the URL becomes ambiguous and the request fails with a confusing error. Encode them first.
from urllib.parse import quote
user = quote(os.environ["PROXY_USER"], safe="")
password = quote(os.environ["PROXY_PASS"], safe="")
Avoid printing proxy_url in logs or error messages, because it contains the password. If you need to log which proxy was used, log only the host and port.
Step 3: use a Session for repeated requests
When a script makes many requests, create a Session. It reuses connections, keeps cookies, and lets you set the proxy once.
session = requests.Session()
session.proxies.update(proxies)
session.headers.update({"User-Agent": "my-qa-script/1.0 (contact: you@example.org)"})
for url in urls:
r = session.get(url, timeout=(5, 20))
print(url, r.status_code)
The timeout can be a pair: the first number is how long to wait to establish the connection, the second is how long to wait for data. Setting a clear, honest User-Agent with a contact address is good practice when you are testing a site you operate or one that allows automated checks.
Keep the pace polite. Add a short pause between requests and stay within the limits that a site publishes. If a site returns a rate-limit response, slow down; do not look for ways around it.
Step 4: environment variables as an alternative
requests reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY from the environment by default. That lets you run an existing script through a proxy without changing code.
export HTTPS_PROXY="http://USER:PASS@proxy.example.net:8080"
export HTTP_PROXY="$HTTPS_PROXY"
export NO_PROXY="localhost,127.0.0.1"
python check_pages.py
Use NO_PROXY for internal addresses that must not go through the proxy. If you ever want to ignore the environment inside a particular session, set session.trust_env = False. Be aware that an explicit proxies argument is combined with the environment rules in a specific order, so when results look surprising, test with trust_env off to learn which source is in effect.
Step 5: SOCKS proxies
For SOCKS, install the extra that adds support.
pip install "requests[socks]"
Then use a SOCKS address.
proxy_url = "socks5h://USER:PASS@proxy.example.net:1080"
proxies = {"http": proxy_url, "https": proxy_url}
The socks5h scheme tells the library to let the proxy resolve host names, which keeps DNS lookups from happening on your machine. The plain socks5 scheme resolves names locally. If you care about where lookups happen, read how to check for DNS leaks in a proxy setup. The SOCKS5 protocol itself is described in RFC 1928.
Step 6: verify that the proxy is really in use
Never assume. Compare the public IP address seen by a simple echo page with and without the proxy.
def public_ip(proxies=None):
r = requests.get("https://api.ipify.org", proxies=proxies, timeout=15)
return r.text.strip()
print("direct:", public_ip())
print("proxy :", public_ip(proxies))
The two values should differ if the proxy works. Any simple IP echo service will do; treat it as a diagnostic only and do not call it in a tight loop. For a fixed address, run the check twice and confirm the same value both times. For a rotating endpoint, expect it to vary as your provider describes.
Step 7: handle certificates and errors sensibly
HTTPS verification stays on by default, and it should stay on. If you meet a certificate error only when the proxy is active, do not pass verify=False. Read the article on certificate cautions when using a proxy with HTTPS to find the real cause, which is often an outdated trust bundle or an inspection layer on your network.
Wrap calls so that failures are visible and recoverable.
import requests
from requests.exceptions import ProxyError, ConnectTimeout, ReadTimeout, SSLError
try:
r = session.get(url, timeout=(5, 20))
r.raise_for_status()
except ProxyError as exc:
print("Proxy refused or unreachable:", type(exc).__name__)
except (ConnectTimeout, ReadTimeout):
print("Timed out; try again later")
except SSLError:
print("Certificate problem; investigate, do not disable verification")
For occasional transient failures, mount a retry policy on the session.
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
session.mount("https://", HTTPAdapter(max_retries=retry))
session.mount("http://", HTTPAdapter(max_retries=retry))
Keep retries modest. Hammering a failing endpoint helps no one, and it can look like abuse to the site you are testing.
Common problems and quick fixes
| Symptom | Likely cause | What to try |
|---|---|---|
| ProxyError or connection refused | Wrong host, port or protocol | Re-check the details on the plan page |
| 407 Proxy Authentication Required | Missing or wrong credentials | Verify username and password; encode special characters |
| Script hangs | No timeout set | Add a timeout tuple to every call |
| Same IP as direct connection | Keys mismatched or variables ignored | Print the proxies dictionary (without secrets), check trust_env |
| Certificate verify failed | Old trust bundle or inspection layer | Update the bundle, inspect the issuer |
| Works in browser, fails in script | Different proxy or trust settings | Compare configuration side by side |
Limits and what to watch for
- A proxy changes the route, not the rules. Terms of service, robots rules and local law still apply to what you request and how often.
- Do not log secrets. Exception messages sometimes include the full proxy URL. Catch and print only safe parts.
- Do not rely on one test. Check the IP address, then check a real target page, then check error handling with a deliberately wrong port.
- Know your endpoint type. Fixed and rotating endpoints behave differently, and session-based sites may expect consistent behaviour across requests.
- Version differences exist. Details such as how environment variables combine with explicit settings can vary slightly between releases, so test on the version you deploy.
- Browser automation is a different tool. If a page needs JavaScript to render, a browser-based approach is better; see the guide to setting up a proxy in Playwright for website testing.
Putting it together in a small helper
Once the pieces work, wrap them in one function so that every script in a project builds its session the same way. A shared helper means a single place to change the timeout, the retry policy and the way credentials are read, instead of copies that drift apart over time.
def build_session():
session = requests.Session()
session.proxies.update(proxies)
session.headers.update({"User-Agent": "my-qa-script/1.0 (contact: you@example.org)"})
session.mount("https://", HTTPAdapter(max_retries=retry))
return session
A few habits make this helper easier to live with. Read configuration once at start-up and fail early with a clear message if a variable is missing, rather than discovering the problem on the fortieth request. Keep one session per worker if you use threads, because sharing a session across threads is not something to rely on without testing. Close sessions when you finish, or use them in a with block, so connections are released cleanly.
It is also sensible to keep a tiny smoke test next to the helper. The test requests the IP echo page, checks that the address differs from your direct address, and requests one harmless page on a site you operate. Run it after changing credentials, after upgrading the library, and before a long job. A thirty-second check is far cheaper than discovering halfway through a job that every request went out directly, or that every request failed.
Finally, think about what the destination will see. The site receives the proxy's IP address, and your headers still describe your script. Testing a page as it appears to visitors in another region is a reasonable QA task, but the result depends on the endpoint you chose and on the site's own logic, so treat it as one data point and confirm important findings with a second method.
Summary
To use a proxy with Python Requests, build a proxies dictionary whose keys are the target schemes and whose values are the proxy address, pass it to a call or set it on a Session, and always include a timeout. Keep credentials in environment variables or a secret store, percent-encode special characters, and use socks5h if you want name resolution to happen at the proxy. Verify the setup by comparing the public IP with and without the proxy, keep certificate verification on, handle errors explicitly, and keep your request rate polite and your use lawful.
When you are ready to try a real endpoint, the options and details are listed on the proxy page.
Frequently asked questions
How do I tell Python Requests to use a proxy?
Pass a proxies dictionary to the request or set it on a Session. The dictionary maps a URL scheme such as http or https to the proxy address, for example http://host:port. You can also set the HTTP_PROXY and HTTPS_PROXY environment variables, which Requests reads by default.
Why does my https key point to an http:// proxy address?
The key describes the scheme of the site you are visiting, while the value describes how to reach the proxy. A proxy that accepts plain connections from your script can still tunnel HTTPS sites to their destination, so both keys often hold the same http:// address.
How do I use a SOCKS proxy?
Install the SOCKS extra for Requests and use a socks5:// or socks5h:// address. The socks5h form asks the proxy to resolve host names, which avoids local DNS lookups.
My password contains special characters and the request fails. Why?
Characters such as @, colon, slash and hash have meaning inside a URL. Percent-encode the username and password, or build the address from separate pieces, before placing them in the proxy URL.
How can I check that traffic really goes through the proxy?
Request a simple page that echoes your public IP address, once without the proxy and once with it, and compare the results. Also set a timeout so a failed connection does not hang the script.
References
About the author

Bob Kanokphon Thongdee
- Founder of XPASS VPN
- Co-founder of eSIMonline.asia
- More than 7 years in online marketing
- Founder of Cojourney Visa and Cojourney Travel
Need a proxy for this?
XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.
See proxy plansKeep reading

Proxy Guides
Using a Proxy with HTTPS: Certificate Cautions to Know
A proxy can carry HTTPS traffic without reading it, but certificate warnings deserve attention. Learn what is normal, what is suspicious, and what never to switch off.
9 min read

Proxy Guides
How to Set Up a Proxy in Playwright for Website Testing
Learn where Playwright accepts proxy settings, how to pass credentials safely, how to exclude hosts, and how to confirm a test really runs through the proxy.
9 min read

Proxy Guides
How to Store Proxy Credentials Securely
Proxy credentials leak through code repositories, shell history, logs and chat messages. Learn practical storage options, rotation habits and what to do after an exposure.
10 min read