Kiri Developers

EXAMPLES

Example: a shop module

shop is a small web shop: it lists orders and takes payments. It uses five of the SDK’s six calls, so it’s the module to read when you want to see them together: kiri.Serve for requests, kiri.DB for orders, kiri.HTTP and kiri.Secret to charge a card with Stripe, kiri.KV so a retried checkout doesn’t charge twice, and kiri.Log for what happened. The quick start builds its first part; this page is the whole thing.

What it may touch

kiri.yaml lists everything the module reaches. Five keys, and nothing else: no files, no other sites, no environment of yours.

app: shop
needs:
  port: 8080
  database: sqlite          # kept by Kiri, under the name shop
  network: [api.stripe.com]
  secrets: [STRIPE_KEY]
  kv: true
Key The call it opens What shop uses it for
port: 8080 kiri.Serve Kiri listens on 8080 and at shop.kiri.local, and hands each request to the handlers.
database: sqlite kiri.DB The orders table, kept by Kiri between runs and rebuilds.
network: [api.stripe.com] kiri.HTTP Creating a charge. Any other host is refused before anything is sent.
secrets: [STRIPE_KEY] kiri.Secret Stripe’s key, read from the keychain when the charge is made.
kv: true kiri.KV Remembering each checkout’s idempotency key, so a retry gets the same order back.

kiri.Log needs no key. Someone who runs this module from a registry reads these five as lines of a prompt, such as Reach these sites: api.stripe.com, before it starts. See kiri.yaml.

The code

Two routes. GET /orders lists orders from the database. POST /checkout takes a total in cents and an Idempotency-Key header: if it has seen the key before, it answers with the same order; if not, it charges the card, stores the order and remembers the key. Pick your language with the tabs or the picker at the top of the page.

package main

import (
	"fmt"
	"net/http"
	"strings"

	"runkiri.com/go/kiri"
)

func main() {
	db, kv, log := kiri.DB(), kiri.KV(), kiri.Log()
	db.Exec(`CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, total INTEGER)`)

	http.HandleFunc("GET /orders", func(w http.ResponseWriter, r *http.Request) {
		rows, err := db.Query("SELECT id, total FROM orders ORDER BY id DESC")
		// ... scan the rows and write them as JSON, as any Go service does
	})

	http.HandleFunc("POST /checkout", func(w http.ResponseWriter, r *http.Request) {
		key := "checkout:" + r.Header.Get("Idempotency-Key")
		if id, ok, _ := kv.Get(key); ok {
			w.Write(id) // a retry: the same order, not a second charge
			return
		}
		total := r.FormValue("total")
		secret, err := kiri.Secret("STRIPE_KEY")
		if err != nil {
			http.Error(w, "payments aren't set up", 503)
			return
		}
		req, _ := http.NewRequest("POST", "https://api.stripe.com/v1/charges",
			strings.NewReader("currency=eur&amount="+total))
		req.Header.Set("Authorization", "Bearer "+secret)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		resp, err := kiri.HTTP().Do(req)
		if err != nil || resp.StatusCode != 200 {
			log.Error("stripe: charge failed", "total", total, "err", err)
			http.Error(w, "the payment didn't go through", 402)
			return
		}
		var id int64
		db.QueryRow("INSERT INTO orders (total) VALUES (?) RETURNING id", total).Scan(&id)
		kv.Set(key, []byte(fmt.Sprint(id)))
		log.Info("charge created", "order", id, "total", total)
		fmt.Fprint(w, id)
	})

	log.Error("stopped", "err", kiri.Serve(nil))
}
use axum::{http::{HeaderMap, StatusCode}, routing::{get, post}, Form, Router};
use serde::Deserialize;

type Answer = Result<String, (StatusCode, String)>;
fn bad(e: kiri::Error) -> (StatusCode, String) {
    (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
}

#[derive(Deserialize)]
struct Checkout { total: i64 }

async fn orders() -> Answer {
    let rows = kiri::db()
        .query("SELECT id, total FROM orders ORDER BY id DESC", ())
        .await.map_err(bad)?;
    // ... turn the rows into JSON, as any axum handler does
}

async fn checkout(headers: HeaderMap, Form(c): Form<Checkout>) -> Answer {
    let idem = headers.get("idempotency-key")
        .and_then(|v| v.to_str().ok()).unwrap_or("");
    let key = format!("checkout:{idem}");
    if let Some(id) = kiri::kv().get(&key).await.map_err(bad)? {
        // a retry: the same order, not a second charge
        return Ok(String::from_utf8_lossy(&id).into_owned());
    }
    let secret = kiri::secret("STRIPE_KEY").map_err(bad)?;
    let resp = kiri::http().post("https://api.stripe.com/v1/charges")
        .bearer_auth(&secret)
        .form(&[("currency", "eur".to_string()), ("amount", c.total.to_string())])
        .send().await.map_err(bad)?;
    if !resp.status().is_success() {
        log::error!("stripe: charge failed total={}", c.total);
        return Err((StatusCode::PAYMENT_REQUIRED, "the payment didn't go through".into()));
    }
    let rows = kiri::db()
        .query("INSERT INTO orders (total) VALUES (?) RETURNING id", (c.total,))
        .await.map_err(bad)?;
    let id: i64 = rows[0].get("id").map_err(bad)?;
    kiri::kv().set(&key, id.to_string()).await.map_err(bad)?;
    log::info!("charge created order={id} total={}", c.total);
    Ok(id.to_string())
}

fn main() -> Result<(), kiri::Error> {
    kiri::log::init();
    let app = Router::new()
        .route("/orders", get(orders))
        .route("/checkout", post(checkout));
    kiri::serve(app)
}
import * as kiri from "@kiri/sdk";

const db = kiri.db();
const kv = kiri.kv();

async function app(req: Request): Promise<Response> {
  const { pathname } = new URL(req.url);

  if (req.method === "GET" && pathname === "/orders") {
    const { rows } = await db.query("SELECT id, total FROM orders ORDER BY id DESC");
    return Response.json(rows);
  }

  if (req.method === "POST" && pathname === "/checkout") {
    const key = `checkout:${req.headers.get("idempotency-key") ?? ""}`;
    const done = await kv.get(key);
    if (done) return new Response(done); // a retry: the same order, not a second charge

    const total = String((await req.formData()).get("total"));
    const stripe = await kiri.http.fetch("https://api.stripe.com/v1/charges", {
      method: "POST",
      headers: { authorization: `Bearer ${kiri.secret("STRIPE_KEY")}` },
      body: new URLSearchParams({ currency: "eur", amount: total }),
    });
    if (!stripe.ok) {
      kiri.log.error("stripe: charge failed", { total });
      return new Response("the payment didn't go through", { status: 402 });
    }
    const { rows } = await db.query("INSERT INTO orders (total) VALUES (?) RETURNING id", [total]);
    await kv.set(key, String(rows[0].id));
    kiri.log.info("charge created", { order: rows[0].id, total });
    return new Response(String(rows[0].id));
  }

  return new Response("not found", { status: 404 });
}

kiri.serve(app);
import logging

import kiri
from flask import Flask, jsonify, request

app = Flask(__name__)
db = kiri.db()
kv = kiri.kv()
log = logging.getLogger("shop")   # logging already goes to the module's log


@app.get("/orders")
def orders():
    cur = db.cursor()
    cur.execute("SELECT id, total FROM orders ORDER BY id DESC")
    return jsonify([{"id": i, "total": t} for i, t in cur.fetchall()])


@app.post("/checkout")
def checkout():
    key = "checkout:" + request.headers.get("Idempotency-Key", "")
    done = kv.get(key)
    if done is not None:
        return done                       # a retry: the same order, not a second charge

    total = request.form["total"]
    resp = kiri.http.post(
        "https://api.stripe.com/v1/charges",
        headers={"Authorization": "Bearer " + kiri.secret("STRIPE_KEY")},
        data={"currency": "eur", "amount": total},
    )
    if resp.status_code != 200:
        log.error("stripe: charge failed", extra={"total": total})
        return "the payment didn't go through", 402

    cur = db.cursor()
    cur.execute("INSERT INTO orders (total) VALUES (?) RETURNING id", (total,))
    order = cur.fetchone()[0]
    kv.set(key, str(order))
    log.info("charge created", extra={"order": order, "total": total})
    return str(order)


kiri.serve(app)

Nothing in the handlers knows where the database is, what Stripe’s key is, or which port the shop listens on. They ask Kiri, and Kiri checks each call against kiri.yaml. The database uses SQLite’s ? placeholders; with database: postgres they’d be $1, and nothing else in the code changes.

The calls behind one checkoutYour browserKirishopapi.stripe.comPOST /checkout · :8080requestkv get checkout:a1not there: not a retrysecret STRIPE_KEYread from the keychainhttp POST /v1/chargesin network: sent200db insert · kv set1042
One checkout, call by call. Kiri takes the request on port 8080 and hands it to the handler. The handler asks the store whether it's a retry, reads Stripe's key from the keychain through Kiri, asks Kiri to make the charge, and stores the order. Every call goes through Kiri; the module never holds a socket, an address or a password.

Run it

kiri check reads the project and the code, and kiri run builds and starts the module. STRIPE_KEY isn’t set the first time, so kiri run asks for it before the module starts and keeps it in your keychain. Use a test key while you try it.

zsh
$ kiri check .
  shop · Go 1.26 · 44 packages
  ✓ 44 packages work as WebAssembly · 0 to change
$ kiri run .
  ◆ shop  building Go 1.26 → WebAssembly…
  ✓ built · uses db, kv, network, port, secrets · kiri.yaml lists all five
  STRIPE_KEY isn't set yet. Value (not shown): ••••••••••••••••
  ✓ saved in your keychain
  ●  serving on :8080 · 2.4 MB · started in 1.3 ms · needs db, kv, network, port, secrets
     http://shop.kiri.local · http://localhost:8080

  Logs show up below. Press Ctrl+C to stop.

  14:05:01  info    charge created  order=1042 total=4250
  14:05:01  POST    200  /checkout             412 ms
  14:05:03  POST    200  /checkout             2 ms

The second POST is a retry with the same Idempotency-Key. It took 2 ms, made no call to Stripe, and answered with the same order:

zsh
$ curl -X POST http://shop.kiri.local/checkout -H "Idempotency-Key: a1" -d total=4250
1042
$ curl -X POST http://shop.kiri.local/checkout -H "Idempotency-Key: a1" -d total=4250
1042
$ curl http://shop.kiri.local/orders
[{"id":1042,"total":4250}]

In Kiri’s window

The module is under Modules in the sidebar, with Share and Stop on its row. Its Logs tab has the lines from kiri.Log, with their fields, and Kiri’s own lines among them. Its Permissions tab lists the five keys in the prompt’s words, what the module did with each, and anything it tried that kiri.yaml doesn’t allow.

Kiri
KiriModulesUSBShareSettings

Modules › shop

OverviewLogsPermissionsSecurity
14:05:01infocharge createdorder=1042 total=4250
14:05:01infoPOST /checkout 200412 ms
14:05:03infoPOST /checkout 2002 ms
14:06:40errorstripe: charge failedtotal=9900
14:07:12warnrefused kiri.HTTP → api.github.comnot in network
The shop module's Logs tab after a few checkouts. The charges carry their order and total as fields; a declined card is an error line; the refused call is Kiri's own line, because a library tried to reach a site that isn't in network.

To put the shop online for someone to try, press Share on its row or run kiri share shop. To give it a real Postgres, change database: sqlite to database: postgres; Kiri starts shop-postgres for it, or connects to your own server if you set the module’s DATABASE_URL secret.

© 2026 Kiri · The SDK is open source under the Apache License 2.0 · Docs · runkiri.com