> ## Documentation index
> Fetch the complete documentation index at: https://k7d.org/llms.txt
> Ask it with GET https://k7d.org/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.

# Python SDK

> Use the k7-sdk package to manage sandboxes from Python

The **`k7-sdk`** PyPI package (`import k7_sdk`) wraps the K7 HTTP API in two clients. The legacy **`katakate`** name still installs but emits a deprecation warning.

- `Client` — synchronous, backed by `requests`.
- `AsyncClient` — `asyncio`-native, backed by `httpx`.

## Install

```bash
pip install k7-sdk==0.5.0            # sync client (requests only)
pip install "k7-sdk[async]==0.5.0"   # also installs httpx for AsyncClient
```

Run this on your **laptop / client**. A k7 node (fresh Ubuntu 24.04) does not ship `python3-venv`; `python3 -m venv …` fails until `sudo apt install -y python3-venv python3-pip`.

The async client raises `RuntimeError` at construction time if `httpx` isn't installed.

Always pass `verify_ssl` as the cluster CA path on the default HTTPS install (`./k7-ca.crt`, or `/etc/k7/tls/ca.crt` on the node). `k7 api status` prints a ready-to-paste snippet that includes it.

## Quickstart

```python
from k7_sdk import Client

k7 = Client(endpoint="https://node:31007", api_key="<your-key>", verify_ssl="./k7-ca.crt")

sb = k7.create({
    "name": "demo",
    "image": "alpine:latest",
    "before_script": "apk add --no-cache curl",
})

print(sb.exec("uname -a"))
print(k7.list())
sb.delete()
```

Discover the endpoint with `k7 api endpoint` and the key with `k7 generate-api-key <name> --role user --tenant <tenant>` (`--role` is required since 0.5.0; see [Tenants and roles](/k7/guides/tenants-and-roles)). Humans can use an OIDC token instead of a key: pass `token_provider=` a callable returning the bearer token (for example a reader for the token in `~/.config/k7/credentials.json` after `k7 login`, a GitHub Actions ID token, or a projected ServiceAccount token). Exactly one of `api_key` / `token_provider` must be given. On the default install the API presents a certificate signed by the cluster CA (`/etc/k7/tls/ca.crt` on the node) — copy it to the client and pass its path as `verify_ssl`. Clusters installed with `--api-hostname` (Let's Encrypt) work with the default `verify_ssl=True`. See the [CLI guide](/k7/guides/cli) for full details.

## `Client` reference

| Method | Returns | Notes |
|--------|---------|-------|
| `Client(endpoint, api_key=None, verify_ssl=True, token_provider=None)` | — | Exactly one of `api_key` (sent as `X-API-Key`) or `token_provider` (a `Callable[[], str]` called per request, sent as `Authorization: Bearer`). `verify_ssl` is `True` (system trust store) or a **CA bundle path** (cluster CA). `verify_ssl=False` raises `ValueError` on an `https://` URL — there is no insecure mode; use `http://` only against a `--api-insecure-http` development install. |
| `whoami()` | `dict` | The caller's identity: subject, role, tenant, namespaces, nodes ([`GET /api/v1/auth/whoami`](/k7/api/endpoints/identity)). |
| `create(config: dict)` | `SandboxProxy` | `config` matches [`SandboxConfig`](/k7/api/endpoints/sandboxes#request-body-schema). |
| `list(namespace=None)` | `list[dict]` | Omit `namespace` to list all. |
| `delete(name, namespace="default")` | `dict` | |
| `delete_all(namespace="default")` | `dict` | Returns `{message, results: [{name, success, error}]}`. |
| `get_metrics(namespace=None)` | `list[dict]` | Per-sandbox `cpu_usage` / `memory_usage`. |
| `install(nodes: list[str])` | `dict` | Remote node install through the k7-node-installer (`admin`, development mode, `--api-remote-install`). Returns the `202` body with the operation id. The pre-0.5.0 playbook-upload form is gone. |
| `install_status(operation)` | `dict` | Per-node `pending` / `running` / `succeeded` / `failed` for an install operation. |
| `pause(name, snapshot=None, namespace=...)` | `dict` | Scale to 0; optional VolumeSnapshot name |
| `resume(name, namespace=...)` | `dict` | Scale back to 1 |
| `fork(source, new_name, namespace=..., snapshot=None)` | `SandboxProxy` | kql: disk clone + cold boot; k7d / k7d-fc: warm CoW fork (memory + disk) |
| `restore(snapshot, new_name, overrides=None, keep_snapshot=True)` | `SandboxProxy` | New sandbox from a snapshot |
| `list_snapshots(...)` / `get_snapshot(...)` / `create_snapshot(...)` / `delete_snapshot(...)` / `gc_snapshots(...)` | varies | Snapshot lifecycle (see [Snapshots API](/k7/api/endpoints/snapshots)) |
| `exec(name, command, namespace="default")` | `dict` | Run a command without a proxy |
| `logs(name, tail=200, container="sandbox", since=0, namespace=...)` | `str` | Snapshot of the pod logs |
| `nodes_storage()` | `dict` | Per-node kfd thin-pool + k7d disk-pool utilization (see [Nodes API](/k7/api/endpoints/nodes)). `operator` / `admin` only (`403` for tenant roles). |
| `usage(start, end, tenant=None, group_by=None)` | `dict` | Showback over `[start, end]` (unix seconds) from the cluster's Prometheus; `group_by` is a comma list of `tenant,namespace,backend,state`. Tenant roles see their own tenant only. See [Observability and metering](/k7/guides/observability-metering). |
| `create_api_key(name, *, role, expires_days, tenant=None, namespaces=None, nodes=None)` | `dict` | `admin`: mint a key; the response carries the one-time `token`. |
| `list_api_keys()` / `revoke_api_key(name)` | `list[dict]` / `dict` | Key inventory (hashes never returned) and revocation. |
| `dedicate_node(node, tenant)` / `undedicate_node(node)` | `dict` | Reserve a node for one tenant / release it (`admin`). |
| `get_role_bindings()` / `put_role_bindings(bindings, deny_subjects)` | `dict` | Read / replace the OIDC role bindings ConfigMap (`admin`). |

`SandboxProxy` (returned by `create`) exposes:

- `exec(command: str) -> dict` — `{exit_code, stdout, stderr, duration_ms}`
- `delete() -> dict` — shorthand for `client.delete(name, namespace)`
- `pause` / `resume` / `fork` — same as the client methods, scoped to this sandbox
- `snapshot(name)` — named VolumeSnapshot without pausing
- `logs(tail=200, container="sandbox", since=0)` — log snapshot

The proxy keeps a reference to the `Client`, so calling `sb.exec(...)` after the parent client closes will raise.

## All sandbox config fields

The `create()` payload accepts every field from the API schema. Common ones:

```python
sb = k7.create({
    "name": "secure-sb",
    "image": "alpine:latest",
    "namespace": "default",

    # Backend selection
    "backend": "kata-qemu-longhorn",      # or "kata-firecracker-devmapper" / "k7d" / "k7d-fc"
    "root_disk_size": "20Gi",        # kata-qemu-longhorn only

    # Docker inside the sandbox (pinned dockerd, overlay2 on a block disk)
    "docker": True,
    "docker_disk": "40Gi",           # default 20Gi

    # Non-root + minimal capabilities
    "pod_non_root": True,
    "container_non_root": True,
    "cap_add": ["CHOWN"],

    # FQDN-aware egress (Cilium); falls back to CIDR if all entries are CIDRs
    "egress_whitelist": ["api.openai.com", "*.huggingface.co"],

    # Ingress is deny-all unless you open ports; scope callers; optionally publish
    "ingress_ports": [8000],
    "ingress_from": ["sandbox:frontend"],   # or "namespace:<ns>" / "cidr:<cidr>"
    # "expose_ports": [8000],               # NodePort; node_ports comes back on list()

    # Resource budget
    "limits": {"cpu": "1", "memory": "1Gi", "ephemeral-storage": "2Gi"},

    # Setup commands run with open egress before lockdown
    "before_script": "pip install openai",

    # Override entrypoint/cmd
    "entrypoint": ["/usr/bin/python3"],
    "cmd": ["-c", "import time; time.sleep(3600)"],
})
```

See [Sandboxes API](/k7/api/endpoints/sandboxes#request-body-schema) for the full table.

<Info>
`env_file` points to a path **on the API node**, not the client. To inject runtime env vars from the client, build them into your `before_script` (`echo "KEY=value" > /etc/sandbox.env`) or commit them to your sandbox image.
</Info>

## Wait until ready

HTTP `POST /sandboxes` (and `Client.create` / `k7 create`) returns once Kubernetes objects exist — often while `ready` is still `False`. Poll `list()` before exec or curling a NodePort:

```python
import time

def wait_until_ready(client, name, namespace="default", timeout=120):
    deadline = time.time() + timeout
    while time.time() < deadline:
        for s in client.list(namespace=namespace):
            ready = s.get("ready")
            if s["name"] == name and s.get("status") == "Running" and ready in (True, "True"):
                return
        time.sleep(2)
    raise TimeoutError(f"{name} did not become Ready")

wait_until_ready(k7, "secure-sb")
```

## Pause, resume, fork

`pause`, `resume`, and `fork` work on `Client` and on the `SandboxProxy` from `create`. Behavior depends on the backend:

- **`kata-qemu-longhorn`** — fork clones the root disk via Longhorn `VolumeSnapshot` (the fork cold-boots, ~45 s); pause/resume scale the Deployment and the PVC survives. A `docker: True` sandbox's graph PVC is cloned too.
- **`k7d`** / **`k7d-fc`** — fork is a warm CoW copy of the whole VM (memory + disk + processes — including a live `docker: True` engine, ~5 ms at the VMM, ~2 s end-to-end to a Ready pod); pause/resume freeze and thaw the live VM in place. Works for sandboxes on any node — the API forwards to the per-node `k7-agent` when needed.

Forks inherit the source's egress and ingress policy, but not its `expose_ports` Service.

```python
base = k7.create({
    "name": "demo",
    "image": "python:3.12-slim",
    "backend": "kata-qemu-longhorn",
    "before_script": "pip install numpy pandas",
})
wait_until_ready(k7, "demo")

base.pause(snapshot="demo-v1")
base.resume()

forks = [base.fork(f"exp-{i}") for i in range(8)]
for f in forks:
    print(f.exec("python -c 'import numpy; print(numpy.__version__)'")["stdout"])
    f.delete()
```

See [Snapshots & fork](/k7/guides/snapshots-fork) for timing notes and CLI equivalents.

## Snapshots and restore

```python
base.snapshot("demo-experiment-1")

for s in k7.list_snapshots(sandbox="demo"):
    print(s["name"], s["kind"], s["age"])

k7.delete_snapshot("demo-experiment-1")
k7.gc_snapshots(all_namespaces=True, keep_fork_for="10m", dry_run=True)

base.pause(snapshot="demo-v1")
base.delete()

restored = k7.restore("demo-v1", "demo-restored")
wait_until_ready(k7, "demo-restored")  # restore returns once objects exist; boot is async
print(restored.exec("ls /")["stdout"])
```

Full HTTP detail: [Snapshots API](/k7/api/endpoints/snapshots).

## Async client

```python
import asyncio
from k7_sdk import AsyncClient

async def main():
    k7 = AsyncClient(endpoint="https://node:31007", api_key="<your-key>", verify_ssl="./k7-ca.crt")
    try:
        await k7.create({"name": "async-sb", "image": "alpine:latest"})

        for _ in range(60):
            sbs = await k7.list()
            if any(s["name"] == "async-sb" and s["ready"] == "True" for s in sbs):
                break
            await asyncio.sleep(2)

        out = await k7.exec("async-sb", "echo from async")
        print(out["stdout"])
    finally:
        await k7.delete("async-sb")
        await k7.aclose()

asyncio.run(main())
```

`AsyncClient` mirrors the sync client surface (`create`, `list`, `delete`, `delete_all`, `exec`, `get_metrics`, `aclose`). Note that `AsyncClient.exec` is a top-level method (`await k7.exec(name, command)`) rather than a proxy method.

### Concurrent sandbox fan-out

```python
import asyncio
from k7_sdk import AsyncClient

async def run_one(k7, idx):
    name = f"worker-{idx}"
    await k7.create({"name": name, "image": "python:3.12-slim"})
    try:
        for _ in range(60):
            if any(
                s["name"] == name and s["ready"] == "True"
                for s in await k7.list()
            ):
                break
            await asyncio.sleep(2)
        result = await k7.exec(name, f"python -c 'print({idx} ** 2)'")
        return result["stdout"].strip()
    finally:
        await k7.delete(name)

async def main():
    k7 = AsyncClient(endpoint="https://node:31007", api_key="<your-key>", verify_ssl="./k7-ca.crt")
    try:
        results = await asyncio.gather(*[run_one(k7, i) for i in range(10)])
        print(results)
    finally:
        await k7.aclose()

asyncio.run(main())
```

## Errors

`requests.HTTPError` / `httpx.HTTPStatusError` are raised on non-2xx responses. The error body follows the API envelope:

```json
{ "error": { "code": "BadRequest", "message": "name already exists" } }
```

Recover the structured error:

```python
import requests

try:
    sb = k7.create({"name": "demo", "image": "alpine"})
except requests.HTTPError as e:
    body = e.response.json()
    print(body["error"]["code"], body["error"]["message"])
```

## Tips

- Always pass `namespace=` if you use anything other than `default`. A **tenant** key (`k7 generate-api-key NAME --role user --tenant team-a`, optionally narrowed with `-n`) cannot list all namespaces or touch a namespace outside its tenant (`403`); only `operator` / `admin` keys see the whole cluster.
- Rotate API keys with `k7 revoke-api-key <name>` and `k7 generate-api-key <name>`.
- The same operations are available via CLI (`k7 pause`, `k7 fork`, `k7 snapshot`, `k7 restore`) — default CLI path is the HTTP API; use `--core` only on the cluster node.
