Get an API key Your API keys

VirginProxy with Python

A complete, copy-ready client for VirginProxy in Python: one function that sends a request, retries what is worth retrying, and returns the answer with its price. It uses nothing but the standard HTTP library.

Set your key as an environment variable first:

Shell
export VP_KEY="vp_live_…"

The client

vp.py
# pip install requests
import base64, os, time
import requests

API = "https://api.virginproxy.com/v1/requests"
RETRYABLE = {"rate_limited", "concurrency_limited", "busy", "maintenance",
             "timeout", "target_unreachable", "connection_failed"}

http = requests.Session()
http.headers["Authorization"] = "Bearer " + os.environ["VP_KEY"]


def fetch(url, retries=3, **options):
    """Fetch url through VirginProxy and return the JSON answer."""
    for attempt in range(retries + 1):
        r = http.post(API, json={"url": url, **options}, timeout=180)
        data = r.json()
        if r.ok:
            return data
        error = data["error"]
        if error["code"] not in RETRYABLE or attempt == retries:
            raise RuntimeError(f"{error['code']}: {error['message']}")
        time.sleep(error.get("retry_after_ms", 1000 * 2 ** attempt) / 1000)


page = fetch("https://httpbin.org/html")
print(page["status"], page["exit"]["ip"], page["cost"]["credits"])

What the client does

See Limits and retries for the reasoning and Errors for every code.

Keep one IP for several requests

Python
first = fetch("https://shop.example/cart", session="cart-42")
second = fetch("https://shop.example/checkout", session="cart-42")
assert first["exit"]["ip"] == second["exit"]["ip"]  # same IP for up to 10 minutes

Images, PDFs and other files

Python
data = fetch("https://httpbin.org/image/png")
raw = base64.b64decode(data["body"]) if data["body_encoding"] == "base64" else data["body"].encode()
with open("image.png", "wb") as f:
    f.write(raw)

Many URLs in parallel

Keep at most as many requests running as your plan allows (1 on Free, 5 on Starter, 20 on Growth, 50 on Scale). More only produces concurrency_limited.

Python
from concurrent.futures import ThreadPoolExecutor

urls = [f"https://shop.example/product/{i}" for i in range(1, 101)]
with ThreadPoolExecutor(max_workers=5) as workers:       # = your plan's limit
    for url, data in zip(urls, workers.map(fetch, urls)):
        print(url, data["status"], data["cost"]["credits"])

Was this page helpful?

Last updated