DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

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

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 and the Sandboxes API reference. 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 covers which key should hold what.

The client

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
Enter fullscreen mode Exit fullscreen mode

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 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

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"])
Enter fullscreen mode Exit fullscreen mode

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.
  • 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 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.

Originally published on the Sandscale blog.

Top comments (0)