A production web API in Jennifer

Jennifer

Versioned routes, migrations, contracts, idempotency, a lifecycle, signed webhooks, logs and end-to-end tests.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 23

What we build

POST /v1/tokens              name + password -> bearer token
GET  /v1/orders              filter, page, Link: rel="next"
POST /v1/orders              JSON Schema checked, Idempotency-Key
GET  /v1/orders/:id          ?select=<JSONPath>
POST /v1/orders/:id/events   pay, ship, deliver, cancel
POST /v1/hooks/payments      signed by the payment provider
GET  /v1/schemas/order.json  the contract   GET /v1  discovery

app.j, src/store.j (SQL), src/lifecycle.j, migrate.j, adduser.j; decks @deckyard/jsonschema, jsonpath, fsm.

2 / 23

webapi: a route is a handler plus a Spec

def api as webapi.Api init webapi.new();
$api = webapi.mount($api, 1, "/v1");
$api = webapi.authenticator($api, verifyToken);
$api = webapi.limiter($api, countHit);
$api = webapi.get($api, "/orders", listOrders, webapi.Spec{
    summary: "list orders", auth: webapi.Auth.Bearer,
    scopes: ["orders:read"], rateLimit: 600,
    rules: {"state": [validate.oneOf(STATES)],
        "customer": [validate.maxLen(254)]}});
func apiGuard(ctx as web.Context) { return webapi.guard($api, $ctx); }
$app = webapi.install($api, $app, apiGuard);
3 / 23

One envelope for every refusal

GET  /v1/orders  no token        401 {"error":"missing bearer token"}
                                     WWW-Authenticate: Bearer
GET  /v1/orders  unknown token   401 {"error":"unauthorized"}
POST /v1/orders  orders:read     403 {"error":"missing scope: orders:write"}
GET  /v1/orders?state=lost       422 {"error":"invalid request",
  "failures":[{"field":"state","rule":"oneOf",
  "message":"must be one of: new, paid, shipped, delivered, cancelled"}]}
POST /v1/tokens  6th in a minute 429 {"error":"rate limit exceeded"}
                                     Retry-After: 28
4 / 23

Versions: a mount, or a second Api

def v1 as webapi.Api init webapi.deprecate(webapi.mount(webapi.new(),
    1, "/v1"), 1, "2027-06-30");
def v2 as webapi.Api init webapi.mount(webapi.new(), 2, "/v2");
$app = webapi.install($v1, $app, guard1);
$app = webapi.install($v2, $app, guard2);
GET /v1  {"registry":"shop","spec":"1.0","apis":[{"version":1,
  "basePath":"/v1","deprecated":false}],"features":["POST /tokens",
  "GET /orders","POST /orders",...,"discovery"]}
5 / 23

Migrations: frozen text in src/store.j

export def const MIGRATIONS as list of mig.Migration init [
    mig.Migration{version: "001", description: "api users and tokens",
        up: ["CREATE TABLE api_users (id SERIAL PRIMARY KEY," +
            " name TEXT NOT NULL UNIQUE, pwhash TEXT NOT NULL," +
            " scopes TEXT NOT NULL)", "CREATE TABLE api_tokens ..."],
        down: ["DROP TABLE api_tokens", "DROP TABLE api_users"]},
    mig.Migration{version: "002", description: "orders",
        up: ["CREATE TABLE orders (...)",
            orm.createIndex("orders_state", "orders", ["state"], false)],
        down: ["DROP TABLE orders"]},
    # 003 idempotency_keys
];
6 / 23

Migrating at deploy: once, under a lock

# migrate.j: sqlmigrate 0.26.0 takes no lock, so hold one
def lock as sql.Tx init sql.begin($conn);
defer sql.rollback($lock);
sql.closeRows(sql.query($lock,
    "SELECT pg_advisory_xact_lock(hashtext('shop.migrate'))"));
def n as int init mig.migrate($conn, store.MIGRATIONS);
$ jennifer run migrate.j & jennifer run migrate.j
lock held, migrating / applied 3 migration(s)
lock held, migrating / applied 0 migration(s)
$ jennifer run app.j        # on a database nobody migrated
level=fatal msg="schema out of date: run migrate.j first" pending=3
7 / 23

orm: queries built, never concatenated

export func filtered(f as Filter) {
    def q as orm.Query init orm.from(orders());
    if ($f.state != "") { $q = orm.where($q, "state", "=", $f.state); }
    # ... the same for customer ...
    return $q;
}
export func listQuery(f as Filter) {
    def q as orm.Query init orm.orderBy(filtered($f), "id", "desc");
    return orm.offset(orm.limit($q, $f.limit), $f.offset);
}
SELECT * FROM orders WHERE state = $1 ORDER BY id DESC LIMIT 20 OFFSET 40
SELECT COUNT(*) AS n FROM orders WHERE state = $1      params ["new"]
8 / 23

Paging: webapi.page, and a Link from uri

def p as webapi.Page init webapi.page($ctx, 20, 100);
# ... count, fetch $p.limit rows from $p.offset ...
if ($p.offset + $p.limit < $total) {
    $q["offset"] = "{$p.offset + $p.limit}";
    $q["limit"] = "{$p.limit}";
    def next as string init link("/v1/orders?" + uri.buildQuery($q));
    web.setHeader($ctx, "Link", "<{$next}>; rel=\"next\"");
}
webapi.sendPage($ctx, $items, $p, $total);
GET /v1/orders?state=new&limit=2   200
Link: <http://127.0.0.1:18480/v1/orders?state=new&offset=2&limit=2>; rel="next"
{"items":[{"id":7,...},{"id":6,...}],"offset":0,"limit":2,"total":5}
9 / 23

API users: a policy, then argon2id

# adduser.j: the password comes from standard input
def policy as password.Schema init password.withMinimums(
    password.withLength(password.schema(), 12, 128), 1, 1, 1, 0);
def report as password.Report init password.validate($policy, $pw);
if (not $report.valid) {
    io.eprintf("adduser: %s\n", strings.join($report.reasons, "; "));
    exit 1;
}
$ echo 'short' | jennifer run adduser.j bob "orders:read"
adduser: too short (minimum 12); needs at least 1 uppercase; needs at
  least 1 digits
10 / 23

Tokens: shown once, stored as a hash

# login(): an unknown name costs one argon2id check too
if (not sql.next($rows)) {
    crypto.verifyPassword($pw, DUMMY_HASH);
    return 0;
}
# newToken(): the client sees the token, the table its SHA-256
def token as string init "shp_" +
    encoding.toText("hex", crypto.randBytes(24));
sql.exec($conn, "INSERT INTO api_tokens (hash, user_id)" +
    " VALUES ($1, $2)", tokenHash($token), $userId);
return $token;
11 / 23

Contract first: one schema for docs and checks

src/order.schema.json, served as GET /v1/schemas/order.json
"required": ["customer", "lines"], "additionalProperties": false,
"customer": {"type": "string", "format": "email", "maxLength": 254},
"lines": {"type": "array", "minItems": 1, "maxItems": 50, "items": {
  "required": ["sku", "qty", "cents"], "additionalProperties": false,
  "sku": {"type": "string", "pattern": "^[A-Z]{3}-[0-9]{2}$"},
  "qty": {"type": "integer", "minimum": 1, "maximum": 99}, ...}}
def const ORDER_SCHEMA as jsonschema.Schema init
    jsonschema.assertFormats(jsonschema.compile(
        json.decode(ORDER_SCHEMA_TEXT)), true);
12 / 23

Schema failures, in the same envelope

def r as jsonschema.Result init jsonschema.validate(ORDER_SCHEMA, $doc);
if (not $r.valid) {
    webapi.failWith($ctx, 422, "invalid order", schemaFailures($r));
POST /v1/orders {"customer":"ada@","lines":[{"sku":"tea","qty":0,
  "cents":450,"gift":true}],"coupon":"FREE"}
422 {"error":"invalid order","failures":[
 {"field":"(root)","rule":"additionalProperties",...},
 {"field":"/customer","rule":"format","message":"is not a valid email"},
 ... /lines/0: additionalProperties, /lines/0/sku: pattern ...
 {"field":"/lines/0/qty","rule":"minimum","message":"must be \u003e= 1"}]}
13 / 23

Idempotent POST: claim the key in the transaction

def reqHash as string init store.tokenHash($raw);   # SHA-256
def tx as sql.Tx init sql.begin($db);
errdefer sql.rollback($tx);
if (not store.claimKey($tx, $uid, $key, $reqHash)) {
    sql.rollback($tx);
    replay($ctx, $uid, $key, $reqHash);       # or 422 on another body
    return;
}
# ... insert the order with orm.insertReturning ...
store.saveResponse($tx, $uid, $key, 201, json.encode($out));
sql.commit($tx);

claimKey: INSERT INTO idempotency_keys ... ON CONFLICT DO NOTHING

14 / 23

Idempotency, on the wire

POST /v1/orders  Idempotency-Key: 7f3c9a2e-0001
201 Location: http://127.0.0.1:18480/v1/orders/1
    {"id":1,"customer":"ada@example.org","state":"new",...}
POST /v1/orders  Idempotency-Key: 7f3c9a2e-0001   (same body)
201 Idempotent-Replayed: true
    {"id":1,"customer":"ada@example.org","state":"new",...}
POST /v1/orders  Idempotency-Key: 7f3c9a2e-0001   (another body)
422 {"error":"Idempotency-Key reused with another body"}
POST /v1/orders  no key
400 {"error":"Idempotency-Key: 8 to 64 letters, digits, -"}
15 / 23

The order lifecycle as a state machine

def m as fsm.Machine init fsm.machine("order", "new");
$m = fsm.addStates($m, ["paid", "shipped", "delivered", "cancelled"]);
$m = fsm.addFinals($m, ["delivered", "cancelled"]);
$m = fsm.addTransition($m, "pay", ["new"], "paid");
$m = fsm.addTransition($m, "ship", ["paid"], "shipped");
$m = fsm.addTransition($m, "deliver", ["shipped"], "delivered");
$m = fsm.addTransition($m, "cancel", ["new"], "cancelled");
$m = fsm.addGuarded($m, "cancel", ["paid"], "cancelled", isAdmin);
s1 --> s4 : cancel [isAdmin]      fsm.mermaid    fsm.check: []
16 / 23

Firing an event, the row locked

def row as map of string to string init store.lockOrder($tx, $id);
try {
    $step = fsm.fire(LIFECYCLE, $row["state"], $event, $ctx);
} catch (e) {
    if ($e.kind != fsm.ERROR_KIND) { throw $e; }
    sql.rollback($tx);
    return Outcome{status: 409, state: $row["state"],
        allowed: fsm.events(LIFECYCLE, $row["state"], $ctx), ...};
}
ship, new           409 {"error":"cannot ship an order that is new",
                         "state":"new","allowed":["pay","cancel"]}
cancel, paid: clerk 409 {...,"allowed":["ship"]}, admin 200
17 / 23

?select=: JSONPath from the client, on a budget

def p as jsonpath.Path init jsonpath.compile($sel);
$p.maxNodes = 10000;             # a query from outside: a small budget
try {
    for (def m in jsonpath.find($doc, $p)) {
        $values = json.append($values, "", $m.value);
    }
} catch (e) { ... }              # kind "limit": 422
?select=$.lines[*].sku          {"values":["TEA-01","MUG-02"]}
?select=$.lines[?@.cents > 1000]
                     {"values":[{"sku":"MUG-02","qty":1,"cents":1200}]}
?select=$.lines[(    422 [{"field":"select","rule":"custom",
                     "message":"must be a JSONPath query"}]
18 / 23

Outgoing webhooks: signed, off the request

def t as task of null init spawn { deliver($body, $reqId); return null; };
task.discard($t);
# deliver:
def headers as map of string to string init {
    "Content-Type": "application/json",
    "Shop-Signature": webhook.stripeSign($hookSecret, $body, $now)};
def r as http.Response init
    http.requestWith("POST", $hookUrl, $headers, $body, 5000, 65536);
level=info msg="webhook delivered" req=01a1f42f-a6f5-...
  hook=http://127.0.0.1:18490/hooks status=204
sink: order.paid order 2 (paid)
19 / 23

Incoming webhooks: verify the raw body

def body as string init encoding.decode("utf-8", web.body($ctx));
if (not webhook.stripeVerify($paySecret, $body,
    web.header($ctx, "Payment-Signature"), 300, $now)) {
    webapi.fail($ctx, 401, "bad signature");
    return;
}
def o as Outcome init transition($id, "pay", "system");
if ($o.status == 409 and $o.state != "new") { ... 200, already paid }
$ jennifer run pay.j 2              200 {"id":2,...,"state":"paid",...}
$ jennifer run pay.j 2              200 {"ok":true,"state":"paid"}
$ jennifer run pay.j 3 --tamper     401 {"error":"bad signature"}
20 / 23

Structured logs, one request id

func stamp(ctx as web.Context) {      # the first middleware
    def id as string init web.header($ctx, "X-Request-Id");
    if (not regex.matches('^[A-Za-z0-9-]{8,64}$', $id)) { $id = uuid.v7(); }
    httpd.setRequestValue($ctx.req, "reqId", $id);
    web.setHeader($ctx, "X-Request-Id", $id);
    log.info(reqLog($ctx), "request", ...);   # method, path
    return true;
}
level=info msg=request req=01a1f42e-010a-... method=POST
  path=/v1/orders
level=info msg="order created" req=01a1f42e-010a-... order=1
21 / 23

Testing end to end: the real app, a fresh database

func fresh() {                # e2e_test.j
    sql.exec($admin, "CREATE DATABASE " + $name);
    os.setEnv("SHOP_DB_DSN", $server + $name + "?sslmode=disable");
    os.run(["jennifer", "run", "migrate.j"]);   # and adduser.j
    def app as os.Process init os.spawn(["jennifer", "run", "app.j"],
        {"stdout": "discard", "stderr": "discard"});
    # ... poll /healthz, return the Fixture ...
}
$ jennifer test e2e_test.j       # SHOP_TEST_DSN set
PASS testCreateIsIdempotent (756 ms)
PASS testIllegalTransitionIsRefused (710 ms)
PASS testUnsignedPaymentIsRefused (609 ms)
22 / 23

Before it goes live

Based on Jennifer 0.27.0, November 2026.

23 / 23