Skip to content

How to use a proxy with Python aiohttp

aiohttp is Python's async-first HTTP client, and it takes a proxy URL per request or per session. This guide shows how to use it with an authenticated residential proxy, choose rotating or sticky IPs, target countries, add SOCKS5 with aiohttp-socks, and handle proxy errors in concurrent code.

Updated 9 November 2026

Prerequisites

  • Python 3.10+ and pip install aiohttp (examples use 3.14); pip install aiohttp-socks for SOCKS5.
  • A proxy login from the dashboard under Logins, written as USER and PASS.

Common uses: high-volume monitoring of public pages and APIs, localized checks across many regions, and data collection pipelines.

Basic HTTP proxy

Pass proxy= to a request, or set a default on ClientSession(proxy=...) in recent 3.x releases. aiohttp supports HTTP proxies and tunnels HTTPS targets through them with CONNECT. Keep the proxy URL's scheme as http://; aiohttp's support for https:// proxy URLs is limited.

import asyncio
import aiohttp

PROXY = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

async def main():
    timeout = aiohttp.ClientTimeout(total=30)
    async with aiohttp.ClientSession(timeout=timeout) as session:
        async with session.get("https://api.ipify.org", proxy=PROXY) as r:
            print(await r.text())

asyncio.run(main())

Authentication

Put the credentials in the proxy URL. aiohttp also has a proxy_auth=aiohttp.BasicAuth(...) argument, but current docs mark it as deprecated and due for removal in 4.0, so prefer the URL form (or proxy_headers with a Proxy-Authorization header).

Unlike requests, aiohttp ignores HTTP_PROXY and HTTPS_PROXY unless you create the session with trust_env=True.

Rotating vs sticky IPs

The gateway rotates per connection. aiohttp's connector keeps connections alive, so requests to the same host can reuse one exit. For a new IP on every request, create the connector with force_close=True. To hold an IP on purpose, add a session id to the username (5 minutes by default, up to 120 with ttl). The session id is part of the URL, so you can mix sticky and rotating requests in one ClientSession.

import asyncio
import aiohttp

PROXY = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

async def main():
    # force_close: no keep-alive, so every request is a new connection and a new exit
    connector = aiohttp.TCPConnector(force_close=True)
    async with aiohttp.ClientSession(connector=connector) as session:
        for _ in range(3):
            async with session.get("https://api.ipify.org", proxy=PROXY) as r:
                print(await r.text())

asyncio.run(main())

Country and city targeting

UsernameExit
USER-cc-gbUnited Kingdom
USER-cc-us-city-new_yorkNew York
USER-cc-us-region-californiaCalifornia
USER-cc-de-asn-3320One German network
USER-cont-euAnywhere in Europe
USER-cc-us-city-houston-strict-falseHouston, or elsewhere in the US

Because the proxy is chosen per request, one session can query several countries at once. Full option list: Targeting.

SOCKS5

aiohttp has no built-in SOCKS support. aiohttp-socks provides a connector; with rdns=True hostnames are resolved by the proxy, like socks5h in other tools. The proxy is then set on the connector, not per request.

python
# pip install aiohttp-socks
import asyncio
import aiohttp
from aiohttp_socks import ProxyConnector

async def main():
    connector = ProxyConnector.from_url(
        "socks5://USER-cc-de:PASS@gw.hyperproxy.io:8888",
        rdns=True,  # resolve hostnames on the proxy side (the socks5h behaviour)
    )
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.get("https://api.ipify.org") as r:
            print(await r.text())

asyncio.run(main())

Concurrency

Share one ClientSession across tasks, and bound concurrency with the connector's limit and limit_per_host (or a semaphore). Always read or release the response body so connections return to the pool. Keep rates polite; proxies don't change a site's rate limits.

python
import asyncio
import aiohttp

PROXY = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888"

async def fetch(session: aiohttp.ClientSession, url: str) -> int:
    async with session.get(url, proxy=PROXY) as r:
        await r.read()
        return r.status

async def main():
    urls = [f"https://example.com/page/{i}" for i in range(200)]
    connector = aiohttp.TCPConnector(limit=20, limit_per_host=5)  # caps open connections
    timeout = aiohttp.ClientTimeout(total=60)
    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
        results = await asyncio.gather(*(fetch(session, u) for u in urls), return_exceptions=True)
    print(results)

asyncio.run(main())

Error handling and retries

For HTTPS targets the gateway answers the CONNECT, and aiohttp raises aiohttp.ClientHttpProxyError with .status set to the gateway status. Plain HTTP targets return a normal response with that status. See Errors:

  • 407: wrong login, an invalid or repeated option, or no balance. Don't retry.
  • 404: no exit matches the targeting; widen it or add strict-false.
  • 403: the target is not allowed. 400: a malformed request.
  • 429: back off. 502 / 504: retry, with a new exit unless the request is sticky.
python
import asyncio
import aiohttp

RETRYABLE = {429, 502, 504}
FATAL = {400, 403, 404, 407}

async def get(session: aiohttp.ClientSession, url: str, proxy: str, attempts: int = 4) -> str:
    for attempt in range(attempts):
        try:
            async with session.get(url, proxy=proxy) as r:
                if r.status not in RETRYABLE:
                    r.raise_for_status()
                    return await r.text()
        except aiohttp.ClientHttpProxyError as e:
            # the gateway refused CONNECT; e.status is its status code
            if e.status in FATAL:
                raise
        except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
            pass
        await asyncio.sleep(2 ** attempt)  # without a session, the retry gets a new exit
    raise RuntimeError(f"gave up on {url}")

Verify the exit IP

Fetch https://api.ipify.org through the proxy. The rotating example prints a new IP each time; the sticky example repeats one IP.

Troubleshooting

  • ClientHttpProxyError 407: check credentials and the spelling of every option.
  • The proxy is ignored: you relied on environment variables without trust_env=True.
  • "Unclosed client session" warnings: use async with for sessions and responses.
  • Same IP everywhere: connection reuse; use force_close=True or per-request session ids.
  • SOCKS URL rejected: proxy= only accepts HTTP proxies; use aiohttp-socks.

FAQ

Can I use different proxies in one ClientSession?

Yes, for HTTP proxies: pass a different proxy= per request. Connections are pooled per proxy, so they don't mix.

Is aiohttp faster than httpx?

For large async workloads aiohttp is often a bit faster, but through a residential proxy the network dominates. See the httpx guide if you also need sync code.

Does aiohttp verify TLS through the proxy?

Yes. The TLS session runs end to end with the target inside the tunnel, and certificates are verified as usual.

Where are more examples?

See Examples and the Python requests guide.

Try it on your own workload

Sign up with GitHub or Google, create a proxy login and send your first request in a minute.

More proxy integration guides

  • Python requests — Rotating and sticky residential proxies with Python requests, including SOCKS5 and retries.
  • Python httpx — Sync and async httpx through a residential proxy with the proxy= argument and SOCKS5.
  • Scrapy — Route Scrapy spiders through residential proxies with request.meta and a middleware.
  • Playwright — Run Playwright through residential proxies, per browser or per context, with sticky sessions.
  • Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
  • Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
  • Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
  • Node.js fetch & undici — Use Node's built-in fetch with undici ProxyAgent or NODE_USE_ENV_PROXY.
  • Go net/http — Configure Go's http.Transport for HTTP and SOCKS5 residential proxies.
  • curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.