Skip to main content

Python SDK

note

This is a platform SDK — it covers the full Kilimanjaro API surface: data, auth (Gate), migrations, functions, policies, audit, org management, and realtime subscriptions. A separate mobile SDK family exists for auth-only mobile use cases.

The Python SDK (k9o on PyPI) gives Python 3.10+ applications idiomatic access to every Kilimanjaro API. Methods are snake_case, errors raise as KError(Exception), and both synchronous and asynchronous call patterns are supported. The SDK is fully type-hinted; collection record bodies are typed as dict[str, Any] (a TypedDict-backed open map — structurally a dict at runtime, checked by pyright and mypy), so static analysers catch mismatches at development time.


Installation​

pip install k9o

Alternative package managers:

uv add k9o
poetry add k9o

Minimum runtime: Python 3.10+.


Setup​

Constructing the client​

Import create_client and supply your api_key, org_slug, and project_slug. base_url is optional — the default is https://api.k9o.io, and when you pass org_slug the SDK derives the canonical https://<org_slug>.api.k9o.io subdomain for you. The explicit form is shown below for clarity; you may omit it on the standard hosted platform. Self-hosted and Sovereign deployments pass their own host. A path-bearing URL raises K9O_INVALID_BASE_URL at construct time.

Python
import os
from k9o import create_client

k9o = create_client(
  base_url="https://acme.api.k9o.io",  # optional
  api_key=os.environ["K9O_API_KEY"],
  org_slug="acme",
  project_slug="member-portal",
)

Showing example in Python

Never hard-code your API key. Always read it from an environment variable or a secrets manager.

Self-hosted and Sovereign deployments​

If you run a self-hosted or Sovereign deployment, pass an explicit base_url pointing at your gateway host — scheme and host only, no path:

Python
import os
from k9o import create_client

k9o = create_client(
  base_url="https://platform.acme.internal",  # host only; no path
  api_key=os.environ["K9O_API_KEY"],
  org_slug="acme",
  project_slug="member-portal",
)

Showing example in Python

Supplying a URL that includes a path segment (e.g. https://api.acme.example.com/v2) raises K9O_INVALID_BASE_URL at construct time — the error surfaces on create_client, not on the first API call. See §7.3 of the SDK spec for the full list of valid and invalid base_url forms.


Getting started​

The first operation most applications make is querying a data collection — build a query, await it, and handle KError. Signing users in has its own section below.

Python
import os
from k9o import create_client, KError

k9o = create_client(
  base_url="https://acme.api.k9o.io",  # optional
  api_key=os.environ["K9O_API_KEY"],
  org_slug="acme",
  project_slug="member-portal",
)

try:
  # Query a collection — returns {data, meta}
  response = k9o.from_("posts").select().limit(10).execute()
  for row in response.data:
      print(row)

  # meta.cursor.next is None on the final page
  print("next cursor:", response.meta.cursor.next)

except KError as e:
  print(f"[{e.code}] {e.message}: {e.recommendation}")
Output · bash
{'id': 'post_1', 'title': 'Hello'}
next cursor: None

Showing example in Python

note

from_ has a trailing underscore because from is a reserved keyword in Python.

A few things to note:

  • k9o.from_("posts") addresses the posts collection in your project. The trailing underscore avoids shadowing Python's built-in from.
  • response.data is a list of records typed as dict[str, Any]; response.meta.cursor.next is an opaque cursor for the next page, or None on the final page.
  • A collection must exist via a migration before you can query it. Querying a non-existent collection raises K9O_COLLECTION_NOT_FOUND.

Authenticating your End-Users​

This server SDK covers password sign-in and session management: sign_in, sign_up, sign_out, whoami, and refresh_token. Social-IdP and passwordless (magic-link / OTP) flows are browser and mobile flows that depend on window.location redirects — they are available on the TypeScript SDK and the mobile SDK family. See the TypeScript SDK and mobile SDK pages, or the Auth API reference for those flows and the full Gate surface. revoke_all_sessions ends every session of the signed-in user, this device included; access tokens already issued live until they expire. See Session lifetime and sign-out.

Password
result = k9o.gate.sign_in(email="[email protected]", password="…")
# result.data is a dict with the wire keys: { user, session }
print("signed in:", result.data["user"]["id"])          # eu_<base62>
print("access token:", result.data["session"]["accessToken"])
Output · bash
signed in: eu_8f3kQ2mZ
access token: eyJhbGciOiJSUzI1NiIs...

Showing example in Password


Handling errors​

Every failure raises KError. The exception carries four fields grounded in the platform error contract:

FieldTypeDescription
codestrSCREAMING_SNAKE_CASE error code from the closed catalogue — always the full K9O_* string
messagestrHuman-readable description; safe to log
contextdictFamily-specific structured fields; content varies by code
recommendationstr | NoneRemediation hint; None when the platform has none to give

Match on e.code using the full K9O_* string — the SDK never strips the prefix.

Python
from k9o import KError

try:
  response = k9o.from_("posts").select().execute()
except KError as e:
  if e.code == "K9O_TIER_CAP_HIT":
      # context carries the capped resource, the cap and the current count
      print("tier cap hit:", e.context)
      # recommendation is text when present, otherwise None
      if e.recommendation:
          print("recommendation:", e.recommendation)
  elif e.code == "K9O_COLLECTION_NOT_FOUND":
      print("collection not found:", e.context.get("collection"))
  else:
      raise
# Output (illustrative; on failure, one case prints depending on the error code):
# tier cap hit: <e.context>
# recommendation: <e.recommendation>
# collection not found: <collection name>

Showing example in Python

Common error codes​

CodeHTTPWhen it fires
K9O_INVALID_CREDENTIALS401Wrong email or password on gate.sign_in
K9O_COLLECTION_NOT_FOUND404The named collection does not exist in this project
K9O_ACCESS_DENIED403Caller's token lacks authority for the requested operation
K9O_TIER_CAP_HIT409A tier-bound resource cap (e.g. MAU limit) has been reached; context names the capped resource
K9O_TIER_RATE_LIMIT_EXCEEDED429Per-period rate limit exceeded
K9O_RESERVED_COLUMN_WRITE_PROHIBITED403Attempt to write a platform-reserved _-prefixed column via from_().insert()
K9O_INVALID_BASE_URL—create_client received a path-bearing or scheme-less base_url; raised at construct time

The full error catalogue is at /api/errors.


Async and streaming​

Requests (from_, query, gate, storage, ai, streams.publish) are ordinary synchronous calls that return an envelope with .data and .meta. Subscriptions (realtime and streams) are async iterators: consume them with async for inside asyncio.run or your own event loop.

Realtime subscriptions (see Data — Realtime) are delivered as async iterators using async for:

Python
import os
import asyncio
from k9o import create_client, realtime_topic

k9o = create_client(
  base_url="https://acme.api.k9o.io",  # optional
  api_key=os.environ["K9O_API_KEY"],
  org_slug="acme",
  project_slug="member-portal",
)

async def watch_posts():
  async for event in k9o.realtime.subscribe(realtime_topic.collection("posts")):
      print(event)

asyncio.run(watch_posts())
Output · bash
{'eventType': 'row_inserted', 'payload': {'id': 'order-124', 'total': 42}, ...}

Showing example in Python

Realtime is Server-Sent Events: a stream lasts up to 300 seconds; to continue after it ends, reconnect with the last event id as Last-Event-ID and drop duplicates by eventId (the client contract, see the Realtime API reference). There is no initial-state replay; read the current rows first, then subscribe for changes.

Streams​

Streams are ordered and replayable. max_bytes is at least 10485760 (10 MiB); the stream's slug, derived from its display name (orders here), is what the other calls take. sequence arrives as a string.

Python
import asyncio
import json

k9o.streams.create("orders", 10_485_760)
k9o.streams.publish("orders", {"id": 1, "total": 42}, subject="eu.new")
k9o.streams.publish("orders", {"id": 2, "total": 17})

async def tail_orders():
  async for event in k9o.streams.subscribe("orders", from_sequence=0):
      print(event["sequence"], json.dumps(event["data"]))  # 1 {"id": 1, "total": 42}
      if event["sequence"] == "2":
          break

asyncio.run(tail_orders())

page = k9o.streams.replay("orders", from_sequence=0, limit=10).data
print(len(page["events"]), page["hasMore"])
Output · bash
1 {"id": 1, "total": 42}
2 {"id": 2, "total": 17}
2 False

Showing example in Python


See also​

  • API reference — full surface reference for every endpoint
  • Conventions — response envelope, KError shape, naming, versioning
  • CLI — the k9o command-line tool
  • SDKs — all twelve v2-launch SDK languages