# Calling the Sandscale sandbox API from Python with requests, no SDK

> A small Python client for the sandbox REST API: start a sandbox, write files, run a command, read results, stop it, and turn error responses into exceptions you can act on.

A small Python client for the sandbox REST API: start a sandbox, write files, run a command, read results, stop it, and turn error responses into exceptions you can act on.

November 24, 2026 · 5 min read · The Sandscale team

Sometimes you do not want an SDK in the dependency tree: a small script, a locked-down service, or a codebase that already wraps every HTTP call its own way. The sandbox API underneath our SDKs is plain HTTP and JSON, so from Python you can drive it with `requests` and under 80 lines of code. This post builds that client, explains the choices in it, and lists what to add before you lean on it in production.

Everything here comes from the [sandbox API guide](https://sandscale.dev/docs/guides/sandboxes-api) and the [Sandboxes API reference](https://sandscale.dev/docs/reference/api/sandboxes). If something in this post and the reference disagree, trust the reference.

## The five calls

A sandbox’s whole life is five requests against `https://api.sandscale.dev/api/v1/sandbox`:

| Step | Request | Permission |
| --- | --- | --- |
| Start | `POST /instances` | `sandboxes:create` |
| Write a file | `PUT /instances/{id}/files` | `sandboxes:use` |
| Run a command | `POST /instances/{id}/exec` | `sandboxes:use` |
| Read a file or list a folder | `GET /instances/{id}/files?path=...` | `sandboxes:use` |
| Stop | `DELETE /instances/{id}` | `sandboxes:manage` in the reference |

Every request carries `Authorization: Bearer <key>` with a personal API key. The guide says a key with `sandboxes:create` and `sandboxes:use` is enough to follow it, while the reference lists `sandboxes:manage` for `DELETE`. If your stop calls come back `403`, that is the permission to check. Our post on [scoping API keys](https://sandscale.dev/blog/scoping-api-keys-for-agents-and-ci) covers which key should hold what.

## The client

```python
import base64
import os

import requests

API = "https://api.sandscale.dev/api/v1/sandbox"

class SandboxAPIError(Exception):
    def __init__(self, status, code, message, request_id):
        super().__init__(f"{status} {code}: {message} (request {request_id})")
        self.status = status
        self.code = code
        self.request_id = request_id

class Sandboxes:
    def __init__(self, api_key=None):
        self.http = requests.Session()
        key = api_key or os.environ["SANDSCALE_API_KEY"]
        self.http.headers["Authorization"] = f"Bearer {key}"

    def _call(self, method, path, timeout=30, **kwargs):
        r = self.http.request(method, f"{API}{path}", timeout=timeout, **kwargs)
        if r.ok:
            return r.json() if r.content else None
        try:
            body = r.json()
        except ValueError:
            body = {}
        err = body.get("error") if isinstance(body.get("error"), dict) else body
        raise SandboxAPIError(
            r.status_code,
            err.get("code") or f"http_{r.status_code}",
            err.get("message") or r.reason,
            err.get("request_id") or r.headers.get("X-Request-ID"),
        )

    def create(self, template="builtin:python", ttl_seconds=600, **fields):
        body = {"template_id": template, "ttl_seconds": ttl_seconds, **fields}
        return self._call("POST", "/instances", json=body)

    def run(self, sandbox_id, command, timeout_sec=60, **fields):
        body = {"command": command, "timeout_sec": timeout_sec, **fields}
        # The HTTP call must outlive the command, so give it a margin.
        return self._call("POST", f"/instances/{sandbox_id}/exec", json=body, timeout=timeout_sec + 30)

    def write_file(self, sandbox_id, path, data):
        if isinstance(data, str):
            data = data.encode()
        body = {"path": path, "content": base64.b64encode(data).decode()}
        self._call("PUT", f"/instances/{sandbox_id}/files", json=body)

    def read_file(self, sandbox_id, path):
        got = self._call("GET", f"/instances/{sandbox_id}/files", params={"path": path})
        if got.get("type") != "file":
            raise ValueError(f"{path} is not a regular file")
        return base64.b64decode(got.get("content", ""))

    def list_dir(self, sandbox_id, path):
        got = self._call("GET", f"/instances/{sandbox_id}/files", params={"path": path})
        if got.get("type") != "dir":
            raise ValueError(f"{path} is not a directory")
        return got.get("entries", [])

    def stop(self, sandbox_id):
        try:
            self._call("DELETE", f"/instances/{sandbox_id}")
        except SandboxAPIError as e:
            if e.code != "sandbox_not_found":
                raise
```

## Why it looks like this

### One session, one header

A `requests.Session` reuses connections and holds the `Authorization` header, so no call can forget it. The key comes from `SANDSCALE_API_KEY` in the environment, never from the source file.

### Every call has a timeout

`requests` waits forever by default. Each call here passes a timeout, 30 seconds unless the caller says otherwise.

`run` is the exception that proves the rule. The exec request does not answer until the command finishes, so the HTTP timeout must be longer than the command’s own `timeout_sec`, or your client gives up on a command that is still running and you lose its result. The client adds a 30 second margin. Our post on [the three clocks](https://sandscale.dev/blog/timeouts-for-agent-sandboxes) explains how the sandbox lifetime, command timeout and HTTP timeout fit together.

### Files travel as base64

`PUT .../files` takes JSON with the file’s `path` and its `content` in base64, so binary files work the same as text. Reading uses the same endpoint with `GET` and a `path` query parameter. The answer has a `type`: `file` with base64 `content`, or `dir` with `entries`, each with a `name`, `type` and `size_bytes`. The client checks the type instead of assuming, because asking for a file and getting a folder listing back should be an error, not an empty string.

### Errors become exceptions with a code

Any non-2xx answer raises `SandboxAPIError` with the HTTP status, a machine-readable `code`, the message and a request ID. The reference lists the codes per endpoint: `template_not_found`, `quota_exceeded`, `policy_denied`, `file_too_large`, `sandbox_not_found` and more. Branch on `code`, not on the message text.

The parser accepts the error fields either under an `error` object or at the top level, and falls back to the `X-Request-ID` header for the request ID. That mirrors what the TypeScript SDK does, and it means the client keeps working whichever shape a given endpoint uses. Include the request ID when you report a problem to us.

### Stop is idempotent

`stop` swallows `sandbox_not_found`. If the sandbox already stopped because its `ttl_seconds` ran out, or another process stopped it, the goal is met. Anything else is still raised.

## Using it

```python
from sandbox_rest import Sandboxes, SandboxAPIError

sb = Sandboxes()
box = sb.create(template="builtin:python", ttl_seconds=600, name="rest-recipe")
try:
    sb.write_file(box["id"], "/workspace/main.py", "import sys\nprint(sys.version)\n")
    run = sb.run(box["id"], ["python3", "main.py"], timeout_sec=30)
    if run["timed_out"]:
        print("timed out")
    elif run["oom_killed"]:
        print("ran out of memory")
    else:
        print(run["exit_code"], run["stdout"], run["stderr"])
finally:
    sb.stop(box["id"])
```

Three habits are built in:

- **`ttl_seconds` on create.** The sandbox stops by itself when it runs out, even if your script crashes before `finally` runs. Set it to a little more than the work needs, not to the maximum.
- **`finally` around everything after create.** The normal path stops the sandbox as soon as you are done.
- **Check `timed_out` and `oom_killed` before `exit_code`.** A killed command’s exit code is not the interesting part; the reason it was killed is.

## What to add for production

The client is deliberately small. Before you rely on it:

- **Retries, carefully.** Retry `429` and `503` on reads (`GET`), honoring `Retry-After` when it is present, with backoff and a cap. Do not blindly retry `POST /instances` or `exec`: a timeout does not tell you whether the server started a sandbox or ran the command, and retrying could do it twice. The TypeScript SDK takes the same line and only retries `GET` and `HEAD`.
- **Limit output size.** `stdout` and `stderr` come back in the JSON body. If you feed them to a model, cap them first.
- **Large uploads.** Each `PUT .../files` carries one file, and the reference lists `413 file_too_large` for anything bigger than the server accepts. For a whole folder, `POST /instances/{id}/project` takes a gzip tar; see [getting code into a sandbox and results out](https://sandscale.dev/blog/uploading-a-project-into-a-sandbox).
- **Live output.** `exec` accepts `"wait": false`, which answers `202` with the run’s ID right away, and the logs endpoint streams the output. [Streaming command output](https://sandscale.dev/blog/streaming-sandbox-output-typescript) shows the TypeScript version; the HTTP is the same.

That is the whole API surface most agents need: start, write, run, read, stop. Everything else is choosing good limits.

**On this page**

1. The five calls
2. The client
3. Why it looks like this
4. Using it
5. What to add for production

**Run your agents in a box of their own**

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

[Start free](https://cloud.sandscale.dev/auth/signup)

## Keep reading

- [November 26, 2026 · **30 questions to ask any agent sandbox provider before you sign up** · A vendor-neutral checklist for choosing where your agents run code: isolation, network, secrets, lifecycle, billing for waiting time, governance, data location, reliability and leaving. With where to find each answer for Sandscale.](https://sandscale.dev/blog/questions-to-ask-an-agent-sandbox-provider)
- [November 26, 2026 · **Agent sandbox glossary: 41 terms in plain English** · Plain definitions for the words that come up when you run AI agent code in isolation: microVM, VMM, KVM, jailer, gVisor, seccomp, namespaces, egress allowlist, lease, snapshot, warm pool, awake vCPU-hour and more.](https://sandscale.dev/blog/agent-sandbox-glossary)

---
Source: https://sandscale.dev/blog/calling-the-sandbox-rest-api-from-python
