httpx proxy setup with authentication and rotation

Use RotatingProxy with httpx by setting the proxy mount for HTTP and HTTPS traffic. The gateway host is gw.rotatingproxy.cc, using port 7070 for HTTP/HTTPS and port 7071 for SOCKS5.

Key points
  • Set the proxy mount for HTTP and HTTPS separately in httpx.
  • Add options for country, city, network, and session to the username.
  • Connect using port 7070 for HTTP/HTTPS or port 7071 for SOCKS5.
  • Verify the exit IP with a service like ipify or ipinfo.

httpx proxy configuration basics

The httpx library uses a mounts dictionary on the client to define proxies for different URL schemes. You must mount proxies for both http:// and https:// schemes to ensure all traffic from that client goes through the proxy gateway. The base proxy URL includes the authentication credentials, gateway host, and port.

Setting the HTTP proxy mount on port 7070

Create an httpx client with a proxy mount for the HTTP and HTTPS schemes using port 7070. The proxy URL format is http://USERNAME:PASSWORD@gw.rotatingproxy.cc:7070. Below is a full synchronous client example:

import httpx

proxy_url = "http://USERNAME:PASSWORD@gw.rotatingproxy.cc:7070"
proxies = {
    "http://": proxy_url,
    "https://": proxy_url,
}

with httpx.Client(proxies=proxies) as client:
    response = client.get("http://httpbin.org/ip")
    print(response.json())

For an asynchronous client, use httpx.AsyncClient with the same proxy mount structure. This setup is essential for tasks like web scraping where you need to route all requests through the proxy network.

Using the SOCKS5 proxy on port 7071

httpx supports SOCKS5 proxies through an optional dependency. Start by installing the package: pip install httpx[socks]. Then, use port 7071 and the socks5:// scheme in your proxy URL. The SOCKS5 proxy also requires authentication in the URL.

import httpx

proxy_url = "socks5://USERNAME:PASSWORD@gw.rotatingproxy.cc:7071"
proxies = {
    "http://": proxy_url,
    "https://": proxy_url,
}

with httpx.Client(proxies=proxies) as client:
    response = client.get("https://api.ipify.org?format=json")
    print(response.json())

If you do not install the socks extra, httpx will raise an ImportError. Check the current httpx documentation for any changes in SOCKS support. For many use cases, the HTTP proxy port 7070 is sufficient and avoids the extra dependency.

Passing targeting and session options in the username

All targeting and session control is done through the username field of the proxy URL. Your proxy user's login is combined with options like network, country, city, and session ID, joined by underscores.

username = "zq4k8m2tva_net.mob_cc.de_city.berlin_sid.a7k2m9_ttl.20"
proxy_url = f"http://{username}:PASSWORD@gw.rotatingproxy.cc:7070"

You can target a US state by adding st.ca (for California) when the country is set to cc.us. For a full reference on username grammar, see the username options documentation. This method is consistent across all our integrations, like the Python requests proxy.

Verifying the exit IP and location

After configuring the client, verify that your requests are exiting from the expected IP and location. Use a simple IP checking service within your code. The ipify API returns plain text or JSON.

import httpx

proxy_url = "http://USERNAME_net.res_cc.us:PASSWORD@gw.rotatingproxy.cc:7070"
proxies = {"all://": proxy_url}  # Shorthand for http and https

with httpx.Client(proxies=proxies) as client:
    resp = client.get("https://api.ipify.org?format=json", timeout=10.0)
    print("Exit IP:", resp.json()["ip"])
    # For more details like city, use ipinfo
    # resp2 = client.get("https://ipinfo.io/json", timeout=10.0)
    # print(resp2.json())

If the IP does not match your targeted country, double-check the cc. option in the username.

Fixing common httpx proxy errors

A 407 Proxy Authentication Required error indicates the proxy did not accept your login. Ensure the username string is correctly formatted with underscores and that the proxy user is active and allowed to use the chosen network. Also confirm the password is correct. Detailed help is at proxy error 407.

Increase the timeout on your httpx client or individual requests. Set a reasonable connect and read timeout, and implement a retry logic.

client = httpx.Client(
    proxies=proxies,
    timeout=httpx.Timeout(connect=10.0, read=30.0)
)

TLS errors through a proxy are rare but can happen if the target server uses an outdated cipher. Httpx uses the system's CA certificates by default. If you encounter SSL errors, you can try disabling verification as a last resort for testing (verify=False), but this is not recommended for production.

Running httpx at scale with rotating proxies

For large-scale crawling, create multiple client instances with different session IDs to distribute traffic across IPs. Use a pool of proxy user logins, each with its own monthly GB cap set in the dashboard, to segment and control costs.

import asyncio
import httpx

async def fetch(url, session_id):
    username = f"USERNAME_sid.{session_id}"
    proxy_url = f"http://{username}:PASSWORD@gw.rotatingproxy.cc:7070"
    proxies = {"all://": proxy_url}
    async with httpx.AsyncClient(proxies=proxies) as client:
        response = await client.get(url)
        return response.text

async def main():
    urls = ["https://example.com/page1", "https://example.com/page2"]
    tasks = [fetch(url, f"sid{i}") for i, url in enumerate(urls)]
    results = await asyncio.gather(*tasks, return_exceptions=True)
    # Process results

Monitor your traffic usage in the dashboard to stay within budget and benefit from automatic volume discounts explained in how monthly volume rates are applied. For planning concurrent workloads, read our guide on planning concurrency for crawlers.

Async httpx client with proxy mounts

The async client configuration is identical to the sync client, but you use httpx.AsyncClient within an async context. This is ideal for high-performance scraping where you can make many requests concurrently without blocking.

import asyncio
import httpx

async def check_ip():
    proxy_url = "http://USERNAME:PASSWORD@gw.rotatingproxy.cc:7070"
    proxies = {"all://": proxy_url}
    async with httpx.AsyncClient(proxies=proxies) as client:
        resp = await client.get("https://api.ipify.org")
        print(resp.text)

asyncio.run(check_ip())

When using async, be mindful of rate limits on target sites to avoid overwhelming them. Implement delays and respect robots.txt as outlined in our web scraping best practices.

Switching between proxy networks

You can switch between residential, mobile, datacenter, and ISP networks by changing the net. option in the username. Each network has different characteristics, coverage, and pricing. For example, net.dc uses datacenter IPs available in 16 countries, while net.mob uses mobile carrier IPs from 87 countries. Choose based on your needs for residential vs datacenter rotating proxies.

Using the shorthand "all://" proxy mount

Httpx accepts the special scheme "all://" to apply the same proxy URL to both HTTP and HTTPS requests. This can make your code cleaner. However, ensure you are not mixing different proxy configurations unintentionally.

proxy_url = "http://USERNAME_net.isp_cc.gb:PASSWORD@gw.rotatingproxy.cc:7070"
proxies = {"all://": proxy_url}
client = httpx.Client(proxies=proxies)

This shorthand works for both sync and async clients. It is functionally equivalent to mounting the same URL for both http:// and https://.

Integrating with web scraping frameworks

You can use an httpx client as the transport within larger scraping frameworks. For example, you could pass a configured client to a parser library. The principles of proxy mounting remain the same. For dedicated framework guides, see Scrapy proxy or Playwright Python proxy.

When building a project like a price tracker with Python and rotating proxies, httpx offers a good balance of speed and simplicity. Always cache responses and compress data where possible to reduce proxy traffic, as explained in how to reduce proxy traffic costs.

Questions

Can I use httpx with a proxy for both http and https sites?

Yes, you must mount the proxy for both the "http://" and "https://" schemes in the client's proxies dictionary. Using the "all://" shorthand is a convenient way to apply the same proxy to all schemes.

Why is my httpx request returning a 407 error with RotatingProxy?

A 407 error indicates the proxy authentication failed. Check that your username string is correctly formatted with underscores, the proxy user is not paused, and the password is correct. Also verify the user is allowed on the network specified (e.g., net.res).

Does httpx support SOCKS5 proxy authentication?

Yes, but you need to install the socks extra with `pip install httpx[socks]`. Then you can use the scheme "socks5://" with the gateway host, port 7071, and your credentials in the URL.

How can I ensure every httpx request uses a different IP?

Omit the `sid` (session ID) option from your username. Without a session ID, each new connection to the gateway will receive a new IP address from the chosen network and location.

How can I target a specific city like London with httpx?

Include the city option in your username, for example `city.london`. Ensure the city token is lowercase and uses hyphens for spaces (e.g., `city.new-york`). Check the dashboard for the list of available cities.

My httpx requests are timing out through the proxy, what should I do?

Increase the timeout on your httpx client. Set separate connect and read timeouts. Also, check your own network connection to the gateway. If the target site is generally slow, implement a retry strategy with exponential backoff.

Start with one top-up, use any network

Create an account in a minute, add $40 or more, and the same balance pays for residential, mobile, datacenter and ISP traffic.