# Copy a request from your browser

> Copy a request from your browser's developer tools as cURL and send it through VirginProxy: in the playground, by hand or with Python or Node.js.

Source: https://docs.virginproxy.com/copy-from-browser/

The quickest way to get a difficult request right is to copy it from your own browser. The developer tools of every major browser can copy a request as a cURL command, with its headers, cookies and body.

## Copy the request

| Browser | How |
| --- | --- |
| Chrome, Edge | Open the developer tools (F12, or Ctrl+Shift+I; on a Mac Cmd+Option+I), go to **Network** and reload the page. Right-click the request, then **Copy** › **Copy as cURL**. On Windows choose **Copy as cURL (bash)**. |
| Firefox | Developer tools › **Network**, right-click the request › **Copy Value** › **Copy as cURL**. |
| Safari | Turn on the developer features under Settings › Advanced. Then Web Inspector › **Network**, right-click the request › **Copy as cURL**. |

For a page, copy the first request of type "document". For data that a page loads afterwards, filter by "Fetch/XHR" and pick the request whose response holds the data.

## Import it in the playground

In the playground of the [dashboard](https://dash.virginproxy.com/), paste the command into the cURL import. Method, URL, query parameters, headers, cookies and body are filled in; you can send the request at once and copy it as code for your language.

## Translate it by hand

| In the cURL command | In the API request |
| --- | --- |
| the URL | `url` (or `url` plus `params`) |
| `-X POST` | `method` |
| `-H 'name: value'` | `headers` |
| `-b 'a=1; b=2'` or `-H 'cookie: …'` | `headers.Cookie` or `cookies` |
| `--data-raw '…'` | `body` (or `json` when it is JSON); the method becomes POST |
| `--compressed` | nothing: the browser profile takes care of it |

### Which headers to keep

- Keep what belongs to the site: `Cookie`, `Authorization`, `Referer`, `Origin`, `Content-Type` and the site's own `X-…` headers, such as CSRF tokens.
- Leave out what belongs to the browser: `User-Agent`, `sec-ch-ua…`, `Sec-Fetch-…`, `Accept-Encoding`, `Accept-Language` and `Priority`. Choose the matching `browser` and `locale` instead; they set all of these consistently.

A request copied from Chrome on Windows, for example, becomes:

**cURL**

```bash
curl https://api.virginproxy.com/v1/requests \
  -H "Authorization: Bearer $VP_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://shop.example/api/cart",
    "method": "POST",
    "browser": "chrome",
    "locale": "en-GB",
    "headers": {
      "Cookie": "session-id=…; consent=yes",
      "Referer": "https://shop.example/product/42",
      "Origin": "https://shop.example",
      "X-CSRF-Token": "…"
    },
    "json": {
      "product": 42,
      "quantity": 1
    },
    "session": "shop-visitor-1"
  }'
```

**Python**

```python
import os, requests

r = requests.post(
    "https://api.virginproxy.com/v1/requests",
    headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
    json={
        "url": "https://shop.example/api/cart",
        "method": "POST",
        "browser": "chrome",
        "locale": "en-GB",
        "headers": {
            "Cookie": "session-id=…; consent=yes",
            "Referer": "https://shop.example/product/42",
            "Origin": "https://shop.example",
            "X-CSRF-Token": "…",
        },
        "json": {"product": 42, "quantity": 1},
        "session": "shop-visitor-1",
    },
    timeout=180,
)
data = r.json()
if not r.ok:
    raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["status"], data["body"][:200])
```

**Node.js**

```javascript
const res = await fetch("https://api.virginproxy.com/v1/requests", {
  method: "POST",
  headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({
    url: "https://shop.example/api/cart",
    method: "POST",
    browser: "chrome",
    locale: "en-GB",
    headers: {
      Cookie: "session-id=…; consent=yes",
      Referer: "https://shop.example/product/42",
      Origin: "https://shop.example",
      "X-CSRF-Token": "…",
    },
    json: { product: 42, quantity: 1 },
    session: "shop-visitor-1",
  }),
  signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
console.log(data.status, data.body.slice(0, 200));
```

**Python SDK**

```pysdk
from virginproxy import VirginProxy  # docs.virginproxy.com/sdk/virginproxy.py

vp = VirginProxy()  # reads VP_KEY
data = vp.request({
    "url": "https://shop.example/api/cart",
    "method": "POST",
    "browser": "chrome",
    "locale": "en-GB",
    "headers": {
        "Cookie": "session-id=…; consent=yes",
        "Referer": "https://shop.example/product/42",
        "Origin": "https://shop.example",
        "X-CSRF-Token": "…",
    },
    "json": {"product": 42, "quantity": 1},
    "session": "shop-visitor-1",
})
print(data)
```

**Node SDK**

```nodesdk
import { VirginProxy } from "./virginproxy.mjs"; // docs.virginproxy.com/sdk/virginproxy.mjs

const vp = new VirginProxy(); // reads VP_KEY
const data = await vp.request({
  url: "https://shop.example/api/cart",
  method: "POST",
  browser: "chrome",
  locale: "en-GB",
  headers: {
    Cookie: "session-id=…; consent=yes",
    Referer: "https://shop.example/product/42",
    Origin: "https://shop.example",
    "X-CSRF-Token": "…",
  },
  json: { product: 42, quantity: 1 },
  session: "shop-visitor-1",
});
console.log(data);
```

**PHP**

```php
<?php
$ch = curl_init("https://api.virginproxy.com/v1/requests");
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 180,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("VP_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "url" => "https://shop.example/api/cart",
        "method" => "POST",
        "browser" => "chrome",
        "locale" => "en-GB",
        "headers" => [
            "Cookie" => "session-id=…; consent=yes",
            "Referer" => "https://shop.example/product/42",
            "Origin" => "https://shop.example",
            "X-CSRF-Token" => "…",
        ],
        "json" => ["product" => 42, "quantity" => 1],
        "session" => "shop-visitor-1",
    ], JSON_UNESCAPED_SLASHES),
]);
$data = json_decode(curl_exec($ch), true);
if (isset($data["error"])) {
    exit($data["error"]["code"] . ": " . $data["error"]["message"] . PHP_EOL);
}
echo $data["status"], " ", $data["body"], PHP_EOL;
```

**Go**

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func main() {
	payload := []byte(`{
  "url": "https://shop.example/api/cart",
  "method": "POST",
  "browser": "chrome",
  "locale": "en-GB",
  "headers": {
    "Cookie": "session-id=…; consent=yes",
    "Referer": "https://shop.example/product/42",
    "Origin": "https://shop.example",
    "X-CSRF-Token": "…"
  },
  "json": {
    "product": 42,
    "quantity": 1
  },
  "session": "shop-visitor-1"
}`)
	req, err := http.NewRequest("POST", "https://api.virginproxy.com/v1/requests", bytes.NewReader(payload))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("VP_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 180 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	var data map[string]any
	if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
		log.Fatal(err)
	}
	if res.StatusCode >= 300 {
		e := data["error"].(map[string]any)
		log.Fatalf("%v: %v", e["code"], e["message"])
	}
	fmt.Println(data["status"], data["body"])
}
```

POST`/v1/requests`[≈ 1 credit](https://docs.virginproxy.com/billing/#cost)[Open in Playground](https://dash.virginproxy.com/playground#request=eyJ1cmwiOiJodHRwczovL3Nob3AuZXhhbXBsZS9hcGkvY2FydCIsIm1ldGhvZCI6IlBPU1QiLCJicm93c2VyIjoiY2hyb21lIiwibG9jYWxlIjoiZW4tR0IiLCJoZWFkZXJzIjp7IkNvb2tpZSI6InNlc3Npb24taWQ94oCmOyBjb25zZW50PXllcyIsIlJlZmVyZXIiOiJodHRwczovL3Nob3AuZXhhbXBsZS9wcm9kdWN0LzQyIiwiT3JpZ2luIjoiaHR0cHM6Ly9zaG9wLmV4YW1wbGUiLCJYLUNTUkYtVG9rZW4iOiLigKYifSwianNvbiI6eyJwcm9kdWN0Ijo0MiwicXVhbnRpdHkiOjF9LCJzZXNzaW9uIjoic2hvcC12aXNpdG9yLTEifQ)

## Convert it in code

These small functions turn a copied cURL command into a request for the API. They cover what browsers produce for ordinary requests; for commands with `$'…'` quoting, copy the request again with the bash variant or translate it by hand.

**Python**

```python
import shlex

BROWSER_HEADERS = {"user-agent", "accept-encoding", "accept-language", "priority", "connection"}

def curl_to_request(command):
    args = shlex.split(command.replace("\\\n", " "))
    req, headers, i = {"method": "GET"}, {}, 1
    while i < len(args):
        a = args[i]
        value = args[i + 1] if i + 1 < len(args) else ""
        if a in ("-X", "--request"):
            req["method"], i = value.upper(), i + 1
        elif a in ("-H", "--header"):
            name, _, v = value.partition(":")
            low = name.strip().lower()
            if low not in BROWSER_HEADERS and not low.startswith(("sec-ch-ua", "sec-fetch-")):
                headers[name.strip()] = v.strip()
            i += 1
        elif a in ("-b", "--cookie"):
            headers["Cookie"], i = value, i + 1
        elif a in ("-d", "--data", "--data-raw", "--data-binary"):
            req["body"], i = value, i + 1
            if req["method"] == "GET":
                req["method"] = "POST"
        elif a.startswith("http"):
            req["url"] = a
        i += 1
    if headers:
        req["headers"] = headers
    return req
```

**Node.js**

```javascript
const BROWSER_HEADERS = new Set(["user-agent", "accept-encoding", "accept-language", "priority", "connection"]);

function words(cmd) {
  const out = [];
  let cur = "", quote = null, started = false;
  cmd = cmd.replace(/\\\r?\n/g, " ");
  for (let i = 0; i < cmd.length; i++) {
    const ch = cmd[i];
    if (quote) {
      if (ch === quote) quote = null;
      else if (ch === "\\" && quote === '"') cur += cmd[++i];
      else cur += ch;
    } else if (ch === "'" || ch === '"') { quote = ch; started = true; }
    else if (/\s/.test(ch)) { if (cur || started) out.push(cur); cur = ""; started = false; }
    else if (ch === "\\") cur += cmd[++i];
    else cur += ch;
  }
  if (cur || started) out.push(cur);
  return out;
}

export function curlToRequest(command) {
  const args = words(command);
  const req = { method: "GET" }, headers = {};
  for (let i = 1; i < args.length; i++) {
    const a = args[i], value = args[i + 1] ?? "";
    if (a === "-X" || a === "--request") { req.method = value.toUpperCase(); i++; }
    else if (a === "-H" || a === "--header") {
      const at = value.indexOf(":");
      const name = value.slice(0, at).trim(), low = name.toLowerCase();
      if (!BROWSER_HEADERS.has(low) && !low.startsWith("sec-ch-ua") && !low.startsWith("sec-fetch-")) headers[name] = value.slice(at + 1).trim();
      i++;
    } else if (a === "-b" || a === "--cookie") { headers.Cookie = value; i++; }
    else if (["-d", "--data", "--data-raw", "--data-binary"].includes(a)) {
      req.body = value; i++;
      if (req.method === "GET") req.method = "POST";
    } else if (a.startsWith("http")) req.url = a;
  }
  if (Object.keys(headers).length) req.headers = headers;
  return req;
}
```

Add `browser`, `locale` and, for several requests in a row, `session` to the result before you send it.

> **Note:** A copied request contains your cookies, and with them your login. Treat it like a password: do not paste it into public places or share it. Use only your own logins, and respect the terms of use of the site.
