ProxyProviders Quick Start Documentation

ProxyProviders

One interface for proxy vendors, many Python clients.

Get proxies from Webshare, Bright Data or your own list, and use them with requests, httpx, aiohttp, Playwright, Scrapy, Crawlee or curl without writing vendor-specific code. Swap providers by changing one line.

codecov Sponsor Me GitHub release (latest by date) GitHub Downloads Support Server LinkedIn

import requests
from proxyproviders import Webshare, ProxyFormat

provider = Webshare(api_key="your-api-key")  # or BrightData(...), or ProxyList([...])
proxy = provider.get_proxy()

response = requests.get(
    "https://httpbin.org/ip", proxies=proxy.format(ProxyFormat.REQUESTS)
)

Table of Contents

Installation

python -m pip install proxyproviders

Python 3.10 or newer. The full documentation is here, and there are runnable examples in the repository.

Using an AI coding assistant? Point it at llms.txt, a short summary of the API written for assistants.

πŸ“Ί Video Tutorial: Watch the quick start guide on YouTube for a walkthrough of getting started with ProxyProviders.

What It Does

Every proxy vendor has its own API, and every HTTP client wants its proxy in a different shape. ProxyProviders sits between the two:

Webshare | Bright Data | your own list
                 ↓
   ProxyProvider  β†’  Proxy
                 ↓
requests | httpx | aiohttp | Playwright | Scrapy | Crawlee | curl
  • Provider API handled for you. Proxies are fetched from the vendor, cached, and refreshed on an interval.

  • One Proxy model. Host, port, credentials, country and protocols look the same whichever vendor they came from.

  • One line to hand it to your client. proxy.format(...) produces what each client expects, with credentials percent-encoded correctly.

  • Vendor-neutral code. Anything written against ProxyProvider works with every provider, so switching vendor does not touch the rest of your application.

Rotation and retries are available if you want them (RotatingSession), and stay out of the way if your framework already does that.

Works With

Client

How to pass the proxy

Format

requests

requests.get(url, proxies=...)

ProxyFormat.REQUESTS

httpx

httpx.Client(proxy=...)

ProxyFormat.HTTPX

aiohttp

session.get(url, proxy=...)

ProxyFormat.AIOHTTP

Playwright

browser.new_context(proxy=...)

ProxyFormat.PLAYWRIGHT

Scrapy

Request(meta={"proxy": ...})

ProxyFormat.SCRAPY

Crawlee

ProxyConfiguration(proxy_urls=[...])

proxy.to_url()

urllib

urllib.request.ProxyHandler(...)

ProxyFormat.URLLIB

curl

curl -x ...

ProxyFormat.CURL

Any subprocess

HTTP_PROXY / HTTPS_PROXY variables

ProxyFormat.ENV

Other tools

host:port:username:password

ProxyFormat.HOST_PORT_USER_PASS

Anything else

scheme://username:password@host:port

ProxyFormat.URL

requests, httpx, aiohttp, urllib and curl are tested in CI by sending a real request through a local proxy with each client’s current release.

Supported Proxy Providers

Provider

Class

Notes

Webshare

Webshare(api_key=...)

10 free datacenter proxies to try it out

Bright Data

BrightData(api_key=..., zone=...)

Super proxy or one proxy per IP in the zone

Any other vendor

ProxyList([...])

Your own list of proxy URLs or host:port:user:pass lines

Getting credentials:

  • Webshare: create an account here (affiliate link), then generate a token in the API tab.

  • Bright Data: create an account here (affiliate link), then create an API token in the account settings.

Keep API tokens out of your code and repository; the examples below read them from environment variables. Each provider’s options are in the provider documentation. Don’t see your vendor? Add a provider or open an issue.

Quick Start Guide

List the proxies from a provider:

import os
from proxyproviders import Webshare

provider = Webshare(api_key=os.environ["WEBSHARE_API_KEY"])

proxies = provider.list_proxies()
print(proxies)  # passwords are left out of the printed output

Or take one at a time. get_proxy() cycles through the list in order by default:

proxy = provider.get_proxy()
print(proxy.proxy_address, proxy.port, proxy.country_code)

Providers take their own options. Webshare passes search_params to the Webshare API, so this returns only proxies based in the US:

provider = Webshare(
    api_key=os.environ["WEBSHARE_API_KEY"], search_params={"country_code_in": "US"}
)

Because every provider has the same interface, code written against ProxyProvider does not care which vendor is behind it:

import os
import requests
from proxyproviders import BrightData, ProxyFormat, ProxyProvider, Webshare


def fetch_ip(provider: ProxyProvider) -> str:
    proxy = provider.get_proxy()
    response = requests.get(
        "https://httpbin.org/ip", proxies=proxy.format(ProxyFormat.REQUESTS)
    )
    return response.json()["origin"]


fetch_ip(Webshare(api_key=os.environ["WEBSHARE_API_KEY"]))
fetch_ip(BrightData(api_key=os.environ["BRIGHTDATA_API_KEY"], zone="my_zone"))

That is how other libraries, such as my TikTokAPI package, accept any proxy vendor without knowing about it.

Using Proxies With Your HTTP Client

Every example below starts with a provider, which can be any provider from the table above.

Python requests With Rotating Proxies

import requests
from proxyproviders import ProxyFormat

proxy = provider.get_proxy()
response = requests.get(
    "https://httpbin.org/ip", proxies=proxy.format(ProxyFormat.REQUESTS)
)

Each get_proxy() call returns the next proxy, so calling it per request rotates through your proxies. To have rotation and retries done for you, use RotatingSession.

httpx Proxy

httpx (0.26 or newer) takes one proxy URL in its proxy= argument, for both the sync and async clients:

import httpx
from proxyproviders import ProxyFormat

with httpx.Client(proxy=provider.get_proxy().format(ProxyFormat.HTTPX)) as client:
    response = client.get("https://httpbin.org/ip")

async with httpx.AsyncClient(
    proxy=provider.get_proxy().format(ProxyFormat.HTTPX)
) as client:
    response = await client.get("https://httpbin.org/ip")

aiohttp Proxy

import aiohttp
from proxyproviders import ProxyFormat

async with aiohttp.ClientSession() as session:
    async with session.get(
        "https://httpbin.org/ip", proxy=provider.get_proxy().format(ProxyFormat.AIOHTTP)
    ) as response:
        print(await response.json())

Playwright Proxy in Python

from playwright.sync_api import sync_playwright
from proxyproviders import ProxyFormat

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(
        proxy=provider.get_proxy().format(ProxyFormat.PLAYWRIGHT)
    )
    page = context.new_page()
    page.goto("https://httpbin.org/ip")

Give each browser context its own get_proxy() call to spread contexts across proxies. The same dictionary works for p.chromium.launch(proxy=...).

Scrapy Proxy

Scrapy’s built-in HttpProxyMiddleware reads the proxy from request.meta and takes the credentials out of the URL:

import scrapy
from proxyproviders import ProxyFormat


class IpSpider(scrapy.Spider):
    name = "ip"

    def start_requests(self):
        yield scrapy.Request(
            "https://httpbin.org/ip",
            meta={"proxy": provider.get_proxy().format(ProxyFormat.SCRAPY)},
        )

Crawlee for Python Proxy

Crawlee rotates proxies and manages sessions itself, so hand it the whole list:

from crawlee.proxy_configuration import ProxyConfiguration

proxy_configuration = ProxyConfiguration(
    proxy_urls=[proxy.to_url() for proxy in provider.list_proxies()]
)

curl and Subprocesses

import os
import subprocess
from proxyproviders import ProxyFormat

proxy = provider.get_proxy()

# As curl arguments: ["-x", "http://user:pass@host:port"]
subprocess.run(["curl", *proxy.format(ProxyFormat.CURL), "https://httpbin.org/ip"])

# Or as HTTP_PROXY / HTTPS_PROXY for any program that reads them
subprocess.run(
    ["curl", "https://httpbin.org/ip"],
    env={**os.environ, **proxy.format(ProxyFormat.ENV)},
)

Use Your Own Proxy List

If your vendor has no provider here, or you simply have a list of proxies, ProxyList gives them the same interface as everything else:

from proxyproviders import ProxyList

provider = ProxyList(
    [
        "http://user:pass@203.0.113.7:8080",
        "203.0.113.8:8080:user:pass",
        "socks5://user:pass@203.0.113.9:1080",
    ]
)

# Or one proxy per line from a file (blank lines and # comments are skipped)
provider = ProxyList.from_file("proxies.txt")

A single proxy can be parsed with Proxy.from_string(...), which accepts a URL, user:pass@host:port, host:port or host:port:user:pass.

Automatic Rotation and Retries

RotatingSession is a requests.Session that picks a proxy for every request. If a request cannot get through its proxy, that proxy is set aside for a while and the request is sent again through the next one:

from proxyproviders import RotatingSession

session = RotatingSession(provider, max_retries=3)

response = session.get("https://httpbin.org/ip", timeout=10)
print(response.json(), session.last_proxy)

It is opt-in: nothing changes for code that calls get_proxy() itself. What it treats as a failed proxy, and when it sends the request again:

  • Could not connect to the proxy, or open a tunnel through it: retried for any HTTP method, because the request never reached the target.

  • Any other connection error or timeout, such as a proxy that drops the connection or stops responding: retried for GET, HEAD and OPTIONS only. A POST may already have been acted on, so the error is raised instead of sending it twice.

  • A 407 Proxy Authentication Required response, or any status you list in retry_statuses: retried for any method.

Ordinary error statuses such as 404 or 500 are returned as usual. File uploads and streamed bodies are sent once and never retried. Deciding that a response means your proxy is blocked is up to you, for example:

session = RotatingSession(provider, max_retries=3, retry_statuses={403, 429})

For httpx 0.26 or newer, sync or async, the same behaviour comes as a transport. Install it with pip install "proxyproviders[httpx]":

import httpx
from proxyproviders.httpx_transport import AsyncRotatingTransport, RotatingTransport

with httpx.Client(transport=RotatingTransport(provider, max_retries=3)) as client:
    response = client.get("https://httpbin.org/ip")

async with httpx.AsyncClient(transport=AsyncRotatingTransport(provider)) as client:
    response = await client.get("https://httpbin.org/ip")

Reporting Failed Proxies

When you make requests yourself, tell the provider about a proxy that failed and get_proxy() will avoid it for failure_cooldown seconds (60 by default):

import requests
from proxyproviders import ProxyFormat

proxy = provider.get_proxy()
try:
    response = requests.get(url, proxies=proxy.format(ProxyFormat.REQUESTS), timeout=10)
except requests.exceptions.ProxyError:
    provider.report_failure(proxy)

provider.report_success(proxy) puts it back early, and provider.available_proxies() lists the ones not currently set aside. If every proxy has failed, get_proxy() still returns one instead of raising. This works the same with every HTTP client, sync or async.

Choosing Which Proxy You Get

get_proxy() takes a selection algorithm. The default is round robin.

from proxyproviders.algorithms import First, Random, RoundRobin

proxy = provider.get_proxy()  # RoundRobin: next proxy in order
proxy = provider.get_proxy(Random())  # a random proxy
proxy = provider.get_proxy(First())  # always the first proxy

# A RoundRobin you create keeps its own position, separate from the provider's default
round_robin = RoundRobin()
proxy1 = provider.get_proxy(round_robin)
proxy2 = provider.get_proxy(round_robin)  # next in sequence

Write your own by subclassing Algorithm:

from typing import List
from proxyproviders import Proxy
from proxyproviders.algorithms import Algorithm


class USProxyAlgorithm(Algorithm):
    """Prefers US proxies, falls back to the first available."""

    def select(self, proxies: List[Proxy]) -> Proxy:
        for proxy in proxies:
            if proxy.country_code == "US":
                return proxy
        return proxies[0]


proxy = provider.get_proxy(USProxyAlgorithm())

Configuration

Options shared by every provider live in ProxyConfig (full reference):

Option

Default

Meaning

refresh_interval

600

Seconds before the proxy list is fetched again. 0 fetches once and never refreshes.

timeout

30

Seconds to wait on each call to the provider’s API

refresh_retry_delay

30

If a refresh fails, the previous list keeps being served and the API is tried again after this many seconds

failure_cooldown

60

Seconds get_proxy() avoids a proxy after report_failure()

import os
import time
from proxyproviders import ProxyConfig, Webshare

config = ProxyConfig(refresh_interval=3)
ws = Webshare(api_key=os.environ["WEBSHARE_API_KEY"], config=config)

ws.list_proxies()  # calls the API
ws.list_proxies()  # cached

time.sleep(5)
ws.list_proxies()  # calls the API again, since more than 3s have passed

list_proxies() and get_proxy() are safe to call from several threads.

SOCKS Proxies

A proxy whose protocols only lists a SOCKS scheme, e.g. ["socks5"], is formatted with that scheme for every client:

proxy.format(ProxyFormat.REQUESTS)
# {'http': 'socks5://user:pass@host:1080', 'https': 'socks5://user:pass@host:1080'}

Your HTTP client needs SOCKS support for this to work. For requests, install it with:

python -m pip install "proxyproviders[socks]"

httpx needs httpx[socks]. aiohttp and Scrapy have no built-in SOCKS support.

Making Your Own Proxy Provider

Subclass ProxyProvider and return a list of Proxy objects from _fetch_proxies. Caching, refreshing, selection, formatting and failure reporting then work without any more code:

from typing import List, Optional
from proxyproviders import Proxy, ProxyConfig, ProxyProvider


class MyProxyProvider(ProxyProvider):
    def __init__(self, config: Optional[ProxyConfig] = None):
        super().__init__(config=config)

    def _fetch_proxies(self) -> List[Proxy]:
        # Call your vendor's API here and convert each entry
        return [
            Proxy(
                id="1",
                username="username",
                password="password",
                proxy_address="192.168.1.1",
                port=80,
            )
        ]


provider = MyProxyProvider()
proxy = provider.get_proxy()

If you write one for a vendor other people use, please contribute it back. CONTRIBUTING.md has the steps, and the repository includes an add-provider skill that walks a coding agent such as Claude Code through the whole process.

How to Support The Project

  • Star the repo 😎

  • Consider sponsoring me on GitHub

  • Send me an email or a LinkedIn message about what you’re doing with it :D

  • Submit PRs for issues or any new providers/features :)

Note: If you want to learn how to web scrape websites check my free and open-source course for learning everything web scraping

ProxyProvider Shared Interface

class proxyproviders.proxy_provider.ProxyConfig(refresh_interval: float = 600, timeout: float = 30, refresh_retry_delay: float = 30, failure_cooldown: float = 60)[source]

Bases: object

Provides standard shared configuration options for all proxy providers.

Example:

from proxyproviders import Webshare, ProxyConfig

config = ProxyConfig(refresh_interval=5)
proxy_provider = Webshare(api_key="your-api-key", config=config)
refresh_interval: float = 600

Duration in seconds after which the proxy list is refreshed to fetch new proxies. Set to 0 to disable automatic refreshing after the initial fetch.

timeout: float = 30

Timeout in seconds for each request to the provider’s API, so a stalled connection raises instead of hanging forever.

refresh_retry_delay: float = 30

After an automatic refresh fails and the previous proxy list is served instead, wait this many seconds before trying the provider’s API again.

failure_cooldown: float = 60

How long, in seconds, ProxyProvider.get_proxy() avoids a proxy after it was passed to ProxyProvider.report_failure().

class proxyproviders.proxy_provider.ProxyProvider(config: ProxyConfig | None = None)[source]

Bases: ABC

Base class for all proxy providers that provides shared functionality across all providers.

You’ll need to use a specific provider to fetch proxies and this shouldn’t directly be initialized. However, this class is useful for type hinting and for creating custom providers that are not included in the library, although consider contributing them to the library if you are making them.

Parameters:

config – Configuration for the proxy provider. View the ProxyConfig class docs for more information.

config: ProxyConfig
list_proxies(force_refresh: bool = False) → List[Proxy][source]

Returns the stored proxies, fetching them from the provider first when they are missing or older than refresh_interval.

Safe to call from several threads: when the list is stale only one thread fetches and the others wait for its result.

If an automatic refresh fails and an earlier list is available, that list is returned and a warning is logged, so one failed call to the provider’s API does not take your proxies away. The error is raised when there is nothing to fall back on, or when force_refresh is True.

Parameters:

force_refresh – If True, fetches new proxies even if the list is not considered stale.

get_proxy(algorithm: Algorithm | None = None) → Proxy[source]

Get a single proxy using the specified selection algorithm.

Parameters:

algorithm – Selection algorithm to use. If None, uses the provider’s default RoundRobin algorithm.

Returns:

Selected proxy

Raises:

ValueError – If no proxies are available

Example

>>> from proxyproviders import Webshare
>>> from proxyproviders.algorithms import Random, RoundRobin
>>>
>>> provider = Webshare(api_key="your-key")
>>>
>>> # Uses default RoundRobin (cycles through proxies)
>>> proxy = provider.get_proxy()
>>>
>>> # Uses Random selection
>>> proxy = provider.get_proxy(Random())
>>>
>>> # One-liner with requests
>>> import requests
>>> from proxyproviders.models.proxy import ProxyFormat
>>> requests.get("https://httpbin.org/ip", proxies=provider.get_proxy().format(ProxyFormat.REQUESTS))
report_failure(proxy: Proxy, cooldown: float | None = None) → None[source]

Tell the provider a proxy just failed, so get_proxy() avoids it for a while.

Nothing calls this for you unless you use RotatingSession; it is how your own code feeds back a connection error, a ban or a bad response. The proxy stays in list_proxies() and comes back into rotation once the cooldown has passed. If every proxy is cooling down, get_proxy() still returns one.

Parameters:
  • proxy – The proxy that failed

  • cooldown – Seconds to avoid it for. Defaults to ProxyConfig.failure_cooldown.

Example

>>> proxy = provider.get_proxy()
>>> try:
...     requests.get(url, proxies=proxy.format(ProxyFormat.REQUESTS), timeout=10)
... except requests.exceptions.ProxyError:
...     provider.report_failure(proxy)
report_success(proxy: Proxy) → None[source]

Clear a failure reported for a proxy, putting it back into rotation right away.

available_proxies() → List[Proxy][source]

Like list_proxies(), without the proxies currently cooling down after report_failure().

should_refresh() → bool[source]

Returns True if the proxy list should be refreshed based on the refresh_interval.

ProxyProviders Supported Providers

Current Providers Supported:

  • Webshare.io (referral link) - try out 10 free datacenter proxies

  • BrightData (affiliate link)

  • ProxyList - your own list of proxies from any other vendor

Don’t see a provider you need? Open an issue or submit a PR!

class proxyproviders.providers.webshare.Webshare(api_key: str, search_params: Dict[str, Any] | None = None, config: ProxyConfig | None = None)[source]

Bases: ProxyProvider

Webshare is a proxy provider that offers residential and datacenter proxies.

Create an account for webshare here (affiliate link) to get started with 10 free data center proxies.

You can find your API key in the Webshare dashboard here

You can find a list of all available parameters in the Webshare API documentation here

Parameters:
  • api_key – Your Webshare API key

  • search_params – Optional parameters to include in the API requests

  • config – Configuration for the proxy provider. View the ProxyConfig class docs for more information.

Example:

from proxyproviders import Webshare

# Initialize the Webshare API client with an API key and optional parameters
proxy_provider = Webshare(api_key="your-api-key", search_params={"country_code_in": "US"})

# Fetch proxies
proxies = proxy_provider.list_proxies()

# With config
from proxyproviders import ProxyConfig

config = ProxyConfig(refresh_interval=60)
proxy_provider = Webshare(api_key="your-api-key", search_params={"country_code_in": "US"}, config=config)

# Fetch proxies
proxies = proxy_provider.list_proxies()
class proxyproviders.providers.brightdata.BrightData(api_key: str, zone: str, username_suffix: str | None = None, use_super_proxy: bool | None = True, config: ProxyConfig | None = None)[source]

Bases: ProxyProvider

BrightData (formerly luminati) is a proxy provider that offers residential and datacenter proxies.

Create an account here (affiliate link).

You can find your API key in the account settings here then create β€œadd token” with scope β€œlimit” (BrightData article for more info)

The BrightData API documentation is here

Parameters:
  • api_key – Your BrightData API key

  • zone – The zone ID/name to fetch proxies for (you can get this from the BrightData dashboard)

  • username_suffix – Optional suffix to append to the username more info allows you to target region, city, etc. (requires use_super_proxy=True)

  • use_super_proxy – Optional flag to use super proxy instead of targeting specific IPs, this is enabled by default. If you want to target specific IPs or have consistent IPs for a session, set this to False.

  • config – Configuration for the proxy provider. View the ProxyConfig class docs for more information.

Example:

from proxyproviders import BrightData

# Initialize the BrightData API client with an API key and a zone
proxy_provider = BrightData(api_key="your-api-key", zone="my_zone")

# Fetch proxies
proxies = proxy_provider.list_proxies() # returns one proxy for super proxy by default

# If you want to manage specific IPs
proxy_provider = BrightData(api_key="your-api-key", zone="my_zone", use_super_proxy=False)
proxies = proxy_provider.list_proxies() # returns multiple proxies for each IP in the zone (potentially thousands)
get_active_zones() → Any[source]

Fetches active zones from BrightData API.

Response:

[
    {
        "name": "zone1",
        "type": "dc",
    }
]
get_zone_username(zone: str) → str[source]

Fetches zone username for the given zone ID from BrightData API.

Note: this isn’t directly an API endpoint, I’m sort of reconstructing some things here and it seems to behave a little weird.

Parameters:

zone – The zone ID to fetch username for

get_zone_passwords(zone: str) → Any[source]

Fetches zone passwords from BrightData API.

Parameters:

zone – The zone ID to fetch passwords for

Response:

{
    "passwords": [
        "password1",
        "password2",
    ]
}
list_all_ips_in_zone(zone: str, country: str | None = None) → Any[source]

Fetches all IPs in a zone from BrightData API.

Parameters:
  • zone – The zone ID to fetch IPs for

  • country – Optional 2-letter country code to filter IPs by

Response:

[
    {
        "ip": "192.168.1.1",
        "country": "US",
    }
]
class proxyproviders.providers.proxy_list.ProxyList(proxies: Iterable[str | Proxy], config: ProxyConfig | None = None)[source]

Bases: ProxyProvider

A provider for proxies you already have, from any vendor.

Use it when your vendor has no provider here yet, or when you manage the list yourself. You get the same interface as every other provider: selection algorithms, output formats, failure reporting and RotatingSession.

Parameters:
  • proxies – The proxies, each either a Proxy or text in any form Proxy.from_string() accepts: a URL such as http://user:pass@host:port or socks5://host:port, or host:port:user:pass

  • config – Configuration for the proxy provider. View the ProxyConfig class docs for more information.

Raises:

ValueError – If an entry cannot be parsed, or the list is empty

Example:

from proxyproviders import ProxyList

provider = ProxyList(
    [
        "http://user:pass@203.0.113.7:8080",
        "203.0.113.8:8080:user:pass",
        "socks5://user:pass@203.0.113.9:1080",
    ]
)

proxy = provider.get_proxy()

# Or one proxy per line from a file, ignoring blank lines and # comments
provider = ProxyList.from_file("proxies.txt")
classmethod from_file(path: str | Path, config: ProxyConfig | None = None) → ProxyList[source]

Load proxies from a text file with one proxy per line.

Blank lines and lines starting with # are skipped.

Parameters:
  • path – Path to the file

  • config – Configuration for the proxy provider

Rotating Session

An opt-in requests.Session that picks a proxy for every request.

Nothing else in the package uses this module. Import it when you want rotation and retries handled for you instead of calling provider.get_proxy() yourself.

class proxyproviders.session.RotatingSession(provider: ProxyProvider, algorithm: Algorithm | None = None, max_retries: int = 2, retry_statuses: Collection[int] = ())[source]

Bases: Session

A requests.Session that routes each request through a proxy from a provider.

Every request asks the provider for a proxy. If the request fails to get through the proxy, the proxy is reported with report_failure() and the request is tried again on the next one, up to max_retries more times. It works with any provider, including ProxyList.

What counts as a failed proxy, and when the request is sent again:

  • Failing to connect to the proxy, or to open a tunnel through it: retried for any HTTP method, because the request never reached the target.

  • Any other connection error or timeout, such as a proxy that drops the connection or stops responding: retried for GET, HEAD and OPTIONS only. Other methods may already have been acted on, so the error is raised instead.

  • A 407 Proxy Authentication Required response, or any status you list in retry_statuses: retried for any method.

Anything else, including ordinary error statuses such as 404 or 500, is returned or raised exactly as requests would. A TLS error is raised without blaming the proxy, since it usually comes from the target. A slow target cannot be told apart from a slow proxy, so a read timeout counts against the proxy. Deciding that a response means β€œbanned” is left to you: list statuses in retry_statuses or call report_failure yourself.

A request made with an explicit proxies= argument is sent as given, with no rotation. Requests that upload files or stream their body are sent once and never retried, since the body cannot be read twice.

Parameters:
  • provider – Where proxies come from

  • algorithm – Selection algorithm, as for provider.get_proxy(). Defaults to the provider’s round robin.

  • max_retries – How many more proxies to try after the first one fails

  • retry_statuses – Extra response status codes treated as a failed proxy, e.g. {403, 429} for a target that blocks proxies. 407 is always included.

Example:

from proxyproviders import Webshare
from proxyproviders.session import RotatingSession

session = RotatingSession(Webshare(api_key="your-api-key"), max_retries=3)

response = session.get("https://httpbin.org/ip", timeout=10)
print(response.json(), session.last_proxy)
last_proxy: Proxy | None

The proxy used for the most recent request, whether it succeeded or not.

request(method: str | bytes, url: str | bytes, *args: Any, **kwargs: Any) → Response[source]

Send a request through a proxy from the provider, retrying on the next proxy if this one fails. Takes the same arguments as requests.Session.request.

send(request: PreparedRequest, **kwargs: Any) → Response[source]

Send a prepared request. Rotates like request() unless proxies is given.

Rotating httpx Transports

Opt-in httpx transports that pick a proxy for every request, sync and async.

Nothing else in the package uses this module, and it is the only one that needs httpx: pip install "proxyproviders[httpx]".

class proxyproviders.httpx_transport.RotatingTransport(*args: Any, **kwargs: Any)[source]

Bases: _Rotation, BaseTransport

An httpx transport that routes each request through a proxy from a provider.

Every request asks the provider for a proxy. If the request fails to get through, the proxy is reported with report_failure() and the request is sent again through the next one, up to max_retries more times.

What counts as a failed proxy:

  • a connect error, connect timeout or proxy error: retried for any HTTP method, because the request never reached the target

  • a read or write error or timeout, or a broken response: retried for GET, HEAD and OPTIONS only

  • a 407 Proxy Authentication Required response, or any status you list in retry_statuses: retried for any method

Anything else is returned or raised exactly as httpx would. httpx reports a failed TLS handshake with the target as a connect error, so that also counts against the proxy. Requests with a streamed or multipart body are sent once and not retried. One connection pool is kept per proxy used, so connections are reused when a proxy comes round again.

Parameters:
  • provider – Where proxies come from

  • algorithm – Selection algorithm, as for provider.get_proxy()

  • max_retries – How many more proxies to try after the first one fails

  • retry_statuses – Extra response status codes treated as a failed proxy, e.g. {403, 429}. 407 is always included.

  • transport_options – Passed to each underlying httpx.HTTPTransport, e.g. verify= or http2=True

Example:

import httpx
from proxyproviders import Webshare
from proxyproviders.httpx_transport import RotatingTransport

transport = RotatingTransport(Webshare(api_key="your-api-key"), max_retries=3)

with httpx.Client(transport=transport) as client:
    response = client.get("https://httpbin.org/ip")
handle_request(request: Request) → Response[source]

Send the request through a proxy, moving to the next proxy if it fails.

class proxyproviders.httpx_transport.AsyncRotatingTransport(*args: Any, **kwargs: Any)[source]

Bases: _Rotation, AsyncBaseTransport

The async version of RotatingTransport, for httpx.AsyncClient.

It behaves the same way and takes the same arguments. Asking the provider for a proxy runs in a worker thread, so a provider refreshing its list from the vendor’s API does not block the event loop.

Example:

import httpx
from proxyproviders import Webshare
from proxyproviders.httpx_transport import AsyncRotatingTransport

transport = AsyncRotatingTransport(Webshare(api_key="your-api-key"))

async with httpx.AsyncClient(transport=transport) as client:
    response = await client.get("https://httpbin.org/ip")
async handle_async_request(request: Request) → Response[source]

Send the request through a proxy, moving to the next proxy if it fails.

ProxyProviders Models

class proxyproviders.models.proxy.Proxy(id: str, username: str, password: str, proxy_address: str, port: int, country_code: str | None = None, city_name: str | None = None, created_at: datetime | None = None, protocols: List[str] | None = None)[source]

Bases: object

Our shared data model for a proxy object across all providers.

id: str

A unique identifier for the proxy

username: str

The username required for authenticating with the proxy

password: str

The password required for authenticating with the proxy. Left out of repr() so printing or logging a proxy does not expose it.

proxy_address: str

The IP address or domain name of the proxy

port: int

The port number through which the proxy connection is established

country_code: str | None = None

The country code where the proxy is located, e.g., β€˜US’, β€˜FR’. Optional

city_name: str | None = None

The city name where the proxy is located, e.g., β€˜New York’, β€˜Paris’. Optional

created_at: datetime | None = None

The timestamp when the proxy was created. Optional

protocols: List[str] | None = None

A list of connection protocols supported by the proxy, e.g., [β€˜http’, β€˜https’]

classmethod from_string(text: str, id: str | None = None, **fields: Any) → Proxy[source]

Build a proxy from text, for proxies you already have as a list or a file.

Accepted forms:

  • a URL: http://user:pass@host:port, socks5://host:port

  • user:pass@host:port and host:port (treated as http)

  • host:port:user:pass, the line format many providers export

Parameters:
  • text – The proxy to parse

  • id – Identifier for the proxy. Defaults to host:port.

  • fields – Any other Proxy fields to set, e.g. country_code="US"

Raises:

ValueError – If the text is not one of the accepted forms

Example

>>> Proxy.from_string("203.0.113.7:8080:user:pass").to_url()
'http://user:pass@203.0.113.7:8080'
classmethod from_url(url: str, id: str | None = None, **fields: Any) → Proxy[source]

Build a proxy from a URL such as http://user:pass@host:port.

The reverse of to_url(): percent-encoded credentials are decoded. See from_string(), which this is an alias of, for every accepted form.

property scheme: str

The URL scheme used to connect to this proxy.

protocols lists what the proxy supports. A proxy that supports http or https (or does not say) is reached over http. A SOCKS-only proxy, e.g. protocols=["socks5"], is reached over that SOCKS scheme.

to_url(protocol: str | None = None) → str[source]

Convert proxy to URL format for use with HTTP clients.

Parameters:

protocol – The protocol to use in the URL. Defaults to scheme, which is http unless the proxy only supports SOCKS.

Returns:

Proxy URL in format β€˜protocol://username:password@host:port’. The username and password are percent-encoded, so characters such as @, :, # or / in them do not change where the URL points. A proxy with no username and no password gives β€˜protocol://host:port’.

Example

>>> proxy.to_url()
'http://user:pass@192.168.1.1:8080'
>>> proxy.to_url('https')
'https://user:pass@192.168.1.1:8080'
format(format_type: Literal[ProxyFormat.URL, ProxyFormat.HTTPX, ProxyFormat.AIOHTTP, ProxyFormat.SCRAPY, ProxyFormat.HOST_PORT_USER_PASS, 'url', 'httpx', 'aiohttp', 'scrapy', 'host_port_user_pass'] = ProxyFormat.URL, **kwargs: Any) → str[source]
format(format_type: Literal[ProxyFormat.REQUESTS, ProxyFormat.URLLIB, ProxyFormat.PLAYWRIGHT, ProxyFormat.ENV, 'requests', 'urllib', 'playwright', 'env'], **kwargs: Any) → Dict[str, str]
format(format_type: Literal[ProxyFormat.CURL, 'curl'], **kwargs: Any) → List[str]
format(format_type: ProxyFormat | str, **kwargs: Any) → str | Dict[str, str] | List[str]

Format proxy for different HTTP clients and tools.

A SOCKS-only proxy (protocols=["socks5"]) is formatted with its SOCKS scheme. Your HTTP client needs SOCKS support for that: requests[socks] or httpx[socks]. aiohttp and Scrapy have no built-in SOCKS support.

Parameters:
  • format_type – Output format (default: URL string). See ProxyFormat for every format and what it is passed to.

  • kwargs – Format-specific options: protocol for URL and PLAYWRIGHT, protocols for REQUESTS and URLLIB

Returns:

Formatted proxy data

Examples

>>> proxy.format()  # Default URL string
'http://user:pass@192.168.1.1:8080'
>>> proxy.format(ProxyFormat.REQUESTS)  # requests.get(url, proxies=...)
{'http': 'http://user:pass@192.168.1.1:8080', 'https': 'http://user:pass@192.168.1.1:8080'}
>>> proxy.format('curl')  # String also works
['-x', 'http://user:pass@192.168.1.1:8080']
>>> proxy.format(ProxyFormat.HTTPX)  # httpx.Client(proxy=...)
'http://user:pass@192.168.1.1:8080'
>>> proxy.format(ProxyFormat.PLAYWRIGHT)  # browser.new_context(proxy=...)
{'server': 'http://192.168.1.1:8080', 'username': 'user', 'password': 'pass'}
>>> proxy.format(ProxyFormat.HOST_PORT_USER_PASS)
'192.168.1.1:8080:user:pass'
class proxyproviders.models.proxy.ProxyFormat(*values)[source]

Bases: Enum

Supported proxy output formats.

REQUESTS = 'requests'

{"http": url, "https": url} for the proxies= argument of requests

CURL = 'curl'

["-x", url] arguments for the curl command line

HTTPX = 'httpx'

URL string for the proxy= argument of httpx.Client / httpx.AsyncClient

AIOHTTP = 'aiohttp'

URL string for the proxy= argument of aiohttp requests and sessions

PLAYWRIGHT = 'playwright'

{"server", "username", "password"} for the proxy= option of Playwright

URL = 'url'

scheme://username:password@host:port URL string

SCRAPY = 'scrapy'

URL string for Request(meta={"proxy": ...}) in Scrapy

URLLIB = 'urllib'

{"http": url, "https": url} for urllib.request.ProxyHandler

ENV = 'env'

HTTP_PROXY / HTTPS_PROXY (and ALL_PROXY for SOCKS) environment variables, in upper and lower case, for subprocesses and tools that read them

HOST_PORT_USER_PASS = 'host_port_user_pass'

host:port:username:password, the plain-text line many proxy tools import

Proxy Formats

Converters between Proxy and the shapes that HTTP clients, browsers and tools expect.

Each output format is one small function registered in _FORMATTERS. Adding a format means adding a ProxyFormat member and a function here; nothing else changes. Parsing the other way (text to proxy fields) lives in parse_proxy_string().

class proxyproviders.models.formats.ProxyFormat(*values)[source]

Bases: Enum

Supported proxy output formats.

REQUESTS = 'requests'

{"http": url, "https": url} for the proxies= argument of requests

CURL = 'curl'

["-x", url] arguments for the curl command line

HTTPX = 'httpx'

URL string for the proxy= argument of httpx.Client / httpx.AsyncClient

AIOHTTP = 'aiohttp'

URL string for the proxy= argument of aiohttp requests and sessions

PLAYWRIGHT = 'playwright'

{"server", "username", "password"} for the proxy= option of Playwright

URL = 'url'

scheme://username:password@host:port URL string

SCRAPY = 'scrapy'

URL string for Request(meta={"proxy": ...}) in Scrapy

URLLIB = 'urllib'

{"http": url, "https": url} for urllib.request.ProxyHandler

ENV = 'env'

HTTP_PROXY / HTTPS_PROXY (and ALL_PROXY for SOCKS) environment variables, in upper and lower case, for subprocesses and tools that read them

HOST_PORT_USER_PASS = 'host_port_user_pass'

host:port:username:password, the plain-text line many proxy tools import

proxyproviders.models.formats.format_proxy(proxy: Proxy, format_type: ProxyFormat | str, **kwargs: Any) → str | Dict[str, str] | List[str][source]

Format proxy as format_type. See Proxy.format().

proxyproviders.models.formats.parse_proxy_string(text: str) → Dict[str, Any][source]

Parse one proxy written as text into the fields of a Proxy.

Accepted forms:

  • a URL: http://user:pass@host:port, socks5://host:port

  • host:port:user:pass, the line format many providers export, and host:port

  • user:pass@host:port (treated as http)

Percent-encoded credentials in a URL are decoded. In host:port:user:pass the password is everything after the third colon, so it may itself contain : or @. An IPv6 host is written in square brackets, e.g. [2001:db8::1]:8080.

Raises:

ValueError – if the text is not one of these forms

ProxyProviders Exceptions

All custom exceptions for the ProxyProvider classes are defined here.

exception proxyproviders.exceptions.ProxyProviderException[source]

Bases: Exception

Base class for all ProxyProvider errors.

exception proxyproviders.exceptions.ProxyFetchException(message: str, status_code: int | None = None)[source]

Bases: ProxyProviderException

Raised when there is an error fetching proxies from the provider.

exception proxyproviders.exceptions.ProxyConversionException[source]

Bases: ProxyProviderException

Raised when there is an error converting proxy data to a standardized format.

exception proxyproviders.exceptions.ProxyInvalidResponseException(response: str)[source]

Bases: ProxyProviderException

Raised when the provider returns an invalid response.