How to Use a Proxy with Python Requests (Production-Ready Example)

To use a proxy with Python Requests, pass a proxy URL for both HTTP and HTTPS traffic. For an authenticated ColaProxy endpoint, take the gateway host, port, username, and password from your dashboard, store them outside the code, and build the proxy URL at runtime.

The example below is designed to be copied into a real project. It URL-encodes credentials, sets explicit timeouts, verifies the exit IP, and reports the most common connection failures without printing secrets.

Prerequisites

  • Python 3.9 or newer
  • The requests package
  • An active proxy endpoint and credentials from the ColaProxy dashboard
python -m pip install requests

1. Store the proxy credentials outside your code

Set these values in your terminal or deployment secret manager. Replace the placeholders with the gateway information displayed in your ColaProxy dashboard.

export PROXY_HOST="GATEWAY_HOST"
export PROXY_PORT="PORT"
export PROXY_USERNAME="YOUR_USERNAME"
export PROXY_PASSWORD="YOUR_PASSWORD"

Do not commit live proxy credentials to Git. Environment variables are sufficient for a local example; production systems should use the secret-management service provided by their hosting platform.

2. Create a reusable Requests session

import os
from urllib.parse import quote

import requests
from requests.exceptions import ProxyError, SSLError, Timeout, RequestException


def required_env(name: str) -> str:
    value = os.getenv(name)
    if not value:
        raise RuntimeError(f"Missing required environment variable: {name}")
    return value


host = required_env("PROXY_HOST")
port = required_env("PROXY_PORT")
username = quote(required_env("PROXY_USERNAME"), safe="")
password = quote(required_env("PROXY_PASSWORD"), safe="")

proxy_url = f"http://{username}:{password}@{host}:{port}"

session = requests.Session()
session.proxies.update({
    "http": proxy_url,
    "https": proxy_url,
})
session.headers.update({
    "User-Agent": "ColaProxy-Python-Example/1.0"
})

try:
    response = session.get("https://httpbin.org/ip", timeout=(10, 30))
    response.raise_for_status()
    print("Proxy connection works. Exit IP response:", response.json())
except ProxyError as exc:
    print("Proxy connection or authentication failed:", exc)
except Timeout:
    print("The proxy or destination did not respond before the timeout.")
except SSLError as exc:
    print("TLS certificate validation failed:", exc)
except RequestException as exc:
    print("The request failed:", exc)

Although the destination uses HTTPS, the proxy URL commonly begins with http://. Requests connects to the HTTP proxy and establishes a tunnel for the HTTPS destination. Use the protocol and endpoint format shown in your provider dashboard rather than guessing from the destination URL.

3. Verify the exit IP before sending workload traffic

The first request should go to an IP-check endpoint, not directly into a crawler or production job. Confirm that the returned IP differs from your local public IP and, when you selected a location, that its geolocation matches the intended market.

For automated systems, make this a startup health check. Stop the job if authentication fails or the exit IP is unexpected. This prevents a configuration error from sending traffic directly from your server.

Python Requests Proxy: Per-Request Configuration vs Session

For one request, pass the dictionary directly:

response = requests.get(
    "https://httpbin.org/ip",
    proxies={"http": proxy_url, "https": proxy_url},
    timeout=(10, 30),
)
response.raise_for_status()

Use a Session when several requests share proxy settings, headers, or cookies. A session also reuses connections, which avoids unnecessary connection setup. Session reuse does not by itself guarantee a fixed exit IP: rotation behavior depends on the proxy product and session configuration selected in the ColaProxy dashboard.

Important: environment proxy variables can override your session

Requests reads standard environment variables such as HTTP_PROXY, HTTPS_PROXY, and NO_PROXY. Its official documentation warns that values assigned to session.proxies may be overwritten by environment proxy settings.

If your code appears to use the wrong proxy, inspect the environment first:

env | grep -i proxy

For a process that must ignore all environment-derived proxy and certificate settings, explicitly disable that behavior:

session = requests.Session()
session.trust_env = False
session.proxies.update({
    "http": proxy_url,
    "https": proxy_url,
})

Do not assume that passing an empty proxies={} always bypasses a proxy configured in the environment. Use NO_PROXY for selected hosts, or a session with trust_env = False when direct routing is intentional.

Common errors and fixes

SymptomLikely causeWhat to check
407 Proxy Authentication RequiredMissing or invalid credentialsCopy the username and password again, URL-encode special characters, and confirm that the account or plan is active.
Connection timeoutWrong host or port, unavailable endpoint, blocked destination, or slow networkVerify the dashboard endpoint, test the IP-check URL, and keep separate connect and read timeouts.
ProxyError or connection refusedThe client cannot reach the proxy gatewayCheck DNS, firewall rules, protocol, gateway hostname, and port.
SSL certificate errorLocal CA configuration, TLS interception, or an incomplete certificate chainUpdate the CA bundle and inspect the network path. Do not use verify=False as a production fix.
Unexpected exit IPEnvironment variables overrode the session, or rotation/session settings differ from expectationsInspect proxy environment variables, check trust_env, and confirm the product’s rotation settings.
Credentials fail only with special charactersThe proxy URL is malformedEncode the username and password with urllib.parse.quote(..., safe="").

Rotation and sticky sessions

ColaProxy’s public product information describes both per-request rotation and sticky-session options for dynamic residential proxies. Choose based on the task:

  • Rotation: useful when independent requests should use different exit IPs.
  • Sticky session: useful when a sequence of requests needs continuity, such as maintaining a login or a multi-step flow.

The exact username parameters or session controls may vary by product. Copy the generated credentials from the ColaProxy dashboard instead of constructing location or session syntax from an unrelated example.

Responsible use

Only access data you are authorized to use. Respect applicable laws, website terms, robots directives where relevant, authentication boundaries, and reasonable request rates. A proxy changes network routing; it does not grant permission to access restricted content.

FAQ

Why do both dictionary values use the same proxy URL?

The dictionary keys describe the destination scheme. Many authenticated proxy gateways accept HTTP proxy connections and tunnel HTTPS destinations, so both keys can point to the same endpoint. Follow the endpoint format supplied in your dashboard.

Does Requests support SOCKS5 proxies?

Yes, after installing the SOCKS extra with python -m pip install "requests[socks]". Use a SOCKS endpoint only when your proxy product provides one.

How should I keep the same IP across several requests?

A Python Session reuses client settings, but proxy IP persistence is controlled by the provider’s sticky-session configuration. Generate or copy the appropriate session credentials from the ColaProxy dashboard.

Next step

Run the IP verification example with the endpoint from your ColaProxy dashboard. Once the exit IP and location are correct, move the same session into your application and add workload-specific retry and rate-limit handling.

About the Author

A

Alyssa

Senior Content Strategist & Proxy Industry Expert

Alyssa is a veteran specialist in proxy architecture and network security. With over a decade of experience in network identity management and encrypted communications, she excels at bridging the gap between low-level technical infrastructure and high-level business growth strategies. Alyssa focuses her research on global data harvesting, identity anonymization, and anti-fingerprinting technologies, dedicated to providing authoritative guides that help users stay ahead in a dynamic digital landscape.

The ColaProxy Team

The ColaProxy Content Team is comprised of elite network engineers, privacy advocates, and data architects. We don't just understand proxy technology; we live its real-world applications—from social media matrix management and cross-border e-commerce to large-scale enterprise data mining. Leveraging deep insights into residential IP infrastructures across 200+ countries, our team delivers battle-tested, reliable insights designed to help you build an unshakeable technical advantage in a competitive market.

Why Choose ColaProxy?

ColaProxy delivers enterprise-grade residential proxy solutions, renowned for unparalleled connection success rates and absolute stability.

  • Global Reach: Access a massive pool of 50 million+ clean residential IPs across 200+ countries.
  • Versatile Protocols: Full support for HTTP/SOCKS5 protocols, optimized for both dynamic rotating and long-term static sessions.
  • Elite Performance: 99.9% uptime with unlimited concurrency, engineered for high-intensity tasks like TikTok operations, e-commerce scaling, and automated web scraping.
  • Expert Support: Backed by a deep engineering background, our 24/7 expert support ensures your global deployments are seamless and secure.
Disclaimer

All content on the ColaProxy Blog is provided for informational purposes only and does not constitute legal advice. The use of proxy technology must strictly comply with local laws and the specific Terms of Service of target websites. We strongly recommend consulting with legal counsel and ensuring full compliance before engaging in any data collection activities.