Cookies and sessions
Cookies are how websites remember a visitor: consent, language, cart, login. You can send them with a request, read the ones a site sets, and let a session keep them for you.
Send cookies
The simplest form is an object of names and values:
curl https://api.virginproxy.com/v1/requests \
-H "Authorization: Bearer $VP_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://httpbin.org/cookies",
"cookies": {
"theme": "dark",
"consent": "yes"
}
}'import os, requests
r = requests.post(
"https://api.virginproxy.com/v1/requests",
headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
json={
"url": "https://httpbin.org/cookies",
"cookies": {"theme": "dark", "consent": "yes"},
},
timeout=180,
)
data = r.json()
if not r.ok:
raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
print(data["body"])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://httpbin.org/cookies",
cookies: { theme: "dark", consent: "yes" },
}),
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.body);from virginproxy import VirginProxy # docs.virginproxy.com/sdk/virginproxy.py
vp = VirginProxy() # reads VP_KEY
data = vp.request({
"url": "https://httpbin.org/cookies",
"cookies": {"theme": "dark", "consent": "yes"},
})
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://httpbin.org/cookies",
cookies: { theme: "dark", consent: "yes" },
});
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://httpbin.org/cookies",
"cookies" => ["theme" => "dark", "consent" => "yes"],
], 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["body"], PHP_EOL;package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
func main() {
payload := []byte(`{
"url": "https://httpbin.org/cookies",
"cookies": {
"theme": "dark",
"consent": "yes"
}
}`)
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["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://httpbin.org/cookies",
"cookies" => { "theme" => "dark", "consent" => "yes" },
})
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://httpbin.org/cookies",
"cookies": {
"theme": "dark",
"consent": "yes"
}
}
""";
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://httpbin.org/cookies",
"cookies": {
"theme": "dark",
"consent": "yes"
}
}
""";
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 PlaygroundWhen a cookie should only go to certain hosts or paths, use a list:
{
"url": "https://www.example.com/shop/",
"cookies": [
{ "name": "consent", "value": "yes", "domain": ".example.com" },
{ "name": "cart", "value": "42", "path": "/shop" }
]
}| Field | Meaning |
|---|---|
name | Required. Up to 256 characters, the characters a cookie name may contain. |
value | Required. A string of up to 8,000 characters without ; or line breaks. |
domain | Optional. Without it the cookie goes to the target host only. With example.com or .example.com it also goes to its subdomains, for example after a redirect to www.example.com. |
path | Optional. Starts with /; the cookie goes only to paths below it. |
At most 200 cookies per request. A Cookie header in headers works too, which is handy when you copy one from your browser (see Copy a request from your browser). Both can be combined: your Cookie header comes first, the other cookies follow.
Read the cookies a site sets
Every response lists the cookies the target set, parsed, including those set on the way through redirects:
"cookies": [
{ "name": "session-id", "value": "262-4410173", "domain": ".shop.example", "path": "/",
"expires": "2027-11-17T10:12:08Z", "secure": true, "http_only": true, "same_site": "Lax" }
]expires, max_age and same_site appear only when the site set them. The raw headers are in headers["set-cookie"], a list with one entry per cookie of the final response.
API = "https://api.virginproxy.com/v1/requests"
AUTH = {"Authorization": "Bearer " + os.environ["VP_KEY"]}
jar = {c["name"]: c["value"] for c in data["cookies"]}
# send them along next time
requests.post(API, headers=AUTH, json={"url": "https://shop.example/cart", "cookies": jar}, timeout=180)const jar = Object.fromEntries(data.cookies.map((c) => [c.name, c.value]));
// send them along next time
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/cart", cookies: jar }),
});Let a session remember cookies
With a session, you do not have to carry cookies yourself. Cookies the site sets are remembered and sent automatically with the next requests of the same session to that site, just like in a browser tab. Cookies you send in cookies are remembered too.
curl https://api.virginproxy.com/v1/requests \
-H "Authorization: Bearer $VP_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://httpbin.org/cookies/set?step=1",
"session": "visitor-7"
}'import os, requests
r = requests.post(
"https://api.virginproxy.com/v1/requests",
headers={"Authorization": "Bearer " + os.environ["VP_KEY"]},
json={
"url": "https://httpbin.org/cookies/set?step=1",
"session": "visitor-7",
},
timeout=180,
)
data = r.json()
if not r.ok:
raise SystemExit(data["error"]["code"] + ": " + data["error"]["message"])
# the second request carries the cookie of the first one
r = requests.post(r.url, headers={"Authorization": "Bearer " + os.environ["VP_KEY"]}, timeout=180,
json={"url": "https://httpbin.org/cookies", "session": "visitor-7"})
print(r.json()["body"]) # {"cookies": {"step": "1"}}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://httpbin.org/cookies/set?step=1",
session: "visitor-7",
}),
signal: AbortSignal.timeout(180_000),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error.code + ": " + data.error.message);
// the second request carries the cookie of the first one
const again = await fetch(res.url, {
method: "POST",
headers: { Authorization: "Bearer " + process.env.VP_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ url: "https://httpbin.org/cookies", session: "visitor-7" }),
});
console.log((await again.json()).body); // {"cookies": {"step": "1"}}from virginproxy import VirginProxy # docs.virginproxy.com/sdk/virginproxy.py
vp = VirginProxy() # reads VP_KEY
data = vp.request({
"url": "https://httpbin.org/cookies/set?step=1",
"session": "visitor-7",
})
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://httpbin.org/cookies/set?step=1",
session: "visitor-7",
});
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://httpbin.org/cookies/set?step=1",
"session" => "visitor-7",
], 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://httpbin.org/cookies/set?step=1",
"session": "visitor-7"
}`)
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://httpbin.org/cookies/set?step=1",
"session" => "visitor-7",
})
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://httpbin.org/cookies/set?step=1",
"session": "visitor-7"
}
""";
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://httpbin.org/cookies/set?step=1",
"session": "visitor-7"
}
""";
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 Playground| How long | |
|---|---|
| Same IP | Up to 10 minutes from the first request of the session. See IPs and sessions. |
| Remembered cookies | Until 30 minutes after the last request of the session. Each request starts the 30 minutes again. |
After 10 minutes the session continues on a new IP with the same cookies, like a person whose connection changed. Use a new session name when you want to start over as a new visitor.
To keep the IP of a session but manage cookies yourself, send "cookie_jar": false. Without a session every request starts with no cookies except the ones you send; cookies set during its own redirects are still passed on to the next step.
Pages loaded with render share the cookies of their session in both directions. You can load one page in the browser and continue with plain requests in the same session.
Note
Remembered cookies are kept in memory only, for your session alone, and are deleted 30 minutes after the session was last used. They never appear in our logs.
Was this page helpful?
Last updated