Tutorials

How to Use a Proxy with Python HTTPX

By IPMusk TeamUpdated 3 min read

Pass a single proxy= URL to httpx.Client or httpx.AsyncClient (replacing the old proxies= argument removed in HTTPX 0.28.0), or map per-scheme and bypass rules through mounts= using HTTPTransport and AsyncHTTPTransport. Keep http:// proxy endpoints under the https:// mount key for CONNECT tunnels, install httpx[socks] for SOCKS5, route high-volume fetches through Rotating Residential and stateful APIs through Static ISP, and bound Timeout, Limits, and trust_env explicitly.

IPMusk Python HTTPX proxy guide diagram showing sync Client and async AsyncClient proxy= and mounts= routing, Rotating Residential vs. Static ISP selection, and pool limits, timeouts, and HTTP 407 isolation
Python HTTPX proxy architecture: route sync Client and async AsyncClient via proxy= or mounts=, split Rotating Residential vs. Static ISP lines, and bound connection limits, timeouts, and 407 errors.

Pass proxy= to Client and AsyncClient

HTTPX routes both HTTP and HTTPS requests through a proxy via the proxy= parameter on httpx.Client, httpx.AsyncClient, or top-level helpers such as httpx.get(..., proxy=...). Note that HTTPX 0.28.0 removed the deprecated proxies= argument, so scripts and dependencies pinned to older examples raise TypeError unless updated to proxy= or mounts=.

Always open Client or AsyncClient in a context manager so connection pools close cleanly, read credentials from environment variables, and set trust_env=False when you do not want shell HTTP_PROXY or HTTPS_PROXY variables overriding explicit routing:

  • Embed username and password in the URL userinfo segment (http://USERNAME:PASSWORD@HOST:PORT). IPMusk authenticates proxy connections by username and password only; IP allowlisting is not supported.
  • Percent-encode special characters in passwords so URL parsing does not split on @ or :.
  • If you need SOCKS5 with HTTPX, install the optional extra first (pip install httpx[socks]) and switch the scheme to socks5://USERNAME:PASSWORD@HOST:PORT.
Python: sync httpx.Client and async httpx.AsyncClient with proxy= (syntax checked)
import asyncio
import os
import httpx

PROXY_URL = os.environ.get(
    "IPMUSK_PROXY_URL",
    "http://USERNAME:PASSWORD@gate.ipmusk.com:31212",
)

# 1) Synchronous Client
with httpx.Client(
    proxy=PROXY_URL,
    timeout=httpx.Timeout(10.0, connect=5.0),
    limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
    trust_env=False,
) as client:
    response = client.get("https://api.ipmusk.com/health")
    response.raise_for_status()

# 2) Asynchronous AsyncClient
async def fetch_batch(urls: list[str]) -> list[int]:
    async with httpx.AsyncClient(
        proxy=PROXY_URL,
        timeout=httpx.Timeout(10.0, connect=5.0),
        limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
        trust_env=False,
    ) as client:
        responses = await asyncio.gather(*(client.get(url) for url in urls))
        return [resp.status_code for resp in responses]

Use mounts= for per-scheme routes and direct bypass rules

When a service needs different proxy pools by scheme or must reach internal endpoints directly without tunneling through a proxy, pass mounts= with httpx.HTTPTransport (sync) or httpx.AsyncHTTPTransport (async). Even under the https:// mount key, the proxy URL itself normally uses the http:// scheme because HTTPX opens an HTTP CONNECT tunnel to the proxy server before performing TLS to the destination.

Pass None as a mount value to bypass proxies for trusted internal hosts while routing external requests through IPMusk:

  • Match transport class to client type: Client requires httpx.HTTPTransport, while AsyncClient requires httpx.AsyncHTTPTransport.
  • Transport retries= handles low-level connection establishment failures (connect errors and timeouts), not HTTP 407/403 status responses.
Python: mounts= with HTTPTransport bypass and AsyncHTTPTransport retry bound (syntax checked)
import os
import httpx

ipmusk_proxy = os.environ["IPMUSK_HTTP_PROXY"]

sync_mounts = {
    "http://": httpx.HTTPTransport(proxy=ipmusk_proxy),
    "https://": httpx.HTTPTransport(proxy=ipmusk_proxy),
    "https://internal.example.com": None,
}

async_mounts = {
    "all://": httpx.AsyncHTTPTransport(proxy=ipmusk_proxy, retries=1),
    "all://internal.example.com": None,
}

with httpx.Client(mounts=sync_mounts, trust_env=False) as client:
    ext_res = client.get("https://example.org")

Match Rotating Residential and Static ISP to your HTTPX workload

AsyncClient with asyncio makes it effortless to fan out hundreds of concurrent fetches, which quickly exposes any mismatch between workload behavior and proxy line type. Keep dynamic high-volume lookups separate from stateful authenticated clients:

Choosing an IPMusk proxy line for Python HTTPX clients
HTTPX workloadRecommended IPMusk productConnection & billing profile
High-concurrency public page or RAG fetches, rotating geo checksRotating Residential (from $2.99 for 1 GB Trial; down to $0.80/GB at 1,000 GB)Single gateway gate.ipmusk.com:31212 with per-request rotation or 1/3/10/30-min sticky exits; country and available state targeting
Long-lived AsyncClient cookie sessions, regional portals, webhook receiversStatic ISP (Native ISP or ISP from $3.99/IP per 30 days)Dedicated assigned IP host and port, unmetered traffic, and 30 or 90 day manual or balance-capped renewal
Permissive JSON/XML feeds and low-cost testingDatacenter (from $2.99/IP per 30 days)Lowest-cost unmetered assigned hosting-ASN IP when destinations allow datacenter ranges

Generate country or available state credential strings on your workspace Connect screen or via build_proxy_url in MCP before setting IPMUSK_PROXY_URL.

Bound Limits, Timeouts, and 407 error handling

By default HTTPX configures Limits(max_connections=100, max_keepalive_connections=20). Under asyncio bursts through a single upstream proxy endpoint, unbounded task concurrency can exhaust sockets or trigger upstream 429 throttling before HTML or JSON payloads arrive.

Always pair an explicit asyncio.Semaphore or tight httpx.Limits with bounded httpx.Timeout settings and separate 407 auth checks:

  • HTTP 407 Proxy Authentication Required: fail immediately without retrying. Validate host, port, and credentials with /tools/proxy-checker or see /blog/proxy-error-407.
  • HTTP 403 Forbidden or TLS resets on permissive proxies: confirm target compatibility before increasing concurrency, and check /blog/proxy-403-forbidden for root-cause triage.
  • HTTP 429 Too Many Requests: honor Retry-After headers in application code and reduce asyncio.Semaphore concurrency (/blog/proxy-429-too-many-requests) instead of multiplying transport retries.
  • Before large batches, keep client.get() errors isolated with try/except httpx.ProxyError and httpx.TimeoutException so partial failures log clearly without dropping clean records.

Sources checked

All HTTPX documentation pages, source files, and IPMusk pricing/tool URLs verified HTTP 200 on December 5, 2026.