# VirginProxy with Python

> A complete Python client for the VirginProxy API with retries, sessions, binary downloads and parallel requests, using requests.

Source: https://docs.virginproxy.com/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:

```bash
export VP_KEY="vp_live_…"
```

## The client

*vp.py:*

```python
# 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

- Sends one `POST /v1/requests` per call and waits up to 180 seconds: enough for your plan's timeout, the wait for a free slot and a `fresh_ip`. With `retry`, allow one more timeout per extra attempt.
- Retries only errors that can succeed later (`rate_limited`, `concurrency_limited`, `busy`, `maintenance`, `timeout`, `target_unreachable`, `connection_failed`), waiting `retry_after_ms` when the API sends it. None of these is charged.
- Raises every other error at once: a wrong URL or key does not get better by trying again.

See [Limits and retries](https://docs.virginproxy.com/limits/) for the reasoning and [Errors](https://docs.virginproxy.com/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"])
```
