aiohttp Proxy Setup: HTTP, HTTPS, SOCKS5 and Rotation
Route aiohttp through HTTP, HTTPS and SOCKS5 proxies: proxy= with working auth on 3.14, trust_env, aiohttp-socks, semaphores, rotation, errors.
To send an aiohttp request through a proxy, pass proxy= with the credentials inside the URL. The same line covers http:// and https:// targets:
import asyncio
import aiohttp
PROXY = "http://USERNAME:PASSWORD@HOST:PORT"
async def main() -> None:
timeout = aiohttp.ClientTimeout(total=60, sock_connect=10, sock_read=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get("https://api.ipify.org", proxy=PROXY) as resp:
print(resp.status, await resp.text())
asyncio.run(main())It prints 200 and the proxy's exit address. If the address is your own, the proxy was not applied.
What you need: pip install aiohttp, and a proxy URL. On Node4, copy it from the Connect card on the dashboard's Proxies page. A free account runs every example that uses a plain HOST:PORT HTTP proxy. SOCKS5 needs pip install aiohttp-socks and a paid plan, because the free tier is HTTP(S) only, and the rotating gateway is a paid product too. The samples are written for aiohttp 3.14 and aiohttp-socks 0.12.
| Proxy type | How aiohttp reaches it |
|---|---|
HTTP proxy, http:// target | proxy="http://...", built in |
HTTP proxy, https:// target | Same argument. aiohttp opens a CONNECT tunnel |
| SOCKS5 proxy | ProxyConnector from the aiohttp-socks package |
Proxy from HTTP_PROXY / HTTPS_PROXY | ClientSession(trust_env=True) |
| WebSocket through a proxy | session.ws_connect(url, proxy="http://...") |
aiohttp HTTP proxy and HTTPS proxy: what the scheme means
The scheme of the proxy URL describes how you talk to the proxy, not what you fetch through it. For an https:// target, aiohttp connects to the proxy in plain HTTP, sends CONNECT host:443, and runs TLS with the destination inside the tunnel. The proxy sees the hostname and relays encrypted bytes. So an "aiohttp HTTPS proxy" setup is almost always an http:// proxy URL carrying an https:// request.
A proxy URL that itself starts with https:// means TLS to the proxy, then a second TLS session inside it. Use that only when a provider tells you its endpoint speaks TLS. A Node4 endpoint speaks plain HTTP, and pointing an https:// proxy URL at a plain listener fails with ClientConnectorSSLError and "wrong version number".
Set the proxy once for the whole session
proxy= on each call is easy to forget, and a call that omits it goes direct without any warning. Since aiohttp 3.11, ClientSession takes a default proxy:
import asyncio
import aiohttp
PROXY = "http://USERNAME:PASSWORD@HOST:PORT"
async def main() -> None:
async with aiohttp.ClientSession(proxy=PROXY) as session:
for url in ("https://api.ipify.org", "http://api.ipify.org"):
async with session.get(url) as resp:
print(url, resp.status, await resp.text())
asyncio.run(main())A proxy= on an individual request still overrides the session default, which is what per-request rotation uses further down. Create one ClientSession per application and reuse it. A session per request throws away the connection pool, and every request pays for a new connection to the proxy, a new tunnel and a new TLS handshake.
aiohttp proxy authentication
aiohttp has three ways to send proxy credentials. They do not behave the same:
| Method | http:// targets | https:// targets | Status in aiohttp 3.14 |
|---|---|---|---|
Credentials in the URL: proxy="http://USER:PASS@HOST:PORT" | Works | Works | Supported |
proxy_auth=aiohttp.BasicAuth("USER", "PASS") | Works | Works | Deprecated: DeprecationWarning, removal announced for 4.0 |
proxy_headers={"Proxy-Authorization": aiohttp.encode_basic_auth("USER", "PASS")} | 407: the header is not sent | Works | Supported |
Use URL credentials. They are the only form that works for both target schemes without a warning. The proxy_headers route that the deprecation message recommends is applied to the CONNECT request only, so a plain http:// request made that way reaches the proxy with no credentials and comes back 407.
A password with reserved characters (@, :, /, #) has to be percent-encoded before it goes into the URL:
from urllib.parse import quote
username = quote("USERNAME", safe="")
password = quote("p@ss:w/rd#1", safe="")
PROXY = f"http://{username}:{password}@HOST:PORT"If you whitelist your IP address under Auth & IP Access in Account Settings, there are no credentials at all: the proxy URL is http://HOST:PORT.
Proxy from environment variables: trust_env
Unlike requests, aiohttp ignores HTTP_PROXY and HTTPS_PROXY unless you opt in:
import asyncio
import aiohttp
async def main() -> None:
async with aiohttp.ClientSession(trust_env=True) as session:
async with session.get("https://api.ipify.org") as resp:
print(await resp.text())
asyncio.run(main())export HTTPS_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export HTTP_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export NO_PROXY="localhost,127.0.0.1"
python app.pyWith trust_env=True:
HTTP_PROXYandHTTPS_PROXYare chosen by the target's scheme.WS_PROXYandWSS_PROXYdo the same for WebSockets.- Hosts listed in
NO_PROXYgo direct. - An explicit
proxy=argument wins over the environment, including for a host inNO_PROXY. - If the proxy URL carries no credentials, aiohttp looks for them in
~/.netrc.
The risk is the mirror image of the default: with trust_env=True and a missing variable, traffic goes direct and nothing fails. Run the check at the end of this page in the same environment as the application.
aiohttp SOCKS5 proxy with aiohttp-socks
aiohttp has no SOCKS support of its own. It also does not reject a socks5:// URL in proxy=: it sends an HTTP request to the SOCKS5 port and fails with a ClientResponseError ("Bad status line") or a ServerDisconnectedError. SOCKS5 goes in through a connector from the aiohttp-socks package instead:
pip install aiohttp aiohttp-socksimport asyncio
import aiohttp
from aiohttp_socks import ProxyConnector
async def main() -> None:
connector = ProxyConnector.from_url("socks5://USERNAME:PASSWORD@HOST:SOCKS_PORT")
async with aiohttp.ClientSession(connector=connector) as session:
async with session.get("https://api.ipify.org") as resp:
print(resp.status, await resp.text())
asyncio.run(main())Every request on that session goes through the SOCKS5 proxy, with no proxy= on the calls. A connector is bound to one proxy for its lifetime.
On Node4, SOCKS5 uses the same host and credentials as HTTP on a different port. Switch the Connect card to SOCKS5 to see it; the rotating gateway gw-rotating_datacenter.node4.io listens for SOCKS5 on port 1083, and the HTTP port will not complete a SOCKS5 handshake. Every paid product includes SOCKS5. A free account's credential is refused there, so this section needs a plan from the pricing page. SOCKS5 proxy setup covers the protocol, and HTTP vs SOCKS5 helps you decide whether you need it at all: for web requests the target sees the same exit address over either.
Where DNS resolves: rdns, not socks5h
In curl and requests, socks5h:// means "resolve the hostname at the proxy". aiohttp-socks does not use that spelling:
ProxyConnector.from_url("socks5h://...")raisesValueError: Invalid scheme component: socks5h.- A plain
socks5://URL already sends the hostname to the proxy, becauserdns(remote DNS) defaults to on for SOCKS5.
To make the choice explicit, build the connector from parts:
from aiohttp_socks import ProxyConnector, ProxyType
def make_connector() -> ProxyConnector:
# Call this from inside a running event loop, next to the ClientSession.
return ProxyConnector(
proxy_type=ProxyType.SOCKS5,
host="HOST",
port=1080, # your SOCKS5 port
username="USERNAME",
password="PASSWORD",
rdns=True, # resolve hostnames at the proxy
)Leave rdns on. With rdns=False, your machine looks up every hostname before the connector dials the proxy. That exposes the lookups to your local resolver, and DNS-based load balancing picks servers near you instead of near the exit.
Concurrency: a semaphore plus the connector limit
aiohttp will happily start ten thousand requests at once. Through a proxy that means ten thousand tunnels, and timeouts that look like a slow proxy. Bound the work in two places: a semaphore for requests in flight, and the connector's limit for open connections.
import asyncio
import random
import time
from datetime import timezone
from email.utils import parsedate_to_datetime
import aiohttp
PROXY = "http://USERNAME:PASSWORD@HOST:PORT"
CONCURRENCY = 20
URLS = [f"https://example.com/?page={n}" for n in range(200)]
RETRYABLE = {429, 500, 502, 503, 504}
MAX_WAIT = 120 # longest Retry-After this job is willing to honor, in seconds
def retry_after(headers):
"""Seconds the server asked us to wait, or None if it did not say."""
value = (headers.get("Retry-After") or "").strip()
if value.isdigit():
return int(value)
try:
when = parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc)
return max(0.0, when.timestamp() - time.time())
async def fetch(session, semaphore, url, attempts=4):
error = "not attempted"
for attempt in range(1, attempts + 1):
wait = None
try:
async with semaphore:
async with session.get(url) as resp:
body = await resp.text()
if resp.status not in RETRYABLE:
return resp.status, body
error = f"HTTP {resp.status}"
wait = retry_after(resp.headers)
except aiohttp.ClientHttpProxyError as exc:
if exc.status == 407:
raise # wrong credentials: retrying cannot help
error = repr(exc)
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
error = repr(exc)
if wait is not None and wait > MAX_WAIT:
raise RuntimeError(f"{url}: server asked for {wait:.0f}s, defer it to a later run")
if attempt < attempts:
backoff = min(30, 2 ** attempt) + random.random()
await asyncio.sleep(wait if wait is not None else backoff)
raise RuntimeError(f"{url} failed after {attempts} attempts: {error}")
async def main() -> None:
semaphore = asyncio.Semaphore(CONCURRENCY)
connector = aiohttp.TCPConnector(limit=CONCURRENCY)
timeout = aiohttp.ClientTimeout(total=60, sock_connect=10, sock_read=30)
async with aiohttp.ClientSession(connector=connector, timeout=timeout, proxy=PROXY) as session:
results = await asyncio.gather(
*(fetch(session, semaphore, url) for url in URLS),
return_exceptions=True,
)
failed = [r for r in results if isinstance(r, Exception)]
print(f"{len(results) - len(failed)} ok, {len(failed)} failed")
for exc in failed[:5]:
print(" ", exc)
asyncio.run(main())Expected output is a line such as 200 ok, 0 failed. What each part is doing:
- The semaphore caps requests in flight, including the time spent reading the body. The backoff sleep sits outside it, so a task that is waiting to retry does not hold a slot.
TCPConnector(limit=...)caps open connections. The default is 100 across the session and no per-host cap.limit=0removes the cap.- The timeout is split.
sock_connectbounds reaching the proxy andsock_readbounds silence between chunks. Avoid a tightconnect=value under load: it also counts time spent waiting for a free pool slot, so a busy pool produces timeouts on a healthy proxy. aiohttp's default is a 300-second total, which is too long for a crawler. Retry-Afterwins when it is present. A429or503that names a wait, in seconds or as an HTTP date, gets exactly that wait. A wait longer thanMAX_WAITstops the URL so you can queue it for a later run instead of holding a worker. Without the header, backoff with jitter spaces the retries and keeps a burst of failures from retrying in lockstep. A407is never retried: the credentials are wrong.return_exceptions=Truekeeps one failed URL from canceling the rest.
For a URL list too large to hold as tasks, feed a fixed number of workers from an asyncio.Queue instead of creating one task per URL.
How high to set CONCURRENCY depends on the plan. On Node4's Rotating Unmetered, concurrent connections are what the plan is sized by: the gateway answers a connection over the limit with a 429 carrying an X-Node4-Conn-Limit header, which aiohttp raises as ClientHttpProxyError with status 429 on an https:// target. Set CONCURRENCY at or below your plan's number (connection limits). Fair-use guidance on the free tier is 10 concurrent threads. High-concurrency proxies goes deeper on sizing.
Rotating proxies in aiohttp
Through a rotating gateway
A rotating gateway is one hostname that picks an exit from a pool for each connection. Because the exit belongs to the connection, aiohttp's keep-alive decides how often it changes: pooled tunnels to the same target keep their exit until they close. force_close=True gives every request its own connection and so its own pick:
import asyncio
import aiohttp
GATEWAY = "http://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:8083"
async def main() -> None:
connector = aiohttp.TCPConnector(force_close=True)
async with aiohttp.ClientSession(connector=connector, proxy=GATEWAY) as session:
for _ in range(3):
async with session.get("https://api.ipify.org") as resp:
print(await resp.text())
asyncio.run(main())It prints three addresses. A pick can repeat an earlier one, so expect variety and not a strict no-repeat sequence. Without force_close, you trade a new exit per request for fewer handshakes, which is the better deal when requests are independent and volume matters more than address spread.
One exit per task with a session id
When a task must keep one address (a login, a cart, a paginated crawl), add a session id to the username. proxy= is a per-request argument, so each task can carry its own:
import asyncio
import aiohttp
def sticky_proxy(task_id: str) -> str:
user = "USERNAME-session-" + task_id
return "http://" + user + ":PASSWORD@gw-rotating_datacenter.node4.io:8083"
async def run_task(session: aiohttp.ClientSession, task_id: str) -> None:
proxy = sticky_proxy(task_id)
for _ in range(2):
async with session.get("https://api.ipify.org", proxy=proxy) as resp:
print(task_id, await resp.text())
async def main() -> None:
async with aiohttp.ClientSession() as session:
await asyncio.gather(*(run_task(session, f"job{n}") for n in range(3)))
asyncio.run(main())Each job prints one address twice. On the Rotating Datacenter and Rotating Unmetered gateways a session id holds its exit for up to 30 minutes; use letters and digits for the id. A ClientSession also shares one cookie jar, so give each identity its own ClientSession when cookies must not mix. Sticky vs rotating sessions covers how long pins last on each product.
Node4 sells the gateway two ways on the same pool, with exits in the US, Italy and Spain: Rotating Datacenter by the gigabyte, from $5.90/month for 10 GB ($0.59/GB), and Rotating Unmetered by concurrent connections with no byte meter, from $29.00/month for 250 connections ($0.116 per connection). An async crawler that moves a lot of data usually fits the second: unmetered pricing lists the tiers. The gateways are paid products; the free tier's static proxies use the list approach below.
Per-request rotation over a proxy list
With static HTTP proxies, pass a different proxy= on each request. aiohttp pools connections per proxy, so one session serves the whole list:
import asyncio
import itertools
import aiohttp
PROXIES = [
"http://USERNAME:PASSWORD@HOST1:PORT",
"http://USERNAME:PASSWORD@HOST2:PORT",
"http://USERNAME:PASSWORD@HOST3:PORT",
]
proxy_cycle = itertools.cycle(PROXIES)
async def fetch(session: aiohttp.ClientSession, url: str) -> str:
proxy = next(proxy_cycle)
async with session.get(url, proxy=proxy) as resp:
return f"{proxy.rsplit('@', 1)[-1]} -> {await resp.text()}"
async def main() -> None:
async with aiohttp.ClientSession() as session:
for line in await asyncio.gather(*(fetch(session, "https://api.ipify.org") for _ in range(6))):
print(line)
asyncio.run(main())Each proxy handles two of the six requests. Combine it with the retry loop above and skip a proxy for a cooldown after it fails, so one dead address does not eat a third of the attempts.
SOCKS5 lists work differently, because a ProxyConnector is bound to one proxy. Keep one ClientSession per SOCKS5 proxy and cycle the sessions, or point a single connector at a gateway's SOCKS5 port and let the gateway rotate. How to rotate proxy IPs compares gateway and client-side rotation in more depth.
aiohttp proxy errors and fixes
| What you see | Cause | Fix |
|---|---|---|
ClientHttpProxyError: 407, message='Proxy Authentication Required' | The proxy rejected the credentials while opening an HTTPS tunnel | Check username, password and encoding. The 407 guide lists the causes in order |
resp.status == 407 on an http:// target | The same rejection, delivered as a response. Also what proxy_headers auth produces on plain HTTP | Put the credentials in the proxy URL |
ClientProxyConnectionError: Cannot connect to host | aiohttp could not reach the proxy | Check host, port and outbound firewall |
ClientConnectorSSLError ... wrong version number | An https:// proxy URL against a plain HTTP proxy | Use http:// as the proxy scheme |
ClientResponseError ... Bad status line, or ServerDisconnectedError | A socks5:// URL passed to proxy= | Use ProxyConnector from aiohttp-socks |
ValueError: Invalid scheme component: socks5h | aiohttp-socks does not accept socks5h:// | Write socks5://. Remote DNS is already the default |
ProxyConnectionError (aiohttp-socks) | The SOCKS5 endpoint did not accept a TCP connection | Check host and SOCKS5 port. Credentials are not involved yet |
ProxyError: Connection not allowed by ruleset (aiohttp-socks) | The SOCKS5 proxy refused the request. On Node4: wrong credentials, a free account, or Rotating Unmetered at its connection limit | Check credentials and plan, then the live connections panel |
ProxyError: Host unreachable (aiohttp-socks) | The exit could not reach the target, or a -country- segment named a country with no exits | Check the target and the username segments |
ProxyError during the handshake, such as "Connection closed unexpectedly" | Usually the SOCKS connector pointed at the HTTP port | Use the SOCKS5 port |
ClientHttpProxyError with status 429 | Rotating Unmetered at its connection limit | Lower CONCURRENCY, or add capacity |
TimeoutError under load, fine at low volume | Too many concurrent requests, or a tight connect= budget counting pool wait | Lower concurrency. Use sock_connect and sock_read |
DeprecationWarning mentioning proxy_auth or BasicAuth | aiohttp 3.14 deprecated both | Move the credentials into the proxy URL |
| The script prints your own IP | A request went out without proxy=, or trust_env=True found no variable | Set the proxy on the ClientSession |
Do not reach for ssl=False when a certificate error appears. A CONNECT proxy does not replace the destination's certificate, so a verification failure points at the destination, your CA bundle or TLS-inspecting software on your network, and ssl=False removes the check that protects the connection.
A request that succeeds through the proxy and still gets a 403 or a CAPTCHA is the target judging the address or the request, not a configuration fault. Why is my IP getting blocked covers that side.
Client or server: "aiohttp proxy server"
Everything on this page is the client side: aiohttp connecting to a proxy server. aiohttp also ships a server framework, aiohttp.web, and people use it to write small reverse proxies that forward incoming requests to a backend. That is a different job from scraping through a proxy pool, and it does not give your outgoing requests a different IP address. To change where your requests appear to come from, you need a proxy server with its own exit addresses, and the client code above to reach it.
Confirm the proxy is applied
The check worth trusting is the address the destination reports. Run it with the same session configuration your application uses:
import asyncio
import ipaddress
import aiohttp
PROXY = "http://USERNAME:PASSWORD@HOST:PORT"
async def egress_ip(session: aiohttp.ClientSession, **kwargs) -> str:
async with session.get("https://api.ipify.org", **kwargs) as resp:
body = (await resp.text()).strip()
if resp.status != 200:
raise RuntimeError(f"HTTP {resp.status}: {body[:80]}")
ipaddress.ip_address(body) # raises ValueError if the body is not an IP
return body
async def main() -> None:
async with aiohttp.ClientSession() as session:
direct = await egress_ip(session)
proxied = await egress_ip(session, proxy=PROXY)
print(f"direct: {direct}")
print(f"proxied: {proxied}")
if direct == proxied:
raise RuntimeError("traffic is not leaving through the proxy")
asyncio.run(main())Expected output is two different addresses. For SOCKS5, build the second session with the ProxyConnector and compare the same way. On a rotating gateway the proxied address changes between runs, which is the product working.
Using requests or httpx instead of aiohttp? Python requests proxy setup covers both. Still choosing a product for this code? SOCKS5 proxies for aiohttp: which proxy type to use matches rotating, residential, dedicated and shared proxies to the jobs aiohttp usually does, and datacenter proxies are the fixed-address option when a list suits you better than a gateway.