On this page
This guide shows the same proxy setup in the three most used Python HTTP clients. Each example prints the exit IP, so you can run it as it is to confirm the connection, then reuse the setup in your own code. If your password contains special characters, see proxy formats for how to encode them.
Keep credentials out of your source code. A simple way is an environment variable:
import os
PROXY = os.environ["PROXY_URL"] # for example http://USERNAME:PASSWORD@HOST:PORT
requests
pip install requests
import requests
PROXY = "http://USERNAME:PASSWORD@HOST:PORT"
proxies = {"http": PROXY, "https": PROXY}
r = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=30)
r.raise_for_status()
print(r.json())
The keys in proxies are the schemes of the websites you visit, and the values are the proxy URL. Use http:// in the value for both keys; HTTPS websites still go through an encrypted tunnel. Always set a timeout, because requests can wait indefinitely by default.
Sessions
A Session reuses connections, which is faster for many requests:
session = requests.Session()
session.proxies.update(proxies)
If HTTP_PROXY or HTTPS_PROXY is set in your environment, requests can prefer it over session.proxies. Passing proxies= on each call, or setting session.trust_env = False, avoids surprises.
SOCKS5
pip install "requests[socks]"
PROXY = "socks5h://USERNAME:PASSWORD@HOST:PORT"
proxies = {"http": PROXY, "https": PROXY}
Use the SOCKS5 port from your dashboard. socks5h:// lets the proxy resolve domain names; socks5:// resolves them on your machine.
httpx
pip install httpx
import httpx
with httpx.Client(proxy="http://USERNAME:PASSWORD@HOST:PORT", timeout=30) as client:
r = client.get("https://api.ipify.org?format=json")
print(r.json())
httpx 0.28 removed the old proxies= argument. Use proxy= as shown, or mounts= if you need different proxies for different URLs.
The async client takes the same argument:
import asyncio
import httpx
async def main():
async with httpx.AsyncClient(proxy="http://USERNAME:PASSWORD@HOST:PORT", timeout=30) as client:
r = await client.get("https://api.ipify.org?format=json")
print(r.json())
asyncio.run(main())
SOCKS5
pip install "httpx[socks]"
client = httpx.Client(proxy="socks5://USERNAME:PASSWORD@HOST:PORT", timeout=30)
httpx sends the hostname to the SOCKS5 proxy, so the proxy resolves domain names with either socks5:// or socks5h://. The socks5h:// scheme is accepted from httpx 0.28.
aiohttp
pip install aiohttp
import asyncio
import aiohttp
PROXY = "http://HOST:PORT"
PROXY_AUTH = aiohttp.BasicAuth("USERNAME", "PASSWORD")
async def main():
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get("https://api.ipify.org?format=json",
proxy=PROXY, proxy_auth=PROXY_AUTH) as resp:
print(await resp.text())
asyncio.run(main())
You can also put the credentials in the URL, as proxy="http://USERNAME:PASSWORD@HOST:PORT", and leave out proxy_auth. aiohttp ignores proxy environment variables unless you create the session with trust_env=True.
SOCKS5
aiohttp has no built-in SOCKS support. The aiohttp-socks package adds it as a connector:
pip install aiohttp-socks
import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector
async def main():
connector = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@HOST:PORT", rdns=True)
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get("https://api.ipify.org?format=json") as resp:
print(await resp.text())
asyncio.run(main())
rdns=True makes the proxy resolve domain names. The connector applies to every request made with that session.
Rotation and connection reuse
All three clients keep connections open and reuse them. For HTTPS websites, requests that reuse one connection leave from the same exit IP, even on a rotating line. That's what you want with a sticky line, and the opposite of what you want when every request should get a new IP.
| Goal | requests | httpx | aiohttp |
|---|---|---|---|
| New connection per request | Call requests.get() without a session |
httpx.Client(proxy=PROXY, limits=httpx.Limits(max_keepalive_connections=0)) |
ClientSession(connector=aiohttp.TCPConnector(force_close=True)) |
| Stable IP | A sticky line, one session per line | A sticky line, one client per line | A sticky line, one session per line |
For several sticky sessions at once, create one client or session per sticky line. Rotating vs sticky sessions explains both modes.
Errors you'll see
| Error | What it means |
|---|---|
ProxyError mentioning 407 Proxy Authentication Required |
The proxy rejected the username or password |
ProxyError mentioning Unable to connect to proxy |
Wrong host or port, or the port is blocked |
ConnectTimeout or ReadTimeout |
The proxy or the website didn't answer in time |
SSLError such as WRONG_VERSION_NUMBER |
https:// used in front of a plain proxy port |
| A message about a missing SOCKS dependency | Install the SOCKS extra shown above |
httpx.ProxyError or aiohttp.ClientHttpProxyError |
The proxy returned an error; check the status code it reports |
For crawls with many pages, see the Scrapy guide. For everything else, troubleshooting lists the common causes and fixes.