Skip to content

Sandbox quickstart

Create a sandbox, run commands, upload and download files, then delete it.

You'll need a Keln API key and credits. See the Quickstart to get started. Python examples use requests (pip install requests).

Set your API key:

export KELN_API_KEY=sk-keln-…

1. Create a sandbox

curl https://sandbox.keln.ai/v1/sandboxes \
  -H "Authorization: Bearer $KELN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"timeout_s": 600}'
import base64
import json
import os
import uuid

import requests

API = "https://sandbox.keln.ai/v1"
http = requests.Session()
http.headers["Authorization"] = f"Bearer {os.environ['KELN_API_KEY']}"

response = http.post(
    f"{API}/sandboxes",
    json={"timeout_s": 600},
    headers={"Idempotency-Key": str(uuid.uuid4())},
)
response.raise_for_status()
sandbox = response.json()
sandbox_id = sandbox["id"]
print(sandbox_id, sandbox["state"])

Example response:

{
  "id": "sbx_4k2v9q0m7c1x8z5n3b6d",
  "object": "sandbox",
  "state": "running",
  "template": "base",
  "cpu": 2,
  "memory_mb": 2048,
  "disk_mb": 10240,
  "created_at": 1793740800,
  "started_at": 1793740801,
  "expires_at": 1793741400,
  "ended_at": null,
  "end_reason": null,
  "paused_at": null,
  "metadata": {},
  "network": { "internet": true },
  "ports": [],
  "port_token": null
}

timeout_s sets the sandbox lifetime in seconds. The default is 300 seconds.

Idempotency-Key lets you safely retry a create request. Requests with the same key and body return the original result for 24 hours.

The API returns 201 when the sandbox is running, usually within a few seconds. If startup takes longer, it returns 202 with state starting. You can send commands or file requests immediately. They'll wait until the sandbox is ready.

For curl, save the sandbox ID:

export SANDBOX=sbx_4k2v9q0m7c1x8z5n3b6d

2. Run a command

curl -N https://sandbox.keln.ai/v1/sandboxes/$SANDBOX/commands \
  -H "Authorization: Bearer $KELN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command": "echo hello from the sandbox"}'
def run(body):
    """Run a command, print its output as it arrives, and return its exit event."""
    url = f"{API}/sandboxes/{sandbox_id}/commands"
    with http.post(url, json=body, stream=True) as response:
        response.raise_for_status()
        event = None
        for line in response.iter_lines():
            line = line.decode()
            if line.startswith("event: "):
                event = line.removeprefix("event: ")
            elif line.startswith("data: "):
                data = json.loads(line.removeprefix("data: "))
                if event in ("stdout", "stderr"):
                    print(base64.b64decode(data["data"]).decode(errors="replace"), end="")
                elif event == "exit":
                    return data
                elif event == "error":
                    raise RuntimeError(data["error"]["message"])


print(run({"command": "echo hello from the sandbox"}))

The response streams Server-Sent Events (SSE). curl -N prints events as they arrive:

id: 1
event: started
data: {"command_id": "cmd_8x1c4v7b2n5m9k3j6h0g", "pid": 41}

id: 2
event: stdout
data: {"data": "aGVsbG8gZnJvbSB0aGUgc2FuZGJveAo=", "ts": 1793740802123}

id: 3
event: exit
data: {"exit_code": 0, "signal": null, "oom_killed": false}

stdout and stderr events contain base64-encoded output in data. To decode the output:

echo aGVsbG8gZnJvbSB0aGUgc2FuZGJveAo= | base64 --decode

3. Upload a file and run it

Upload a file with PUT. The request body contains the file contents. Paths must be absolute. The default user's home directory is /home/user.

cat > main.py <<'EOF'
print("hello from main.py")
open("/home/user/out.txt", "w").write("42\n")
EOF

curl -X PUT "https://sandbox.keln.ai/v1/sandboxes/$SANDBOX/files?path=/home/user/main.py" \
  -H "Authorization: Bearer $KELN_API_KEY" \
  -H "Content-Type: application/octet-stream" \
  --data-binary @main.py

curl -N https://sandbox.keln.ai/v1/sandboxes/$SANDBOX/commands \
  -H "Authorization: Bearer $KELN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"argv": ["python3", "/home/user/main.py"]}'
code = b'print("hello from main.py")\nopen("/home/user/out.txt", "w").write("42\\n")\n'
response = http.put(
    f"{API}/sandboxes/{sandbox_id}/files",
    params={"path": "/home/user/main.py"},
    data=code,
    headers={"Content-Type": "application/octet-stream"},
)
response.raise_for_status()

print(run({"argv": ["python3", "/home/user/main.py"]}))

argv runs a program directly. command, in step 2, runs a shell line through bash -lc.

4. Download a file

curl "https://sandbox.keln.ai/v1/sandboxes/$SANDBOX/files?path=/home/user/out.txt" \
  -H "Authorization: Bearer $KELN_API_KEY"
response = http.get(
    f"{API}/sandboxes/{sandbox_id}/files",
    params={"path": "/home/user/out.txt"},
)
response.raise_for_status()
print(response.content)

The response contains the raw file bytes.

5. Delete the sandbox

curl -X DELETE https://sandbox.keln.ai/v1/sandboxes/$SANDBOX \
  -H "Authorization: Bearer $KELN_API_KEY"
stopped = http.delete(f"{API}/sandboxes/{sandbox_id}").json()
print(stopped["state"], stopped["end_reason"])

The response returns the sandbox with state set to stopped and end_reason set to deleted.

Billing stops immediately, and the sandbox contents are deleted. Sandboxes also stop automatically when they reach expires_at.

Where to go next