Guide
How to Use a Proxy in Python: requests, httpx and aiohttp Examples
In Python, a proxy is defined as a URL in the form http://USER:PASSWORD@host:port. HTTP and SOCKS5 examples for requests, httpx and aiohttp, sticky session handling, checking your exit IP, and proxy errors by library.
Key takeaways
- In Python, a proxy is defined as a URL in the form http://USER:PASSWORD@host:port; the scheme describes the proxy server’s protocol, so the proxy address is written with http:// even for HTTPS targets.
- requests takes the proxy as a {"http": ..., "https": ...} dictionary; if the "https" key is missing, HTTPS requests skip the proxy and go out from your real IP.
- Current httpx versions use a single proxy= parameter; the old proxies= dictionary was removed in version 0.28. aiohttp takes the proxy on each request through the proxy= argument, with optional proxy_auth.
- SOCKS5 requires requests[socks], httpx[socks] or aiohttp-socks; the socks5h scheme or the rdns=True setting leaves DNS resolution to the proxy.
- Because session objects reuse connections, consecutive requests on a rotating gateway can leave from the same IP; for jobs that need a fixed IP, each profile should open its own session with a username carrying its own session ID.
To use a proxy in Python, you write the proxy address as a URL in the form http://USER:PASSWORD@host:port and pass it to your HTTP library: requests takes it through a proxies dictionary, httpx through a single proxy parameter, and aiohttp through a proxy argument on each request. For SOCKS5, you need to install one of the requests[socks], httpx[socks] or aiohttp-socks packages.
The differences between the libraries mostly show up in the details: whether they read environment variables, whether they reuse connections, and which exception they raise when something fails. The examples below use the WeProxy gateway address gw.weproxy.com.tr:8989; USER and PASSWORD are the credentials from your dashboard.
How do you write a proxy address in Python?
All three libraries expect the proxy in the same URL format:
scheme://username:password@host:port
The scheme describes the protocol the proxy server speaks, not the protocol of the target site. If you’re reaching an HTTPS site through an HTTP proxy, the proxy address still starts with http://; the client sends CONNECT to the proxy and the TLS connection is set up inside the tunnel. Writing the proxy address with https:// means trying to speak TLS with the proxy itself, and in most setups that ends in an SSLError or a connection error.
SOCKS5 has two schemes. socks5:// resolves the target domain on your own machine, while socks5h:// sends the domain to the proxy and has it resolved on the proxy side. The second form keeps DNS queries from leaving your local network; the DNS leak guide covers the difference in detail. For choosing a protocol, see HTTP vs SOCKS5.
If the password contains @, :, / or #, percent-encode it before putting it in the URL. An unencoded @ makes the client treat the rest of the password as the host name, and the result is a 407 or an unresolvable address error:
import os
from urllib.parse import quote
user = quote(os.environ["WEPROXY_USERNAME"], safe="")
password = quote(os.environ["WEPROXY_PASSWORD"], safe="")
PROXY = f"http://{user}:{password}@gw.weproxy.com.tr:8989"
Reading credentials from an environment variable or a secret manager instead of hardcoding them keeps the password from leaking when you push the code to Git. If the dashboard gave you a list in ip:port:user:pass format, the proxy format converter turns those lines into URL format. For socks5h, IPv6 addresses and per-tool format differences, see the proxy formats guide.
How do you use a proxy with requests?
requests is the most widely used synchronous HTTP library. It takes the proxy as a dictionary mapped by scheme:
import requests
proxies = {
"http": PROXY,
"https": PROXY,
}
r = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=(10, 30))
r.raise_for_status()
print(r.json()) # {"ip": "<proxy exit IP>"}
The keys in the dictionary are the target’s scheme. If you only set the "http" key, HTTPS requests skip the proxy and go out directly from your own IP. This is the most common reason behind the “I set a proxy but my real IP still shows” complaint. Point both keys at the same proxy. This setting only covers the script’s own requests; the browser and other programs on the same machine still go out from your own IP. The proxy vs VPN article explains the difference between an app-level proxy and a VPN that tunnels the whole device.
timeout=(10, 30) allows 10 seconds to connect and 30 seconds to read the response. If you pass a single number, both stages share the same limit, and it gets harder to tell whether a timeout came from the proxy or from a slow target.
If you’ll be sending lots of requests, use a Session. A session keeps TCP connections and cookies, so there’s no new handshake on every request:
with requests.Session() as s:
s.proxies.update(proxies)
for url in ["https://api.ipify.org", "https://httpbin.org/headers"]:
print(s.get(url, timeout=(10, 30)).text)
By default, requests also reads the HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY environment variables. The Requests documentation notes that values from the environment can override the session.proxies setting. If these variables are set on the server for some other tool, pass the proxy on every request with the proxies= parameter, or turn off environment reading with s.trust_env = False. If the target domain is on the NO_PROXY list, the request still goes out without the proxy.
How do you use a SOCKS5 proxy with requests?
SOCKS support comes as a separate dependency:
python -m pip install "requests[socks]"
Then you write the same dictionary with a SOCKS scheme:
SOCKS = f"socks5h://{user}:{password}@gw.weproxy.com.tr:8989"
proxies = {"http": SOCKS, "https": SOCKS}
r = requests.get("https://api.ipify.org?format=json", proxies=proxies, timeout=(10, 30))
print(r.json())
If the package isn’t installed, requests raises an exception with the message InvalidSchema: Missing dependencies for SOCKS support. Writing socks5 instead of socks5h works, but the target domain gets resolved by your local DNS. requests can’t carry UDP traffic such as games, VoIP or QUIC; setups that need UDP are covered in the UDP proxy guide.
How do you use a proxy with httpx?
httpx has an interface similar to requests, but it offers both synchronous and asynchronous clients and supports HTTP/2. In current versions, the proxy is passed through a single proxy parameter. The proxies= dictionary you’ll see in older examples was deprecated in version 0.26 and removed in 0.28, so old code you find online may raise a TypeError.
import httpx
timeout = httpx.Timeout(30.0, connect=10.0)
with httpx.Client(proxy=PROXY, timeout=timeout) as client:
r = client.get("https://api.ipify.org?format=json")
print(r.json())
The async version takes the same parameters:
import asyncio
import httpx
async def main():
async with httpx.AsyncClient(proxy=PROXY, timeout=30.0) as client:
r = await client.get("https://api.ipify.org?format=json")
print(r.json())
asyncio.run(main())
If you only want certain domains to go through the proxy, you can set up routing with mounts. The client below sends api.ipify.org requests to the proxy and lets the rest of the traffic go out directly:
mounts = {"https://api.ipify.org": httpx.HTTPTransport(proxy=PROXY)}
with httpx.Client(mounts=mounts) as client:
print(client.get("https://api.ipify.org").text) # proxy IP
For SOCKS5, install python -m pip install "httpx[socks]" and pass the address with the socks5:// scheme. httpx reads environment variables too (trust_env=True is the default); when you pass the proxy parameter explicitly, the proxy from the environment isn’t used. Details are in the httpx proxy documentation.
Using an async proxy with aiohttp
aiohttp is a common choice for scrapers that need to run hundreds of requests at once. The proxy is passed on each request with the proxy argument rather than set once on the session. Passing credentials separately with BasicAuth instead of embedding them in the URL removes the encoding hassle when the password contains special characters:
import asyncio
import aiohttp
PROXY_URL = "http://gw.weproxy.com.tr:8989"
AUTH = aiohttp.BasicAuth("USER", "PASSWORD")
async def fetch(session, url, sem):
async with sem:
async with session.get(url, proxy=PROXY_URL, proxy_auth=AUTH) as resp:
return resp.status, await resp.text()
async def main():
urls = ["https://api.ipify.org?format=json"] * 20
sem = asyncio.Semaphore(5)
timeout = aiohttp.ClientTimeout(total=60, connect=10)
async with aiohttp.ClientSession(timeout=timeout) as session:
results = await asyncio.gather(
*(fetch(session, u, sem) for u in urls), return_exceptions=True
)
for item in results:
print(item)
asyncio.run(main())
asyncio.Semaphore(5) keeps at most five requests open at the same time. WeProxy plans have no limit on concurrent connections or threads. The reason to cap concurrency is the target site: a sudden burst of requests from a single IP runs into the target’s rate limit and gets a 429. return_exceptions=True keeps a single failure from stopping the whole job.
aiohttp doesn’t read environment variables by default (trust_env=False). It doesn’t support SOCKS on its own either; for that, you use the aiohttp-socks package:
from aiohttp_socks import ProxyConnector
connector = ProxyConnector.from_url(
"socks5://USER:[email protected]:8989", rdns=True
)
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get("https://api.ipify.org") as resp:
print(await resp.text())
rdns=True leaves domain resolution to the proxy; it’s the equivalent of the socks5h scheme. With this approach the connection pool is tied to a single proxy, so you open a separate ClientSession for each proxy. Proxy support is covered in detail in the aiohttp documentation.
requests vs httpx vs aiohttp
| Feature | requests | httpx | aiohttp |
|---|---|---|---|
| Execution model | Synchronous | Synchronous and asynchronous | Asynchronous |
| Proxy parameter | proxies={"http": ..., "https": ...} | proxy="..." (client level) | proxy="..." (request level) |
| Credentials | In the URL | In the URL | In the URL or proxy_auth=BasicAuth(...) |
| SOCKS5 | requests[socks] | httpx[socks] | aiohttp-socks |
| Environment variables | On by default | On by default | Off by default |
| HTTP/2 | No | Yes (httpx[http2]) | No |
| Best suited for | Simple scripts, small batch jobs | Moving from sync to async code, API clients | High-concurrency scraping |
If an existing project uses requests and you’re not sending more than a few hundred requests a minute, there’s no need to switch libraries. If you need to crawl thousands of URLs in parallel, aiohttp or httpx.AsyncClient use resources more efficiently; requests also works with a thread pool, but each thread carries its own connection.
How do you manage rotating and sticky IPs in Python?
On a rotating gateway, the proxy address stays the same while the exit IP rotates through the pool. On the Python side, the only thing to watch is connection reuse. requests.Session, httpx.Client and aiohttp.ClientSession keep the connection to the same target open; for HTTPS requests, that means the same CONNECT tunnel gets reused. If IP rotation is applied per new connection, consecutive requests can leave from the same IP. To find out whether the gateway rotates per request or per connection, query api.ipify.org twice with the same session, then twice with two separate sessions, and compare the results.
Stateful jobs like logins, shopping carts or multi-step forms need the opposite: the same IP across requests. In WeProxy residential and mobile pools, you do this by adding a session ID to the username. The same exit IP can be held for up to 24 hours in the residential pool and up to 60 minutes in the mobile pool. The exact username format varies by product, so copy it from the dashboard. In code, opening a separate session for each account or profile is enough:
import requests
from urllib.parse import quote
# Usernames are copied from the dashboard; each profile carries its own session ID.
PROFILES = {
"account-1": "USER_WITH_SESSION_1",
"account-2": "USER_WITH_SESSION_2",
}
PASSWORD = quote("PASSWORD", safe="")
def session_for(profile: str) -> requests.Session:
user = quote(PROFILES[profile], safe="")
proxy = f"http://{user}:{PASSWORD}@gw.weproxy.com.tr:8989"
s = requests.Session()
s.proxies.update({"http": proxy, "https": proxy})
return s
sessions = {name: session_for(name) for name in PROFILES}
for name, s in sessions.items():
print(name, s.get("https://api.ipify.org", timeout=(10, 30)).text)
Two profiles shouldn’t share the same session ID; if they do, the target site sees two separate users on the same IP. The sticky vs rotating guide has a scenario table showing which jobs need sticky and which need rotating. The plan that offers both rotation and sticky sessions is on the rotating residential proxy page. When deciding which country, city or network each account should appear from, the geo-targeting guide will help.
How do you verify the proxy is working?
The quickest way to see that your code goes out through the proxy is to check your exit IP with and without the proxy and compare the two:
import requests
direct = requests.get("https://api.ipify.org", timeout=10).text
via_proxy = requests.get("https://api.ipify.org", proxies=proxies, timeout=(10, 30)).text
print("direct:", direct, "| proxy:", via_proxy)
assert direct != via_proxy, "Request is not going through the proxy"
If the two values match, the proxy dictionary isn’t reaching the request: check the "https" key, the NO_PROXY variable and the trust_env setting. Use the My IP tool to see the proxy IP’s country and network, and the proxy checker to test the proxy itself independently of your code. A proxy that works in the proxy checker but not from your code points to a problem in the library settings.
In browser automation (Playwright, Selenium), DNS and WebRTC can leak through a separate channel even when the IP looks right. The risk is low with script-based clients, but if you use SOCKS, double-check that you chose socks5h or rdns=True.
Python proxy errors and how to fix them
The same problem shows up as a different exception in each library. The table maps the four most common cases:
| Situation | requests | httpx | aiohttp |
|---|---|---|---|
Proxy rejected the credentials (407) | ProxyError (“Tunnel connection failed: 407”) | ProxyError | ClientHttpProxyError (status 407) |
| Couldn’t connect to the proxy | ProxyError or ConnectTimeout | ConnectError or ConnectTimeout | ClientProxyConnectionError |
| Target didn’t respond in time | ReadTimeout | ReadTimeout | ServerTimeoutError (subclass of TimeoutError) |
| SOCKS dependency missing | InvalidSchema | ImportError (socksio missing) | aiohttp-socks must be installed |
When you get a 407, first check that the password is percent-encoded, then that your plan is active. If you work with an IP whitelist, the exit IP of the server running the code must be registered in the dashboard; if a script that ran on your local machine starts getting 407 after moving to a cloud server, that’s the reason. Don’t retry on 407: trying again with the wrong credentials won’t change the result.
429, 502, 503 and 504, on the other hand, can be temporary and call for retries with backoff. A ready-made urllib3.Retry example for requests, along with which layer each code comes from, is in the proxy error codes guide. If ConnectTimeout keeps happening, your corporate network or cloud provider may be blocking outbound traffic on port 8989.
Compliance and security when using a proxy with Python
If you’re writing a script that collects data, follow the target’s robots.txt file (RFC 9309) and terms of use even though the requests go out through a proxy, and keep the request rate at a level the site can handle. If you process personal data, obligations under KVKK and GDPR apply regardless of proxy use. Permitted and prohibited uses of WeProxy services are listed on the acceptable use page.
Keep credentials in environment variables, and remove the password from the proxy URL before sharing logs. More setup examples are on the Python integration page, and a runnable sample project is in the weproxy-io/python-proxy repository. For choosing an IP type and session setup for scraping jobs, see the web scraping page. If you’re torn between residential and datacenter IPs, the residential vs datacenter comparison covers which one gets blocked less on which kind of target.
Frequently asked questions
How do I use a proxy with Python requests?
Write the proxy address as http://USER:PASSWORD@host:port, build a dictionary that assigns it to both the "http" and "https" keys, and pass it to the request with the proxies= parameter. For many requests, open a requests.Session and use session.proxies.update(). If the password contains characters like @ or :, encode it with urllib.parse.quote, otherwise you’ll get a 407 error.
Why does my real IP still show after I set a proxy?
The most common cause is a missing "https" key in the proxies dictionary; in that case HTTPS requests go out directly. The NO_PROXY environment variable may also cover the target domain, or HTTP_PROXY values from the environment may be overriding the session setting. Query api.ipify.org with and without the proxy and compare the results to find the problem quickly.
Why does the proxies parameter raise an error in httpx?
httpx deprecated the proxies= dictionary in version 0.26 and removed it completely in 0.28. In current versions, you pass a single proxy as httpx.Client(proxy="http://USER:PASSWORD@host:port"). If only some domains should go through the proxy, define httpx.HTTPTransport(proxy=...) per domain with the mounts parameter. Watch for version differences when copying old examples from the internet; pip show httpx displays the installed version.
Can I use a SOCKS5 proxy with aiohttp?
On its own, aiohttp only supports HTTP proxies. For SOCKS5, install the aiohttp-socks package, create a connector with ProxyConnector.from_url("socks5://USER:PASSWORD@host:port", rdns=True) and pass it to ClientSession. rdns=True leaves domain resolution to the proxy. Since the connector is tied to a single proxy, you need to open a separate session for each proxy you use.
How many concurrent requests can I send through a proxy in Python?
WeProxy plans have no limit on concurrent connections or threads; in practice, the target site sets the limit. A sudden burst of requests from a single IP runs into the target’s rate limit and gets a 429. When working with aiohttp or httpx.AsyncClient, cap concurrency with asyncio.Semaphore, respect the Retry-After header, and follow the target’s robots.txt and terms of use.









