Metadata-Version: 2.5
Name: skopik-sdk
Version: 0.1.0
Summary: The Python SDK for Skopik Platform: Databases, Buckets, Queues, Topics, Sandboxes, Workers and Email.
Project-URL: Homepage, https://platform.skopik.com
Project-URL: Documentation, https://platform.skopik.com/docs/sdk
Project-URL: Source, https://github.com/skalerlabs/skopik-platform/tree/main/sdk-python
Author: Skaler Labs
License-Expression: MIT
License-File: LICENSE
Keywords: buckets,database,queues,sandbox,sdk,skopik,skopik-platform,topics,workers
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: websockets>=13.1
Description-Content-Type: text/markdown

# skopik-sdk

The Python SDK for [Skopik Platform](https://platform.skopik.com): Databases, Buckets, Queues, Topics, Sandboxes, Workers and Email.

```bash
pip install skopik-sdk
```

It runs on Python 3.10 or later, in servers, scripts and CI, and inside Skopik Workers and Sandboxes. `Skopik` is the client for ordinary code and `AsyncSkopik` the one for `asyncio`: they have the same methods, and the async one's are awaited.

## Connecting

From a server, a script or CI, the client uses an org's key: `api_key`, or `SKOPIK_API_KEY`, or the key `skopik login` stored. A `read` key can read but not change anything.

```python
from skopik import Skopik

skopik = Skopik()  # SKOPIK_API_KEY, or `skopik login`
```

```python
from skopik import AsyncSkopik

async with AsyncSkopik() as skopik:
    rows = (await skopik.databases.sql("shop").query("SELECT * FROM orders")).objects
```

Inside a Worker or Sandbox, `Skopik.from_bindings()` uses its [bindings](https://platform.skopik.com/docs/bindings/): no key, and the binding's name from `skopik.json` in place of the resource's name. Bindings reach data operations only: creating, deleting or rewinding a resource needs a key.

```python
skopik = Skopik.from_bindings()
db = skopik.databases.sql("DB")  # the binding DB
```

A Python Worker carries its packages in its bundle: `pip install --target .packages skopik-sdk` before you deploy. The SDK and what it needs are pure Python.

`SKOPIK_API_URL` (or `base_url=`) points the client at another API, such as `https://api.platform-staging.skopik.com`.

## Databases

```python
from datetime import datetime, timedelta, timezone

shop = skopik.databases.sql("shop")
shop.execute("CREATE TABLE IF NOT EXISTS orders (id TEXT PRIMARY KEY, total REAL)")
shop.execute("INSERT INTO orders VALUES (?, ?)", ["o_1", 42])
for order in shop.query("SELECT * FROM orders"):  # each row a dict
    print(order["id"], order["total"])

shop.batch([
    ("UPDATE orders SET total = ? WHERE id = ?", [40, "o_1"]),
    "DELETE FROM orders WHERE total = 0",
])  # one transaction

notes = skopik.databases.documents("notes")
notes.put({"id": "n1", "title": "Hello", "tags": ["inbox"]})
for note in notes.query({"field": "tags", "op": "contains", "value": "inbox"}):
    print(note["title"])

# History: read, compare or rewind to any moment of the last 30 days
an_hour_ago = datetime.now(timezone.utc) - timedelta(hours=1)
shop.query_at("SELECT count(*) AS n FROM orders", at=an_hour_ago)
shop.rewind(at="2026-11-30T12:00:00Z")
shop.undo_rewind()

skopik.databases.create("analytics", type="sql")
```

A result has the engine's `columns` and `rows`, and `objects`, each row as a dict. `bytes` parameters are sent as blobs, and blobs come back as `bytes`.

## Buckets

```python
from pathlib import Path

uploads = skopik.buckets.bucket("uploads")
uploads.put("avatars/1.png", Path("1.png"))  # a file is sent as it is read
uploads.put("notes.txt", "hello")
print(uploads.get("notes.txt").text())
for o in uploads.list(prefix="avatars/"):
    print(o["key"], o["size"])

with uploads.open("videos/big.mp4") as obj:  # a stream, for a large object
    for chunk in obj:
        ...
uploads.download("videos/big.mp4", "big.mp4")
```

## Queues

```python
jobs = skopik.queues.queue("jobs")
jobs.send({"task": "resize", "key": "avatars/1.png"})  # sent as JSON
jobs.send_batch(["a", "b", {"body": b"\x00\x01", "content_type": "application/octet-stream"}])
jobs.schedules.create("nightly", "0 3 * * *", {"task": "cleanup"})

for dead in jobs.dead_letters():
    print(dead["id"], dead.payload.json())
jobs.send_back()  # every dead letter back to the Queue
```

In the consumer Worker, `queue_delivery(request)` reads a delivery's headers, from an `http.server` handler, a WSGI environ, an ASGI scope or a framework's request:

```python
from skopik import queue_delivery

delivery = queue_delivery(self)  # None for any other request
if delivery:
    print(delivery.queue, delivery.message_id, delivery.attempt)
```

## Topics

```python
skopik.topics.publish("chat/lobby", {"text": "hi"})
credential = skopik.topics.create_credential(["chat/**"], ttl_seconds=3600)  # for a browser

with skopik.topics.subscribe(["chat/lobby"], on_reconnect=refetch_state) as sub:
    for message in sub:
        print(message.topic, message.json())
```

A subscription connects again after a lost connection and calls `on_reconnect`, since nothing published meanwhile is kept. Inside a Worker, publish and make credentials through a Topic binding by naming it: `topics.publish(topic, body, binding="EVENTS")`.

## Sandboxes

```python
box = skopik.sandboxes.create(name="builds/42", memory_mib=1024)
box.write_file("/work/requirements.txt", "requests\n")
result = box.exec(["pip", "install", "-r", "requirements.txt"], cwd="/work", timeout_secs=600)
print(result["exit_code"], result["stdout"])

for event in box.exec_stream("pytest", cwd="/work"):
    if event.type == "exit":
        print("exit", event.exit_code)
    else:
        print(event.text, end="")
box.stop()  # the disk is kept; the next command boots it again
```

## Workers

```python
deployed = skopik.workers.deploy("api", directory="./app", runtime="python")
print(deployed["url"])

api = skopik.workers.worker("api")
api.secrets.set("STRIPE_KEY", "sk_live_…")
deployments = api.deployments()
if len(deployments) > 1:
    api.set_alias("production", deployments[1]["id"])  # roll back
for line in api.logs.tail():
    print(line["line"])
```

`deploy` packs the directory (or a mapping of `files`), makes the Worker if it does not exist, uploads a new deployment and points `production` (or `alias=`) at it, as `skopik deploy` does.

## Email

```python
skopik.email.send(to="ada@example.com", subject="Welcome", text="Your workspace is ready.")
```

## Errors, retries and lists

Every failure is a `SkopikError` with the API's stable `code`, the HTTP `status` and a `message`:

```python
from skopik import SkopikError

try:
    skopik.databases.create("shop", type="sql")
except SkopikError as e:
    if e.code != "database_exists":
        raise
```

Reads, puts and deletes are retried twice after a network error, `429`, `502`, `503` or `504`, waiting `Retry-After` when the API sends it (`max_retries=` changes it). Anything else that changes data, such as a publish, a send or a command, is never sent again by the SDK, since it may already have happened.

A list goes through every page when iterated; `.page()` reads one page (`items`, `prefixes`, `next`) and `.all()` reads every item into a list.

API records are plain dicts with the API's own field names, typed for editors with `TypedDict`.

## Anything else

`skopik.call(tool, **arguments)` calls any [MCP tool](https://platform.skopik.com/docs/mcp/) by name, as `skopik <tool>` does, for an operation the SDK does not wrap, such as members, invites or the Git integration.

## License

MIT
