Copy a request from your 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, 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-Typeand the site's ownX-…headers, such as CSRF tokens. - Leave out what belongs to the browser:
User-Agent,sec-ch-ua…,Sec-Fetch-…,Accept-Encoding,Accept-LanguageandPriority. Choose the matchingbrowserandlocaleinstead; they set all of these consistently.
A request copied from Chrome on Windows, for example, becomes:
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"
}'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])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));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)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
$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;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"])
}require "json"
require "net/http"
uri = URI("https://api.virginproxy.com/v1/requests")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer " + ENV.fetch("VP_KEY")
req["Content-Type"] = "application/json"
req.body = JSON.generate({
"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",
})
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, read_timeout: 180) { |http| http.request(req) }
data = JSON.parse(res.body)
abort(data["error"]["code"] + ": " + data["error"]["message"]) unless res.is_a?(Net::HTTPSuccess)
puts JSON.pretty_generate(data)import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Main {
public static void main(String[] args) throws Exception {
String payload = """
{
"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"
}
""";
HttpRequest req = HttpRequest.newBuilder(URI.create("https://api.virginproxy.com/v1/requests"))
.header("Authorization", "Bearer " + System.getenv("VP_KEY"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(180))
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> res = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() >= 300) {
System.err.println(res.statusCode() + " " + res.body()); // the error object: code, message
System.exit(1);
}
System.out.println(res.body()); // JSON: read it with the JSON library of your choice
}
}using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(180) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VP_KEY"));
var payload = """
{
"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"
}
""";
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.virginproxy.com/v1/requests");
req.Content = new StringContent(payload, Encoding.UTF8, "application/json");
var res = await http.SendAsync(req);
using var data = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
if (!res.IsSuccessStatusCode)
{
var e = data.RootElement.GetProperty("error");
Console.Error.WriteLine(e.GetProperty("code") + ": " + e.GetProperty("message"));
Environment.Exit(1);
}
Console.WriteLine(data.RootElement);/v1/requests≈ 1 creditOpen in PlaygroundConvert 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.
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 reqconst 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.
Was this page helpful?
Last updated