> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vers.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Python & TypeScript cookbook

> Copy-paste /api/v2 workflows in Python (httpx) and TypeScript (fetch): create computers, run commands, transfer files, branch in parallel, and sleep/wake.

Vers exposes a standard JSON REST API at `https://api.vers.sh/api/v2` with
Bearer token auth and durable, idempotent operations. You don't need a heavy
client library to integrate it — the complete lifecycle fits in \~80 lines of
standard `httpx` (Python) or native `fetch` (TypeScript / Node 20+ / Bun).

> [!NOTE]
>
> Lifecycle mutations (create, checkpoint, restore, delete, image import) take a
> UUID `Idempotency-Key` header and return `202 Accepted` with a durable operation
> to poll or stream. Calls like branch, exec, sleep, and wake return directly.
> See [Durable operations](https://docs.vers.sh/api-reference/overview.md#durable-operations-and-idempotency).

## Prerequisites

* Export `VERS_API_KEY` from your [Vers dashboard](https://docs.vers.sh/get-api-key.md).
* **Python:** Python 3.10+ with `pip install httpx`.
* **TypeScript:** Node 20+, Bun, or Deno (uses built-in `fetch` and `node:crypto`).

## End-to-end lifecycle example

This script imports an OCI image once, starts a KVM computer, writes and reads a
file, executes a direct-argv command, captures a full-state checkpoint, fans out
4 parallel branches (`$0` per branch), sleeps and wakes the computer, and cleans up.

> [tab] Python (httpx)
>
> ```python vers_client.py theme={"theme":{"light":"min-light","dark":"min-dark"}}
> import base64
> import os
> import time
> import uuid
> import httpx
>
> BASE_URL = os.environ.get("VERS_ORCHESTRATOR_URL", "https://api.vers.sh")
> API_KEY = os.environ["VERS_API_KEY"]
>
> client = httpx.Client(
>     base_url=BASE_URL,
>     headers={"Authorization": f"Bearer {API_KEY}"},
>     timeout=120.0,
> )
>
>
> def wait_operation(op: dict, poll_s: float = 0.5) -> dict:
>     """Poll a durable 202 Operation until it reaches a terminal state."""
>     op_id = op["operation_id"]
>     while op["status"] == "pending":
>         time.sleep(poll_s)
>         op = client.get(f"/api/v2/operations/{op_id}").raise_for_status().json()
>     if op["status"] != "succeeded":
>         raise RuntimeError(f"Operation {op_id} {op['status']}: {op.get('failure')}")
>     return op
>
>
> # 1. Import a public OCI image (reusable across runs; cached by digest)
> img_op = client.post(
>     "/api/v2/images",
>     headers={"Idempotency-Key": str(uuid.uuid4())},
>     json={
>         "name": "python-3-12-slim",
>         "source": {
>             "type": "public_registry",
>             "image_ref": "docker.io/library/python:3.12-slim",
>         },
>     },
> ).raise_for_status().json()
> image_id = wait_operation(img_op)["result"]["id"]
>
> # 2. Boot a KVM microVM (2 vCPU / 4 GiB RAM / 16 GiB disk)
> create_op = client.post(
>     "/api/v2/computers",
>     headers={"Idempotency-Key": str(uuid.uuid4())},
>     json={
>         "keep_alive": False,  # eligible for auto-sleep ($0 compute while asleep)
>         "vm_config": {
>             "oci_image_id": image_id,
>             "vcpu_count": 2,
>             "mem_size_mib": 4096,
>             "fs_size_mib": 16384,
>             "command": ["sleep", "infinity"],
>             "labels": {"name": "cookbook-base"},
>         },
>     },
> ).raise_for_status().json()
> computer_id = wait_operation(create_op)["result"]["id"]
>
> # 3. Write and read a file (base64 JSON or raw application/octet-stream)
> client.put(
>     f"/api/v2/computers/{computer_id}/files",
>     json={
>         "path": "/workspace/app.py",
>         "content_b64": base64.b64encode(b"print('ready from vers')\n").decode(),
>         "create_dirs": True,
>         "mode": 0o644,
>     },
> ).raise_for_status()
>
> file_resp = client.get(
>     f"/api/v2/computers/{computer_id}/files",
>     params={"path": "/workspace/app.py"},
> ).raise_for_status().json()
> print("Read back:", base64.b64decode(file_resp["content_b64"]).decode().strip())
>
> # 4. Run a direct-argv command (no implicit shell; pass keep_background=True for daemons)
> exec_res = client.post(
>     f"/api/v2/computers/{computer_id}/exec",
>     json={
>         "command": ["python3", "/workspace/app.py"],
>         "working_dir": "/workspace",
>         "timeout_secs": 300,
>     },
> ).raise_for_status().json()
> print("Exec:", exec_res["exit_code"], exec_res["stdout"].strip())
>
> # 5. Capture a full-state checkpoint (CPU, RAM, processes, disk)
> ckpt_op = client.post(
>     f"/api/v2/computers/{computer_id}/checkpoints",
>     headers={"Idempotency-Key": str(uuid.uuid4())},
>     json={"name": "warm-state", "keep_paused": False},
> ).raise_for_status().json()
> checkpoint_id = wait_operation(ckpt_op)["result"]["id"]
>
> # 6. Fan out 4 parallel branches from that checkpoint ($0 per branch)
> branches = client.post(
>     "/api/v2/branches",
>     json={
>         "source": {"type": "checkpoint", "checkpoint_id": checkpoint_id},
>         "count": 4,
>     },
> ).raise_for_status().json()["computers"]
> branch_ids = [c["computer_id"] for c in branches]
> print("Branched computers:", branch_ids)
>
> # 7. Sleep ($0 active compute) and wake (retains RAM, processes, and private IP)
> client.post(f"/api/v2/computers/{computer_id}/sleep").raise_for_status()
> woke = client.post(f"/api/v2/computers/{computer_id}/wake").raise_for_status().json()
> print("Woke with IP:", woke["ip"])
>
> # 8. Clean up all computers
> for cid in [computer_id, *branch_ids]:
>     del_op = client.delete(
>         f"/api/v2/computers/{cid}",
>         headers={"Idempotency-Key": str(uuid.uuid4())},
>     ).raise_for_status().json()
>     wait_operation(del_op)
> ```

> [tab] TypeScript (fetch)
>
> ```typescript vers-client.ts theme={"theme":{"light":"min-light","dark":"min-dark"}}
> import { randomUUID } from "node:crypto";
>
> const BASE_URL = process.env.VERS_ORCHESTRATOR_URL ?? "https://api.vers.sh";
> const API_KEY = process.env.VERS_API_KEY!;
>
> interface Operation {
>   operation_id: string;
>   status: "pending" | "succeeded" | "failed" | "quarantined";
>   cursor: number;
>   result?: { kind: string; id: string } | null;
>   failure?: unknown;
> }
>
> async function versFetch<T>(
>   path: string,
>   init: RequestInit & { idempotent?: boolean } = {},
> ): Promise<T> {
>   const headers = new Headers(init.headers);
>   headers.set("Authorization", `Bearer ${API_KEY}`);
>   if (init.body && !headers.has("Content-Type")) {
>     headers.set("Content-Type", "application/json");
>   }
>   if (init.idempotent) {
>     headers.set("Idempotency-Key", randomUUID());
>   }
>   const res = await fetch(`${BASE_URL}${path}`, { ...init, headers });
>   if (!res.ok) {
>     throw new Error(`Vers ${res.status} ${path}: ${await res.text()}`);
>   }
>   if (res.status === 204) return undefined as T;
>   return (await res.json()) as T;
> }
>
> async function waitOperation(op: Operation): Promise<Operation> {
>   let current = op;
>   while (current.status === "pending") {
>     await new Promise((r) => setTimeout(r, 500));
>     current = await versFetch<Operation>(`/api/v2/operations/${current.operation_id}`);
>   }
>   if (current.status !== "succeeded") {
>     throw new Error(`Operation ${current.operation_id} ${current.status}: ${JSON.stringify(current.failure)}`);
>   }
>   return current;
> }
>
> async function main() {
>   // 1. Import a public OCI image (reusable across runs)
>   const imgOp = await waitOperation(
>     await versFetch<Operation>("/api/v2/images", {
>       method: "POST",
>       idempotent: true,
>       body: JSON.stringify({
>         name: "node-22-slim",
>         source: {
>           type: "public_registry",
>           image_ref: "docker.io/library/node:22-bookworm-slim",
>         },
>       }),
>     }),
>   );
>   const imageId = imgOp.result!.id;
>
>   // 2. Boot a KVM microVM (2 vCPU / 4 GiB RAM / 16 GiB disk)
>   const createOp = await waitOperation(
>     await versFetch<Operation>("/api/v2/computers", {
>       method: "POST",
>       idempotent: true,
>       body: JSON.stringify({
>         keep_alive: false,
>         vm_config: {
>           oci_image_id: imageId,
>           vcpu_count: 2,
>           mem_size_mib: 4096,
>           fs_size_mib: 16384,
>           command: ["sleep", "infinity"],
>           labels: { name: "cookbook-base" },
>         },
>       }),
>     }),
>   );
>   const computerId = createOp.result!.id;
>
>   // 3. Write and read a file
>   await versFetch(`/api/v2/computers/${computerId}/files`, {
>     method: "PUT",
>     body: JSON.stringify({
>       path: "/workspace/hello.mjs",
>       content_b64: Buffer.from("console.log('ready from vers');\n").toString("base64"),
>       create_dirs: true,
>       mode: 0o644,
>     }),
>   });
>
>   const file = await versFetch<{ content_b64: string }>(
>     `/api/v2/computers/${computerId}/files?path=${encodeURIComponent("/workspace/hello.mjs")}`,
>   );
>   console.log("Read back:", Buffer.from(file.content_b64, "base64").toString("utf8").trim());
>
>   // 4. Execute a direct-argv command
>   const exec = await versFetch<{ exit_code: number; stdout: string; stderr: string }>(
>     `/api/v2/computers/${computerId}/exec`,
>     {
>       method: "POST",
>       body: JSON.stringify({
>         command: ["node", "/workspace/hello.mjs"],
>         working_dir: "/workspace",
>         timeout_secs: 300,
>       }),
>     },
>   );
>   console.log("Exec:", exec.exit_code, exec.stdout.trim());
>
>   // 5. Branch directly from the live computer into 4 parallel copies ($0/branch)
>   const { computers: branches } = await versFetch<{
>     computers: Array<{ computer_id: string; ip: string; name?: string | null }>;
>   }>("/api/v2/branches", {
>     method: "POST",
>     body: JSON.stringify({
>       source: { type: "computer", computer_id: computerId },
>       count: 4,
>     }),
>   });
>   const branchIds = branches.map((b) => b.computer_id);
>   console.log("Branched computers:", branchIds);
>
>   // 6. Sleep ($0 compute) and wake
>   await versFetch(`/api/v2/computers/${computerId}/sleep`, { method: "POST" });
>   const woke = await versFetch<{ ip: string }>(`/api/v2/computers/${computerId}/wake`, {
>     method: "POST",
>   });
>   console.log("Woke with IP:", woke.ip);
>
>   // 7. Clean up all computers
>   for (const id of [computerId, ...branchIds]) {
>     await waitOperation(
>       await versFetch<Operation>(`/api/v2/computers/${id}`, {
>         method: "DELETE",
>         idempotent: true,
>       }),
>     );
>   }
> }
>
> main().catch(console.error);
> ```

## Streaming operation progress instead of polling

Instead of polling `GET /api/v2/operations/{operation_id}`, you can stream
newline-delimited JSON (`application/x-ndjson`) events from
`GET /api/v2/operations/{operation_id}/events?cursor=0&follow=true`. If your
client disconnects, reconnect with the last seen `operation.cursor`.

> [tab] Python (httpx)
>
> ```python theme={"theme":{"light":"min-light","dark":"min-dark"}}
> import json
>
> def stream_operation(op_id: str, cursor: int = 0) -> dict:
>     with client.stream(
>         "GET",
>         f"/api/v2/operations/{op_id}/events",
>         params={"cursor": cursor, "follow": "true"},
>     ) as resp:
>         resp.raise_for_status()
>         last_op = None
>         for line in resp.iter_lines():
>             if not line:
>                 continue
>             event = json.loads(line)
>             if event["type"] == "snapshot":
>                 last_op = event["operation"]
>                 if last_op["status"] != "pending":
>                     return last_op
>             elif event["type"] == "end" and event["terminal"] and last_op:
>                 return last_op
>     raise RuntimeError(f"Stream ended before operation {op_id} finished")
> ```

> [tab] TypeScript (fetch)
>
> ```typescript theme={"theme":{"light":"min-light","dark":"min-dark"}}
> async function streamOperation(opId: string, cursor = 0): Promise<Operation> {
>   const res = await fetch(
>     `${BASE_URL}/api/v2/operations/${opId}/events?cursor=${cursor}&follow=true`,
>     { headers: { Authorization: `Bearer ${API_KEY}` } },
>   );
>   if (!res.ok || !res.body) {
>     throw new Error(`Stream failed: ${res.status}`);
>   }
>   const reader = res.body.getReader();
>   const decoder = new TextDecoder();
>   let buf = "";
>   let lastOp: Operation | undefined;
>
>   for (;;) {
>     const { done, value } = await reader.read();
>     if (done) break;
>     buf += decoder.decode(value, { stream: true });
>     let idx: number;
>     while ((idx = buf.indexOf("\n")) !== -1) {
>       const line = buf.slice(0, idx).trim();
>       buf = buf.slice(idx + 1);
>       if (!line) continue;
>       const event = JSON.parse(line);
>       if (event.type === "snapshot") {
>         lastOp = event.operation;
>         if (lastOp && lastOp.status !== "pending") return lastOp;
>       } else if (event.type === "end" && event.terminal && lastOp) {
>         return lastOp;
>       }
>     }
>   }
>   throw new Error(`Stream ended before operation ${opId} finished`);
> }
> ```

## Practical tips for production callers

* **Pass `keep_background: true` for daemons:** By default, `POST /exec` reaps background processes when the command exits. Set `keep_background: true` when starting dev servers or background workers so they remain alive across subsequent `exec` and `checkpoint` calls.
* **Reuse the same `Idempotency-Key` on network retries:** If a create or checkpoint call times out before you read the response, replaying the exact same request with the same UUID converges on the original operation instead of creating duplicate computers.
* **Avoid shell parsing when possible:** `POST /exec` executes `command` directly as argv (`["pytest", "-q"]`). Wrap explicitly in `["bash", "-lc", "..."]` only when you need shell pipes or redirects.

## Next steps

> [card] [Multi-VM project networks](https://docs.vers.sh/guides/project-networks.md)
>
> Put app + Postgres computers on an isolated private network and branch the whole stack.

> [card] [REST API reference](https://docs.vers.sh/api-reference/overview.md)
>
> Browse all 89 generated `/api/v2` endpoints and try them interactively.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.