How to Test an HTTP Proxy with Python HTTPX
Published
Set one explicit proxy for the test
Install HTTPX with the Python interpreter you use for your application. This example uses the proxy parameter available in HTTPX 0.28. It sends one HTTPS GET through an approved HTTP proxy and reports the status and the IP seen by the destination.
python -m pip install httpx
export PROXY_TEST_URL='http://gateway.example:8080'
Replace the sample gateway with the endpoint your operator provided. In PowerShell, set the variable with $env:PROXY_TEST_URL = 'http://gateway.example:8080'. For an approved proxy that requires a password, load the URL from your normal secret mechanism. HTTPX supports credentials in the proxy URL. Keep the populated value out of logs and commit history. HTTPX proxy configuration.
Verify the route with AsyncClient
Save the script as test-httpx-proxy.py and run python test-httpx-proxy.py. Use the TestMyProxies IP endpoint if allowed by your network, or use your own HTTPS test endpoint that returns an ip field. For a managed test environment that uses a specific trusted CA bundle, set PROXY_TEST_CA to the approved PEM file.
import asyncio
from ipaddress import ip_address
import os
import ssl
import httpx
TARGET = "https://testmyproxies.com/api/my-ip"
async def check_proxy():
proxy_url = os.environ.get("PROXY_TEST_URL")
if not proxy_url:
raise SystemExit("Set PROXY_TEST_URL to your approved proxy URL.")
ca_file = os.environ.get("PROXY_TEST_CA")
verify = ssl.create_default_context(cafile=ca_file) if ca_file else True
timeout = httpx.Timeout(10.0, connect=5.0)
async with httpx.AsyncClient(
proxy=proxy_url, trust_env=False, verify=verify, timeout=timeout
) as client:
try:
response = await client.get(TARGET)
except httpx.ProxyError:
raise SystemExit("Proxy negotiation failed. Check the proxy settings.") from None
except httpx.TimeoutException:
raise SystemExit("The proxy test timed out.") from None
except httpx.RequestError:
raise SystemExit("Request failed. Check DNS, reachability and TLS.") from None
if response.status_code != 200:
raise SystemExit(f"Target returned HTTP {response.status_code}.")
try:
payload = response.json()
if not isinstance(payload["ip"], str):
raise ValueError("IP needs to be a string")
exit_ip = ip_address(payload["ip"])
except (ValueError, KeyError, TypeError):
raise SystemExit("Target did not return a valid IP address.") from None
print(f"Target HTTP {response.status_code}, exit IP {exit_ip}")
if __name__ == "__main__":
asyncio.run(check_proxy())
trust_env=False makes the comparison use the explicit proxy and avoids ambient settings such as HTTPS_PROXY, NO_PROXY and SSL_CERT_FILE. Certificate verification stays enabled. For troubleshooting an existing application, also check how its real client is configured. A client using environment defaults can take a different route. HTTPX environment settings · HTTPX asynchronous clients.
Use the failing stage to choose the next check
- Proxy negotiation failed. Check the gateway, port and authentication settings. If the gateway is an HTTP proxy, cURL can show whether CONNECT returned 407. Display CONNECT and destination statuses.
- Request failed or timed out. Check DNS, TCP reachability and the certificate in the same Python environment. Run the same HTTPS request through the same endpoint in cURL to isolate the client configuration.
- A target status such as 403. The destination replied. Check the policy for that URL and compare it with the result from a known permitted endpoint.
- HTTP 200 and a valid IP. Compare the exit IP with the address or range you expected. The exit IP can match another route when both use the same public egress. Use the gateway’s connection log when you need to confirm the route.
If your application uses the synchronous Requests library, follow the Requests proxy test for that client. For a network-wide problem, work through the DNS, port and HTTPS checks from the same machine.