Skip to main content

Java SDK

note

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

The Java SDK exposes the complete Kilimanjaro v2 API surface from the dev.k9o.* package family. It targets JDK 21+ and is designed for high-concurrency server workloads — virtual threads are the native execution model for blocking I/O paths. The SDK uses a builder-pattern construction style and delivers errors through KError extends RuntimeException, keeping the call sites free of checked exceptions while preserving the full structured error payload.

Language baseline: JDK 21+. Method names and field accessors follow camelCase. The wire format is always camelCase JSON regardless of the Java accessor shape; the SDK handles the translation at its boundary.

This SDK covers the complete v2 API surface:

  • Data — k9o.from(collection) query builder, object storage
  • Auth (Gate IAK) — k9o.gate() surface: signIn, signUp, signOut, whoami, refreshToken
  • Migrations — k9o.migrations(): schema migration lifecycle
  • Functions — k9o.functions(): serverless function invocation
  • Policies — k9o.policies(): JSON-policy authoring, RBAC/ABAC rule management
  • Audit — k9o.audit(): structured audit log query
  • Org / project management — k9o.org(), k9o.projects()
  • Realtime — k9o.realtime(): Server-Sent Events subscription to a topic

Installation​

Add the coordinate to your build file. Use the latest stable version from Maven Central.

Maven

<dependency>
<groupId>dev.k9o</groupId>
<artifactId>core</artifactId>
<version>1.5.0</version>
</dependency>

Gradle (Kotlin DSL)

implementation("dev.k9o:core:1.5.0")

Gradle (Groovy DSL)

implementation 'dev.k9o:core:1.5.0'

Setup​

Constructing the client​

Construct the client with orgSlug, projectSlug, and apiKey. baseUrl is optional — the default is https://api.k9o.io; if you pass orgSlug, the SDK derives https://<orgSlug>.api.k9o.io automatically. The snippet below shows baseUrl explicitly for clarity, but you may omit it. Self-hosted and Sovereign deployments pass their own host as baseUrl. A path-bearing baseUrl throws KError with code K9O_INVALID_BASE_URL at construction time.

Java
import dev.k9o.K9o;

K9o.K9oClient k9o = K9o.createClient(K9o.Opts.builder()
  .baseUrl("https://acme.api.k9o.io") // optional
  .apiKey(System.getenv("K9O_API_KEY"))
  .orgSlug("acme")
  .projectSlug("member-portal")
  .build());

Showing example in Java

API key: always read the key from an environment variable or a secrets manager — for example System.getenv("K9O_API_KEY"). Never hard-code it.

orgSlug and projectSlug are the slug-form identifiers you assigned when creating the org and project in the Console. They are slug-only; never pass an internal org_ or proj_ prefixed ID here.

Self-hosted / Sovereign override​

For self-hosted or Sovereign deployments — a Private Perimeter or local DevProxy instance — pass your own host as baseUrl instead of the Kilimanjaro Cloud subdomain:

Java
K9o.K9oClient k9o = K9o.createClient(K9o.Opts.builder()
  .baseUrl("https://platform.acme.internal")  // scheme + host only; no path
  .apiKey(System.getenv("K9O_API_KEY"))
  .orgSlug("acme")
  .projectSlug("member-portal")
  .build());

Showing example in Java

baseUrl must be a scheme and host (with an optional port). Supplying a path-bearing value — for example https://api.k9o.io/v2 — throws KError with code K9O_INVALID_BASE_URL at construction time, before any network request is made. Common valid forms: https://platform.acme.internal, http://localhost:8080.


Getting started​

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

Java
import dev.k9o.K9o;
import dev.k9o.KError;

K9o.K9oClient k9o = K9o.createClient(K9o.Opts.builder()
  .baseUrl("https://acme.api.k9o.io") // optional
  .apiKey(System.getenv("K9O_API_KEY"))
  .orgSlug("acme")
  .projectSlug("member-portal")
  .build());

try {
  var resp = k9o.from("posts").select().limit(10).execute(Post.class);
  resp.data().forEach(System.out::println);
  System.out.println("next cursor: " + resp.meta().cursor().next());

} catch (KError e) {
  System.err.printf("[%s] %s: %s%n",
      e.getCode(),
      e.getMessage(),
      e.getRecommendation() != null ? e.getRecommendation() : "—");
}
Output · bash
Post[id=post_1, title=Hello]
next cursor: null

Showing example in Java

k9o.from("posts").select().limit(10).execute(Post.class) queries the posts collection in your project's data schema. Every successful response is {data, meta} — data() is a list of records deserialized into the supplied type (Post.class); meta().cursor().next() is the opaque pagination cursor for the next page, null on the final page.

For the full collection query surface — filters, limit, cursor, and count — see the Data API reference.


Authenticating your End-Users​

This server SDK covers password sign-in and session management: signIn, signUp, signOut, whoami, and refreshToken. Social identity-provider and passwordless flows (magic-link and OTP) are browser and mobile flows — see the TypeScript SDK and mobile SDK pages, or the Auth API reference for those and the full Gate surface. revokeAllSessions 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
import dev.k9o.Gate;

var result = k9o.gate().signIn(new Gate.SignInInput("[email protected]", "…"));
System.out.println("signed in: " + result.data().get("user").get("id").asText());
System.out.println("access token: " + result.data().get("session").get("accessToken").asText());
Output · bash
signed in: eu_8f3kQ2mZ
access token: eyJhbGciOiJSUzI1NiIs...

Showing example in Password


Handling errors​

Every platform error surfaces as KError extends RuntimeException. The exception carries these fields that are consistent across every error code and every SDK:

AccessorTypeDescription
getCode()StringSCREAMING_SNAKE_CASE error code from the closed error catalogue
getMessage()StringHuman-readable description; safe to log and display
getContext()ObjectStructured, code-specific fields; content varies by code
getRecommendation()String (nullable)Remediation hint; null when there is none

KError is an unchecked exception — you do not declare it in method signatures. The idiomatic pattern is to switch on getCode() for known error families and re-throw unknown ones:

Java
import dev.k9o.KError;
import dev.k9o.Gate;

// --- Tier cap ---
try {
  var response = k9o.from("events").select().execute(Event.class);
  response.data().forEach(System.out::println);
} catch (KError e) {
  if ("K9O_TIER_CAP_HIT".equals(e.getCode())) {
      // getContext() names the capped resource; getRecommendation() is a string or null
      System.err.println("Tier cap reached: " + e.getMessage());
      if (e.getRecommendation() != null) {
          System.err.println("Recommendation: " + e.getRecommendation());
      }
      // Output (illustrative; written to stderr when the tier cap is hit):
      // Tier cap reached: <message>
      // Recommendation: <recommendation>
  } else {
      throw e;  // re-throw unexpected errors
  }
}

// --- Auth errors ---
try {
  var session = k9o.gate().signIn(new Gate.SignInInput("[email protected]", "…"));
} catch (KError e) {
  if ("K9O_INVALID_CREDENTIALS".equals(e.getCode())) {
      // guide the user to retry sign-in
  } else {
      throw e;
  }
}

Showing example in Java

A caller that switches on known codes and falls through to a generic throw e handles every error the platform can produce, including future codes added in later API versions.

Error codes used in these examples:

CodeFamilyWhen it fires
K9O_TIER_CAP_HITCapacityA tier-bound cap (e.g. MAU, storage) has been reached
K9O_INVALID_CREDENTIALSAuthEmail/password combination is incorrect
K9O_INVALID_BASE_URLValidation (SDK construct-time)baseUrl passed to createClient contains a path segment or an unsupported scheme

The full catalogue is at /api/conventions#2-kerror.


Async and streaming​

Virtual threads​

The SDK is built for JDK 21 virtual threads. Blocking I/O paths (query, insert, gate calls) pin to virtual threads when invoked from a virtual-thread executor — you do not need to wrap calls in a CompletableFuture to achieve concurrency. For platform thread pools the SDK is also safe; it has no thread-affinity requirement.

Realtime subscriptions​

Realtime subscriptions are delivered over Server-Sent Events as a stream you iterate with for. 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.

import dev.k9o.Realtime;

try (var stream = k9o.realtime().subscribe(Realtime.Topic.collection("orders"), null)) {
for (var event : stream) {
System.out.println(event.eventType() + ": " + event.payload()); // RealtimeEvent: topic, eventType, payload, occurredAt, eventId
}
// Output (illustrative):
// row_inserted: {id=order-124, total=42}
// row_deleted: {id=order-124}
}

See the Realtime API reference for topics and the frame format.

Streams​

Streams are ordered and replayable. maxBytes is at least 10485760 (10 MiB), and the stream's slug from the create result is what the other calls take. subscribe(slug, null) starts at the first event; pass a sequence string to resume after it, and close the subscription (the break inside try-with-resources) to end it.

import dev.k9o.Streams;

Streams.UserStream stream = k9o.streams().create("orders", 10_485_760L, null).data();
k9o.streams().publish(stream.slug(), Map.of("id", 1, "total", 42), "eu.new");
k9o.streams().publish(stream.slug(), Map.of("id", 2, "total", 17), null);

try (var events = k9o.streams().subscribe(stream.slug(), null)) {
for (Streams.StreamEvent event : events) {
System.out.println(event.sequence() + " " + event.data()); // 1 {id=1, total=42}
if ("2".equals(event.sequence())) break;
}
// Output (illustrative):
// 1 {"id":1,"total":42}
// 2 {"id":2,"total":17}
}

Streams.ReplayResult page = k9o.streams().replay(stream.slug(), 0L, null, 10).data();
System.out.println(page.events().size() + " " + page.hasMore());
// Output (illustrative):
// 2 false

See also​

  • Full API reference — every surface, every parameter, every error code
  • API conventions — response envelope, KError shape, pagination, idempotency
  • CLI — the same platform surface from the terminal
  • All SDKs — TypeScript, Python, Kotlin, .NET, Swift, Ruby, PHP, Dart, Go, Rust, React Native