NewUnlimited residential proxies: unmetered traffic on a fixed price. From $33.25/day

Python ยท Integration guide

How to use proxies with Python Requests

Requests only needs a proxies dictionary to send traffic through Proxonym. This guide covers authentication, location targeting, rotating and sticky IPs, SOCKS5 and retries for gateway errors.

  • 6 steps
  • 12 min setup
  • Copy-paste code

Before you start

  • Python 3.10 or newer
  • Requests 2.x, plus the socks extra for SOCKS5
  • A Proxonym residential or mobile plan
Get proxy credentials

Already a customer? Your username and password are in the dashboard.

  1. Install Requests

    Install Requests with pip. The socks extra pulls in PySocks, which you only need for the SOCKS5 endpoint.

    Shell
    python -m pip install requests
    python -m pip install "requests[socks]"   # only for SOCKS5
  2. Send a request through the gateway

    Put your credentials in the proxy URL and use it for both the http and https keys. HTTPS targets are tunneled with CONNECT, so the proxy URL itself keeps the http:// scheme.

    Python
    import requests
    
    PROXY = "http://USERNAME:[email protected]:8000"
    proxies = {"http": PROXY, "https": PROXY}
    
    response = requests.get("https://api.ipify.org", proxies=proxies, timeout=60)
    print("Exit IP:", response.text)
  3. Target a country, state, city or ASN

    This helper builds the username from keyword arguments in the order the gateway expects. Use lowercase ISO country codes and underscores for spaces, and choose a state or a city, not both.

    Python
    import requests
    
    
    def proxy_for(**params):
        """proxy_for(country="us", city="new_york", session="a7k2", lifetime=30)"""
        user = "USERNAME"
        for key in ("country", "state", "city", "asn", "session", "lifetime"):
            if key in params:
                user += f"-{key}-{params[key]}"
        url = f"http://{user}:[email protected]:8000"
        return {"http": url, "https": url}
    
    
    for proxies in (
        proxy_for(country="us", city="new_york"),
        proxy_for(country="de", state="bavaria"),
        proxy_for(country="us", asn=7922),
    ):
        info = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=60).json()
        print(info["ip"], info.get("city"), info.get("country"))
  4. Rotate or keep the same IP

    With no session parameter, every new connection gets a new IP, and requests.get() opens a new connection on each call. Reusing proxy_for() from the previous step, add a session ID of up to 32 letters and digits to keep one IP for up to 120 minutes.

    Python
    import secrets
    
    import requests
    
    # Rotating: a new exit IP on every call
    for _ in range(3):
        print(requests.get("https://api.ipify.org", proxies=proxy_for(country="us"), timeout=60).text)
    
    # Sticky: the same exit IP for up to 30 minutes
    sticky = proxy_for(country="us", session=secrets.token_hex(4), lifetime=30)
    for _ in range(3):
        print(requests.get("https://api.ipify.org", proxies=sticky, timeout=60).text)
  5. Use the SOCKS5 endpoint

    With PySocks installed, point both keys at port 1080. The socks5h:// scheme resolves hostnames on the proxy side, which keeps DNS lookups off your own network.

    Python
    import requests
    
    PROXY = "socks5h://USERNAME-country-gb:[email protected]:1080"
    proxies = {"http": PROXY, "https": PROXY}
    
    print(requests.get("https://api.ipify.org", proxies=proxies, timeout=60).text)
  6. Retry gateway errors

    Mount a retry policy for transient failures and catch ProxyError, which Requests raises when the gateway refuses a tunnel. Retries will not fix a 407, 402 or 403, so correct the credentials, balance or target first.

    Python
    import requests
    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
    
    retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 502, 504])
    session = requests.Session()
    session.mount("http://", HTTPAdapter(max_retries=retry))
    session.mount("https://", HTTPAdapter(max_retries=retry))
    
    PROXY = "http://USERNAME-country-us:[email protected]:8000"
    proxies = {"http": PROXY, "https": PROXY}
    
    try:
        response = session.get("https://example.com", proxies=proxies, timeout=(10, 60))
        response.raise_for_status()
        print(response.status_code, len(response.text))
    except requests.exceptions.ProxyError as exc:
        # The message includes the gateway status, for example 407 or 502
        print("Gateway refused the tunnel:", exc)
    except requests.exceptions.RequestException as exc:
        print("Request failed:", exc)

Frequently asked questions

Why does Requests fail with Tunnel connection failed: 407?

The gateway rejected the credentials in your proxy URL. Copy the username and password again from the dashboard, join targeting parameters with dashes, and URL-encode any special characters in the password. If the same code works on one machine but not another, look for an HTTPS_PROXY environment variable that overrides your settings.

Does Requests support SOCKS5 proxies?

Yes, once you install the socks extra with pip install "requests[socks]", which adds PySocks. Use socks5h://USERNAME:[email protected]:1080 so hostnames resolve on the proxy side. Targeting and session parameters work the same as on the HTTP endpoint, so you can switch protocols without changing the username.

How do I send many requests in parallel?

Requests is synchronous, so run calls in a ThreadPoolExecutor or move to an async client such as httpx or aiohttp. Proxonym allows unlimited concurrent sessions with a per-account burst limit of around 10,000 requests per second, so the practical ceiling is usually the target site. Give each worker its own session ID when it needs a stable IP.

Can I use httpx or aiohttp instead of Requests?

Yes. In httpx, pass proxy="http://USERNAME:[email protected]:8000" when you create a Client or AsyncClient. In aiohttp, pass the same URL as the proxy argument of each request. Both libraries pool connections, so requests that reuse a connection keep the same exit IP until it closes.

Ready to plug it in? Get your credentials.

Pick a plan, copy your username and password from the dashboard and run the code above.

  • Pay as you go
  • Instant activation
  • Crypto accepted
  • 24/7 support