Skip to main content

Rust SDK

note

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

The Rust SDK (k9o on crates.io) is async-first, built on Tokio and Reqwest, and returns Result<Response<T>, KError> from every method. It targets Rust 1.78+. All method names and field names follow snake_case; type names follow PascalCase; error codes are SCREAMING_SNAKE_CASE strings matched as &str. Data-plane record bodies are serde_json::Value — Rust's de-facto-standard open value type — because collection schemas are defined by you at runtime, not pre-generated into the SDK.


Installation​

Cargo.toml
[dependencies]
k9o = "1.5.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

Or with cargo-add:

cargo add k9o

The crate coordinate is k9o on crates.io. The minimum supported Rust version is 1.78.


Setup​

Constructing the client​

Construct the client with org_slug, project_slug, and api_key. base_url is optional — the default is https://api.k9o.io; when you supply org_slug, the SDK derives https://<org_slug>.api.k9o.io automatically. Passing base_url explicitly (as shown below) is fine and makes the target URL obvious in a quickstart. Self-hosted and Sovereign deployments pass their own host. A path-bearing URL fails at construction time with K9O_INVALID_BASE_URL.

The API key must come from an environment variable or a secrets store. Never hard-code a key in source.

Rust
use k9o::{Client, ClientOpts};

let k9o = Client::new(ClientOpts {
  base_url: Some("https://acme.api.k9o.io".into()), // optional
  api_key: std::env::var("K9O_API_KEY").ok(),
  org_slug: Some("acme".into()),
  project_slug: Some("member-portal".into()),
  ..Default::default()
})?;

Showing example in Rust

Self-hosted / Sovereign Control override​

If you run a self-hosted or Sovereign Control deployment, pass base_url containing only scheme + host — no path. See §7.3 of the API conventions for the full override rules.

Rust
use k9o::{Client, ClientOpts};

let k9o = Client::new(ClientOpts {
  base_url: Some("https://platform.acme.internal".into()), // optional
  api_key: std::env::var("K9O_API_KEY").ok(),
  org_slug: Some("acme".into()),
  project_slug: Some("member-portal".into()),
  ..Default::default()
})?;

Showing example in Rust

Supplying a path-bearing URL (e.g. https://platform.acme.internal/v2) fails at construction time with K9O_INVALID_BASE_URL. The SDK validates the base_url value at Client::new so the error surfaces during startup, not at the first request.


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.

Rust
use k9o::{Client, ClientOpts, KError};

#[tokio::main]
async fn main() -> Result<(), KError> {
  let k9o = Client::new(ClientOpts {
      base_url: Some("https://acme.api.k9o.io".into()), // optional
      api_key: std::env::var("K9O_API_KEY").ok(),
      org_slug: Some("acme".into()),
      project_slug: Some("member-portal".into()),
      ..Default::default()
  })?;

  // Query a collection — record bodies are serde_json::Value
  let resp = k9o.from("posts").select().limit(10).execute::<serde_json::Value>().await?;
  println!("{:?} {:?}", resp.data, resp.meta.cursor);

  Ok(())
}
Output · bash
[Object {"id": String("post_1"), "title": String("Hello")}] Some(MetaCursor { next: None, total_count: None })

Showing example in Rust

k9o.from(collection) opens a query builder against the named collection in k9o_<proj_id>. .select().limit(n).execute::<T>() returns Result<Response<Vec<T>>, KError>.

resp.meta.cursor.next is Option<String> — None on the final page.


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 identity-provider (OAuth2/SAML) and passwordless (magic-link / OTP) flows are browser and mobile flows that require window.location redirects — they are available on the TypeScript SDK and the mobile SDKs, not here. See 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
use k9o::SignInInput;

let session = k9o.gate().sign_in(SignInInput { email: "[email protected]", password: "…" }).await?;
println!("signed in: {}", session.data["user"]["id"]);
println!("access token: {}", session.data["session"]["accessToken"]);
Output · bash
signed in: "eu_8f3kQ2mZ"
access token: "eyJhbGciOiJSUzI1NiIs..."

Showing example in Password


Handling errors​

Every fallible SDK method returns Result<Response<T>, KError>. KError is a plain struct:

pub struct KError {
pub code: String, // SCREAMING_SNAKE_CASE; closed catalogue — /api/errors
pub message: String, // human-readable; safe to log and surface
pub context: HashMap<String, serde_json::Value>, // family-specific structured fields
pub recommendation: Option<String>, // remediation hint; may be None
pub status: Option<u16>, // HTTP status, when the error came from the wire
pub request_id: Option<String>, // correlation ID of the failed request
}

KError implements std::error::Error, so it propagates naturally with ? into anyhow::Error or any thiserror-derived type.

Match on code.as_str() to branch per error family. All codes are drawn from the closed catalogue in the error reference; do not match on message (it is human-readable prose, not a stable identifier).

Rust
use k9o::{Client, KError};

async fn list_orders(k9o: &Client) -> Result<(), KError> {
  match k9o.from("orders").select().limit(10).execute::<serde_json::Value>().await {
      Ok(resp) => {
          for row in &resp.data {
              println!("{:?}", row);
          }
          Ok(())
      }
      Err(e) => {
          match e.code.as_str() {
              "K9O_TIER_CAP_HIT" => {
                  // Tier cap reached; recommendation is text when present
                  eprintln!("tier cap: {} | {:?}", e.message, e.recommendation);
              }
              "K9O_UNAUTHENTICATED" => {
                  eprintln!("API key missing, invalid, or expired");
              }
              "K9O_COLLECTION_NOT_FOUND" => {
                  eprintln!("collection does not exist: {}", e.message);
              }
              "K9O_ACCESS_DENIED" => {
                  eprintln!("insufficient role for this action: {}", e.message);
              }
              _ => {
                  eprintln!("[{}] {}", e.code, e.message);
              }
          }
          Err(e)
      }
  }
}
Output · bash
Object {"id": String("order_1"), "total": Number(42)}

Showing example in Rust

A selection of codes you are likely to encounter:

CodeFamilyWhen it fires
K9O_UNAUTHENTICATEDAuthAPI key absent, invalid, or expired
K9O_INVALID_CREDENTIALSAuthEmail/password sign-in rejected
K9O_TIER_CAP_HITCapacityA metered tier cap (e.g. MAU, storage) is exceeded
K9O_TIER_RATE_LIMIT_EXCEEDEDCapacityPer-period request rate exceeded
K9O_COLLECTION_NOT_FOUNDResourcefrom("name") references a collection that doesn't exist
K9O_ACCESS_DENIEDAuthorityCaller's role is insufficient for the requested action
K9O_INJECTION_DETECTEDValidationAnti-injection posture rejected a query parameter
K9O_INVALID_BASE_URLValidationbase_url passed to Client::new contains a path segment

recommendation is text when present. The full per-code context shapes are in the error catalogue.

Propagating with ?​

Because KError implements std::error::Error, you can propagate it directly:

Rust
async fn fetch_posts(k9o: &k9o::Client) -> anyhow::Result<Vec<serde_json::Value>> {
  let resp = k9o.from("posts").select().limit(10).execute::<serde_json::Value>().await?;
  Ok(resp.data)
}

Showing example in Rust


Async and streaming​

The SDK is async-first. Every network method is an async fn returning a Future; drive it with any Tokio executor. The default Client uses Tokio's multi-thread runtime; you can also call SDK methods from within an existing Tokio context.

Realtime subscriptions​

Realtime subscriptions use Server-Sent Events at the wire layer. subscribe returns a subscription; call next().await to read 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.

Rust
use k9o::{Client, KError};

async fn watch_orders(k9o: &Client) -> Result<(), KError> {
  let mut sub = k9o
      .realtime()
      .subscribe(&k9o::realtime_topic::collection("orders"), None)
      .await?;

  while let Some(event) = sub.next().await {
      match event {
          Ok(ev) => println!("{}: {}", ev.event_type, ev.payload),
          Err(e) => eprintln!("stream error: {}", e),
      }
  }
  Ok(())
}
Output · bash
row_inserted: {"id":"order-124","total":42}
row_deleted: {"id":"order-124"}

Showing example in Rust

Each event carries topic, event_type, payload, and occurred_at. See the Data reference for topics and the frame format.

The change-feed handle does not reconnect: after an event: resync frame, re-read the data and subscribe again.

Streams​

Streams are ordered and replayable. max_bytes is at least 10485760 (10 MiB), and the stream's slug is what the other calls take. subscribe(&slug, None) starts at the first event; pass Some("2") to resume after sequence 2. close() ends the loop, and the handle reconnects on its own when the server closes a connection.

Rust
use serde_json::json;

let stream = k9o.streams().create("orders", 10_485_760, None).await?;
let slug = stream.data.slug;

k9o.streams().publish(&slug, &json!({ "id": 1, "total": 42 }), Some("eu.new")).await?;
k9o.streams().publish(&slug, &json!({ "id": 2, "total": 17 }), None).await?;

let mut events = k9o.streams().subscribe(&slug, None).await?;
while let Some(event) = events.next().await {
  let event = event?;
  println!("{} {}", event.sequence, event.data); // 1 {"id":1,"total":42}
  if event.sequence == "2" {
      events.close();
  }
}

let page = k9o.streams().replay(&slug, Some(0), None, Some(10)).await?;
println!("{} {}", page.data.events.len(), page.data.has_more);
Output · bash
1 {"id":1,"total":42}
2 {"id":2,"total":17}
2 false

Showing example in Rust


See also​

  • API reference — full surface, all endpoints, all parameters
  • API conventions — response envelope, KError shape, URL grammar, pagination
  • CLI — the same operations from the terminal
  • SDKs — TypeScript, Python, Go, and all other supported languages