Scraping and automation libraries

How to use a proxy with Python requests

Requests is the most widely used HTTP library for Python and the usual starting point for scrapers, price checkers and API clients. It takes a proxy through a proxies dictionary that maps each target scheme to a proxy URL with your username and token inside.

This guide covers the dictionary format that trips people up, sessions that keep one IP, SOCKS5 with remote DNS, retries, and the same setup in httpx and aiohttp for async code.

Updated 23 November 2026

What you need
Hostgate.firstproxy.shop
HTTP / HTTPS port8000
SOCKS5 port9000
Usernameuser-country-us
PasswordYOUR_TOKEN

Requests supports HTTP on port 8000 out of the box, and SOCKS5 on port 9000 after installing requests[socks]. Your username and token appear on the Proxy setup page of your dashboard after your first order.

Setup

How do I connect Python requests to a proxy?

Follow the steps in order. Replace YOUR_TOKEN with the token from your dashboard and change the country, city or session in the username to suit the job.

  1. Install requests

    Use a virtual environment so the project keeps its own versions. The socks extra installs PySocks and is only needed for SOCKS5.

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

    Both keys of the dict point to the same http:// proxy URL. The key is the scheme of the site you request, and the value is how to reach the proxy. Writing https:// in the value makes urllib3 try TLS to the proxy itself and usually ends in an SSL error.

    import requests
    
    proxy = "http://user-country-us:YOUR_TOKEN@gate.firstproxy.shop:8000"
    proxies = {"http": proxy, "https": proxy}
    
    resp = requests.get("https://ipinfo.io/json", proxies=proxies, timeout=(10, 30))
    print(resp.status_code, resp.json())
  3. Build the username for country and city

    Keep the targeting in code so each job can change it. City values are lowercase with hyphens. Encode the token with quote if you ever rotate to one with special characters.

    from urllib.parse import quote
    
    HOST, PORT, TOKEN = "gate.firstproxy.shop", 8000, "YOUR_TOKEN"
    
    def proxy_url(country, city=None, session=None, ttl=None):
        user = f"user-country-{country}"
        if city:
            user += f"-city-{city}"
        if session:
            user += f"-session-{session}-ttl-{ttl or 10}m"
        return f"http://{user}:{quote(TOKEN, safe='')}@{HOST}:{PORT}"
    
    p = proxy_url("us", city="chicago")
    print(requests.get("https://ipinfo.io/json", proxies={"http": p, "https": p}).json())
  4. Keep one IP across requests with a session

    A sticky session name plus a requests.Session keeps both the IP and the cookies, which is what logins and multi-page flows need. Pass proxies= on each call: if an HTTPS_PROXY environment variable is set, it overrides session.proxies because of how requests merges settings.

    import uuid
    import requests
    
    sid = uuid.uuid4().hex[:8]
    p = proxy_url("de", session=sid, ttl=30)
    proxies = {"http": p, "https": p}
    
    with requests.Session() as s:
        for _ in range(3):
            r = s.get("https://ipinfo.io/ip", proxies=proxies, timeout=(10, 30))
            print(r.text.strip())   # same IP three times
  5. Switch to SOCKS5

    After installing the socks extra, use port 9000 and the socks5h:// scheme. The h tells requests to let the proxy resolve hostnames, so no DNS lookup leaves from your own network.

    p = "socks5h://user-country-jp:YOUR_TOKEN@gate.firstproxy.shop:9000"
    r = requests.get("https://ipinfo.io/json", proxies={"http": p, "https": p}, timeout=30)
    print(r.json())
  6. Add retries and use the same proxy in httpx or aiohttp

    Mount an adapter with urllib3 Retry for temporary errors. For async code, httpx takes a single proxy= argument (the older proxies= was removed in httpx 0.28), and aiohttp takes proxy= per request.

    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
    
    s = requests.Session()
    retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
    s.mount("https://", HTTPAdapter(max_retries=retry))
    s.mount("http://", HTTPAdapter(max_retries=retry))
Test

How do I check that the proxy works?

Print the JSON from ipinfo.io. The country and city should match your username, and the IP should differ from the one you get without the proxy.

A working proxy returns a response like the one shown, trimmed to the main fields. The IP belongs to the exit, the city and country follow your username, and the time zone is where that IP is located, here United States.

p = proxy_url("us", city="new-york")
print(requests.get("https://ipinfo.io/json", proxies={"http": p, "https": p}, timeout=30).json())
ipinfo.io/json response
{
  "ip": "203.0.113.24",
  "city": "New York",
  "country": "US",
  "timezone": "America/New_York"
}

203.0.113.24 is a documentation address. Your result shows a real exit IP.

Targeting

How do I set country, city and session in the username?

All targeting is written into the username, so Python requests needs no extra settings to change location. Parts are joined with hyphens in this order after your proxy user. The password is always your token.

Proxy username parts
PartFormatExampleRule
Country-country-{cc}-country-usRequired. Two-letter country code in lowercase. 64 countries are available.
City-city-{city}-city-new-yorkOptional. City name in lowercase, spaces become hyphens. 172 cities are available.
Session-session-{id}-session-a1b2c3Optional. Any letters and digits you choose. The same id keeps the same IP, a new id gets a new IP.
Session length-ttl-{minutes}m-ttl-30mUsed with a session. Residential 1 to 120 minutes, mobile 1 to 60, long-acting ISP up to 720 (12 hours).
Full usernameuser-country-us-city-new-york-session-a1b2c3-ttl-30m

Find country codes and city values on the proxy locations page.

Troubleshooting

Python requests proxy errors and fixes

The problems people run into most often with Python requests, with the message you are likely to see and how to solve it.

ProxyError: Tunnel connection failed: 407 Proxy Authentication Required

The token or username is wrong, or a special character in the token broke the URL. Copy the token again and wrap it in quote(token, safe=""). Make sure there are no spaces or line breaks at the end of values read from environment files.

SSLError or wrong version number

The proxy URL starts with https://. Change it to http:// for both keys of the dict. HTTPS sites are still encrypted, because requests opens a CONNECT tunnel and does TLS with the target.

Requests go out from my own IP

The dict key is missing for the scheme you request. A dict with only "http" does not proxy https:// URLs. Set both keys, and check that NO_PROXY does not list the target domain.

ConnectTimeout or ReadTimeout

Always pass a timeout, for example timeout=(10, 30) for connect and read. Requests has no default timeout and can wait forever. Retry with a new session name if one exit stays slow.

InvalidSchema: Missing dependencies for SOCKS support

Install requests[socks] in the same environment that runs the script. Check with python -m pip show pysocks.

A rotating username keeps the same IP

A Session reuses open connections, and a reused tunnel keeps its exit IP. Use requests.get without a session, or a new session name per task, when you need a fresh IP each time.

FAQ

Python requests proxy questions

Short answers to what people ask most about using a proxy with Python requests.

How do I set a proxy in Python requests?

Create a dict with the keys http and https that both point to http://username:YOUR_TOKEN@gate.firstproxy.shop:8000, then pass it as proxies= to requests.get or to each Session call.

Should the https key use an https:// proxy URL?

No. The key is the scheme of the target site, the value is how to reach the proxy. Use http:// for both. HTTPS pages are still encrypted end to end through a CONNECT tunnel.

How do I use SOCKS5 with requests?

Install requests[socks], then use socks5h://username:YOUR_TOKEN@gate.firstproxy.shop:9000 for both keys. The socks5h scheme makes the proxy resolve DNS, while socks5 resolves names on your machine.

Why is session.proxies ignored?

Requests merges environment proxy variables after session.proxies, so a set HTTPS_PROXY variable wins. Pass proxies= on each request, or set session.trust_env = False to ignore the environment.

How do I rotate IPs with requests?

Use a username without a session part and avoid reusing connections, so each request leaves from a new IP. For a fixed IP per task, generate a session name with uuid and add a ttl.

Get your token and run the first Python requests request

Create an account, top up from $40 with crypto, and copy the gateway, username and token from the dashboard.