Skip to content
Jennifer Programming Language

webapi API reference

A JSON-API conventions layer over the bundled web module. web is the HTTP framework - routing, :param captures, middleware, cookies, sessions, CORS, ETag; webapi adds the pieces every JSON API re-implements by hand on top of it: a uniform error envelope, request validation (reusing validate), versioned route mounting, pluggable bearer auth and rate limiting (the app supplies a verifier and a counter as func values, so this module depends on no jwt / store), content negotiation, and pagination.

It is a value-semantic builder finished once, before the server runs: webapi.new() -> add mounts, an authenticator, routes with a Spec -> webapi.install($api, $app, apiGuard). Routes and the authenticator / limiter are func values; the one small guard shim in the entry program exists only to bind the built Api into web as every route's handler (Jennifer has no closures yet, so the shim captures $api through a top-level binding):

func apiGuard(ctx as web.Context) { return webapi.guard($api, $ctx); }

The Spec-evaluation core (webapi.evaluate) is a pure function of (Spec, Identity, data), testable without a server. Needs the default jennifer binary (web needs net); unavailable under jennifer-tiny.

Import with import "webapi.j" as webapi;. See the webapi guide for prose and examples.

Contents

NameWhat it is
aliasAdditionally serve version at the bare root, so /v1/deck is also reachable as /deck.
authenticatorSet the authenticator: an entry-program func(token as string) -> webapi.Identity value.
deleteRegister a DELETE route with a Spec.
deniedSend a 403 error envelope.
deprecateMark every mount of version deprecated with a sunset date: the discovery document lists it, and every res...
deprecatedSinceMark every mount of version deprecated as of since: the discovery document lists it, and every response...
discoveryBuild the discovery document from the route table, so the advertised versions and features cannot drift fro...
evaluateThe pure core: decide whether a request bearing identity and data may proceed under spec, without tou...
failSend the uniform error envelope {"error": message} at status.
failWithSend the error envelope with field-level failures detail:...
featureSet an explicit discovery feature label for the most recently added route (defaults to "METHOD /pattern"), ...
formDataThe form body (application/x-www-form-urlencoded) as a string map.
getRegister a GET route with a Spec.
guardThe Spec-enforcing guard.
identityInside a handler: the authenticated identity for this request - the one the guard computed, kept on the req...
installRegister every route on the web.App, once per mount path (via web.mount), with the guard as its web h...
jsonDataThe named top-level JSON body fields, flattened to strings (a nested or array-valued field is omitted; read...
limitKeySet how an unauthenticated request is keyed for rate limiting: an entry-program...
limiterSet the rate limiter: an entry-program func(key as string, limit as int) -> ratelimit.Result value - usua...
mountServe this version's routes under path, returning a new Api.
negotiatePick the media type the caller prefers from those the handler can send, by the request's Accept header (R...
newA fresh, empty API builder.
notFoundSend a 404 error envelope.
onErrorRegister a web.onError hook on app (it is web.onError).
pageParse the offset / limit query parameters into a Page.
patchRegister a PATCH route with a Spec.
postRegister a POST route with a Spec.
publicA zero Spec: a public JSON route with no scopes, rules, or rate limit.
putRegister a PUT route with a Spec.
queryDataThe named query parameters as a string map (absent names omitted).
sendJsonSend an envelope-consistent JSON response.
sendPageSend a paged list response: {"items": [...], "offset", "limit", "total"}.
unauthorizedSend a 401 error envelope with a WWW-Authenticate: Bearer header.
validatedInside a handler: the request data the route's rules were checked against (query, then the body's top-level...
wantsWhat the caller wants from the Accept header: "json" or "html", by content negotiation (see...
Apistruct: The built API description: its routes, mount points, and the authenticator / limiter func values.
Decisionstruct: The outcome of evaluating a Spec against a request: proceed, or halt with the status + message (and any v...
Identitystruct: The result of authenticating a request.
Mountstruct: One version mount point.
Pagestruct: A page window parsed from a request's offset / limit query parameters by webapi.page.
RouteDefstruct: One registered route.
RouteEntrystruct: One mount and route pair as the guard matches it: the route served under the mount, with the full pattern a...
Specstruct: The metadata attached to a route: what it needs and what it makes.
Authenum: How a route authenticates.
Producesenum: What a route produces, driving content negotiation.

Functions

alias

jennifer
webapi.alias(a as Api, version as int)

Additionally serve version at the bare root, so /v1/deck is also reachable as /deck.

a
the builder to extend
version
the version to also mount at the root
Returns Api
a new Api with the root alias added

authenticator

jennifer
webapi.authenticator(a as Api, handler as func)

Set the authenticator: an entry-program func(token as string) -> webapi.Identity value. The module calls it for a Bearer route; it never learns how a token is verified.

a
the builder to extend
handler
the verifier func value
Returns Api
a new Api with the authenticator set

delete

jennifer
webapi.delete(a as Api, pattern as string, handler as func, spec as Spec)

Register a DELETE route with a Spec.

a
the builder to extend
pattern
the route pattern
handler
the entry-program handler func value
spec
the route's specification
Returns Api
a new Api with the route added

denied

jennifer
webapi.denied(ctx as web.Context, message as string)

Send a 403 error envelope.

ctx
the request context
message
the error message

deprecate

jennifer
webapi.deprecate(a as Api, version as int, sunset as string)

Mark every mount of version deprecated with a sunset date: the discovery document lists it, and every response of its routes carries Sunset: <HTTP-date> (RFC 8594). Set the date the deprecation took effect with deprecatedSince to also send Deprecation (RFC 9745).

a
the builder to extend
version
the version to deprecate
sunset
the sunset date: YYYY-MM-DD (00:00 UTC) or an RFC 3339 timestamp
Returns Api
a new Api with the version marked deprecated
Throws Error
kind "webapi" for a malformed date, or one before the deprecatedSince date

deprecatedSince

jennifer
webapi.deprecatedSince(a as Api, version as int, since as string)

Mark every mount of version deprecated as of since: the discovery document lists it, and every response of its routes carries Deprecation: @<seconds> (RFC 9745; a future date announces a coming deprecation). Pair with deprecate for the sunset date, which must not be earlier.

a
the builder to extend
version
the version to deprecate
since
the deprecation date: YYYY-MM-DD (00:00 UTC) or an RFC 3339 timestamp
Returns Api
a new Api with the version marked deprecated
Throws Error
kind "webapi" for a malformed date, or one after the sunset date

discovery

jennifer
webapi.discovery(a as Api, registry as string, specVersion as string)

Build the discovery document from the route table, so the advertised versions and features cannot drift from what is actually served: {"registry", "spec", "apis": [{version, basePath, deprecated, deprecatedSince, sunset}], "features": [name, ...]}. features is the set of route feature labels.

a
the built API
registry
the registry / service name to advertise
specVersion
the spec version string to advertise
Returns json.Value
the discovery document

evaluate

jennifer
webapi.evaluate(
    spec as Spec,
    identity as Identity,
    data as map of string to string)

The pure core: decide whether a request bearing identity and data may proceed under spec, without touching the engine. Returns proceed=true, or proceed=false with the status / message (and validation failures) to answer. Order: auth (401) -> scopes (403) -> validation (422). Rate limiting is applied by the guard (it is stateful), before these checks, not here.

spec
the route specification
identity
the authenticated caller (ok=false when none)
data
the request data to validate
Returns Decision
proceed, or a status + message to answer

fail

jennifer
webapi.fail(ctx as web.Context, status as int, message as string)

Send the uniform error envelope {"error": message} at status.

ctx
the request context
status
the HTTP status
message
the error message

failWith

jennifer
webapi.failWith(
    ctx as web.Context,
    status as int,
    message as string,
    failures as list of validate.Failure)

Send the error envelope with field-level failures detail: {"error": message, "failures": [{field, rule, message}, ...]}.

ctx
the request context
status
the HTTP status
message
the error message
failures
the per-field failures

feature

jennifer
webapi.feature(a as Api, feature as string)

Set an explicit discovery feature label for the most recently added route (defaults to "METHOD /pattern"), so the discovery document reads meaningfully.

a
the builder whose last route to label
feature
the feature name
Returns Api
a new Api with the last route's feature set
Throws Error
kind "webapi" when there is no route to label

formData

jennifer
webapi.formData(ctx as web.Context)

The form body (application/x-www-form-urlencoded) as a string map.

ctx
the request context
Returns map of string to string
the form fields

get

jennifer
webapi.get(a as Api, pattern as string, handler as func, spec as Spec)

Register a GET route with a Spec.

a
the builder to extend
pattern
the route pattern (:param captures allowed)
handler
the entry-program handler func value
spec
the route's specification
Returns Api
a new Api with the route added

guard

jennifer
webapi.guard(a as Api, ctx as web.Context)

The Spec-enforcing guard. Wire it from an entry-program shim named in install: func apiGuard(ctx) { return webapi.guard($api, $ctx); }. install registers the shim as each route's web handler. For a request it matches the route, then in this order: sets Deprecation / Sunset for a deprecated version, authenticates, rate-limits (every request counts, keyed on the identity's subject or else the client, so a flood of bad tokens or invalid bodies is limited too), answers a missing bearer token 401, checks the paging parameters (a malformed limit / offset is a 400), a rejected token (401), the scopes (403) and the rules (422). Any failure is answered with the error envelope. A request that passes runs the route's handler; a throw from the handler, or from the authenticator, limiter or key function, is answered 500 {"error": "internal server error"} (nothing of the error is sent, nor when the handler had already answered) and rethrown, so web logs it and calls its onError hook. A web.WebError with a 4xx status (a body that cannot be read: 400, past a body parser's cap: 413) is not answered here but rethrown as it is, so web answers it with its status, as a client fault.

Wired by hand as a web.before middleware instead (without install), it only checks: it returns true for a request that may proceed (or matches no API route), false when it has answered.

a
the built API
ctx
the request context
Returns bool
true to proceed to the handler, false when it has answered

identity

jennifer
webapi.identity(a as Api, ctx as web.Context)

Inside a handler: the authenticated identity for this request - the one the guard computed, kept on the request, so the authenticator is not called a second time. Called where no guard ran for the request, it calls the authenticator itself. Returns a zero Identity (ok: false) for an absent or rejected credential.

a
the built API
ctx
the request context
Returns Identity
the caller's identity

install

jennifer
webapi.install(a as Api, app as web.App, guard as func)

Register every route on the web.App, once per mount path (via web.mount), with the guard as its web handler. guard must be an entry-program func value that calls webapi.guard($api, $ctx); the shim is only needed to bind the Api (Jennifer has no closures yet for the guard to capture it directly). For each request of a route the guard enforces the Spec, then runs the route's handler (see guard), so it runs after every web.before middleware, whether registered before or after install.

a
the built API
app
the web router to register onto
guard
the entry-program guard shim func value
Returns web.App
a new App with the routes and guard installed

jsonData

jennifer
webapi.jsonData(ctx as web.Context, fields as list of string)

The named top-level JSON body fields, flattened to strings (a nested or array-valued field is omitted; read those with web.bodyJson). Only a body whose Content-Type is application/json (or a +json type) is read; for any other, or an empty body, the map is empty. A malformed JSON body throws web.WebError (status 400; kind "limit", status 413, past a cap).

ctx
the request context
fields
the JSON keys to read
Returns map of string to string
the present scalar fields

limitKey

jennifer
webapi.limitKey(a as Api, handler as func)

Set how an unauthenticated request is keyed for rate limiting: an entry-program func(ctx as web.Context) -> string value. The default is the client host (IPv6 by /64). Behind a reverse proxy every request comes from the proxy, so supply a function that reads the forwarding header the proxy sets - and trust it only from the proxy: any client can send X-Forwarded-For, so honouring it unconditionally lets a client pick its own bucket. Authenticated requests stay keyed on the identity's subject.

a
the builder to extend
handler
the key func value
Returns Api
a new Api with the key function set

limiter

jennifer
webapi.limiter(a as Api, handler as func)

Set the rate limiter: an entry-program func(key as string, limit as int) -> ratelimit.Result value - usually ratelimit.check over a limiter built for limit. A denied request is answered 429 with Retry-After from the result's retryAfter. The key is the identity's subject when authenticated, else the limitKey function's result, else the client host (an IPv6 client by its /64, since one host routinely holds a whole /64).

a
the builder to extend
handler
the limiter func value
Returns Api
a new Api with the limiter set

mount

jennifer
webapi.mount(a as Api, version as int, path as string)

Serve this version's routes under path, returning a new Api. A version may be mounted at several paths (mount then alias); each is served by install.

a
the builder to extend
version
the version label (surfaced in discovery)
path
the base path to mount under
Returns Api
a new Api with the mount added

negotiate

jennifer
webapi.negotiate(ctx as web.Context, offered as list of string)

Pick the media type the caller prefers from those the handler can send, by the request's Accept header (RFC 9110 content negotiation). Each offered type takes the quality (q, default 1) of the most specific range that matches it (an exact type/subtype over a type wildcard over the full wildcard); the highest positive quality wins, and a tie goes to the type listed first in offered. A range whose q is not an RFC 9110 qvalue (0 to 1, at most three decimals) is ignored. An absent header accepts everything, so the first offered type wins.

ctx
the request context
offered
the media types the handler can produce, in order of preference
Returns string
the chosen type from offered, or "" when the caller accepts none of them

new

jennifer
webapi.new()

A fresh, empty API builder.

Returns Api
an API with no routes, mounts, or auth

notFound

jennifer
webapi.notFound(ctx as web.Context, message as string)

Send a 404 error envelope.

ctx
the request context
message
the error message

onError

jennifer
webapi.onError(app as web.App, handler as func)

Register a web.onError hook on app (it is web.onError). A throw from an installed route's handler is already answered by the guard with a 500 envelope {"error": "internal server error"}; it is then rethrown, so web writes it to stderr and calls this hook with it, for logging or alerting. The hook runs after the response is sent and cannot change it.

app
the router to extend
handler
an entry-program func(e as Error) value
Returns web.App
a new App with the error handler set

page

jennifer
webapi.page(ctx as web.Context, defaultLimit as int, maxLimit as int)

Parse the offset / limit query parameters into a Page. An absent limit is defaultLimit, an absent offset 0; a limit above maxLimit is lowered to it, so a client cannot ask for the whole table. A value that is not a whole number of at most 18 digits, or a limit of 0, is the client's error: on an API route guard has already answered it with a 400 envelope, so page only throws for it on a route the guard does not cover.

ctx
the request context
defaultLimit
the limit when none is supplied
maxLimit
the largest allowed limit
Returns Page
the window
Throws Error
kind "webapi" for a malformed limit or offset

patch

jennifer
webapi.patch(a as Api, pattern as string, handler as func, spec as Spec)

Register a PATCH route with a Spec.

a
the builder to extend
pattern
the route pattern
handler
the entry-program handler func value
spec
the route's specification
Returns Api
a new Api with the route added

post

jennifer
webapi.post(a as Api, pattern as string, handler as func, spec as Spec)

Register a POST route with a Spec.

a
the builder to extend
pattern
the route pattern
handler
the entry-program handler func value
spec
the route's specification
Returns Api
a new Api with the route added

public

jennifer
webapi.public()

A zero Spec: a public JSON route with no scopes, rules, or rate limit. Keeps an unauthenticated route a one-liner: webapi.get($a, "/x", h, webapi.public()).

Returns Spec
the zero specification

put

jennifer
webapi.put(a as Api, pattern as string, handler as func, spec as Spec)

Register a PUT route with a Spec.

a
the builder to extend
pattern
the route pattern
handler
the entry-program handler func value
spec
the route's specification
Returns Api
a new Api with the route added

queryData

jennifer
webapi.queryData(ctx as web.Context, fields as list of string)

The named query parameters as a string map (absent names omitted).

ctx
the request context
fields
the parameter names to read
Returns map of string to string
the present query values

sendJson

jennifer
webapi.sendJson(ctx as web.Context, status as int, value as json.Value)

Send an envelope-consistent JSON response.

ctx
the request context
status
the HTTP status
value
the response body

sendPage

jennifer
webapi.sendPage(
    ctx as web.Context,
    items as json.Value,
    p as Page,
    total as int)

Send a paged list response: {"items": [...], "offset", "limit", "total"}. items must already be a json.Value list (the page slice the handler built).

ctx
the request context
items
the page's items, as a JSON list
p
the page window
total
the total item count across all pages

unauthorized

jennifer
webapi.unauthorized(ctx as web.Context, message as string)

Send a 401 error envelope with a WWW-Authenticate: Bearer header.

ctx
the request context
message
the error message

validated

jennifer
webapi.validated(a as Api, ctx as web.Context)

Inside a handler: the request data the route's rules were checked against (query, then the body's top-level scalars for a JSON body or its fields for an application/x-www-form-urlencoded one; no other body is read). The guard already validated it, so a handler that got this far can trust it. Takes the Api because Jennifer has no per-request state to stash it in.

a
the built API
ctx
the request context
Returns map of string to string
the request data

wants

jennifer
webapi.wants(ctx as web.Context)

What the caller wants from the Accept header: "json" or "html", by content negotiation (see negotiate) between application/json and text/html. JSON wins a tie, and is the answer when the header is absent, * / *, or accepts neither type.

ctx
the request context
Returns string
"json" or "html"

Structs

Api

The built API description: its routes, mount points, and the authenticator / limiter func values. Value-semantic; every builder returns a fresh Api. The authenticator / limiter are entry-program func values, called through their home interpreter so they resolve their own imports and can construct a webapi.Identity across the module boundary.

jennifer
def struct Api {
    routes as list of RouteDef,
    mounts as list of Mount,
    authenticator as func,
    hasAuthenticator as bool,
    limiter as func,
    hasLimiter as bool,
    limitKey as func,
    hasLimitKey as bool,
    table as list of RouteEntry
};
routes
the registered routes
mounts
the version mount points
authenticator
func(token as string) -> Identity (only when hasAuthenticator)
hasAuthenticator
whether an authenticator is set (else every route is public)
limiter
func(key as string, limit as int) -> ratelimit.Result (only when hasLimiter)
hasLimiter
whether a rate limiter is set (else no limiting)
limitKey
func(ctx as web.Context) -> string, the key of an unauthenticated request (only when hasLimitKey)
hasLimitKey
whether a key function is set (else the client host, IPv6 by /64)
table
every mount and route pair, its full pattern split once, rebuilt by the builders that change routes or mounts

Decision

The outcome of evaluating a Spec against a request: proceed, or halt with the status + message (and any validation failures) to answer. The return of the pure webapi.evaluate.

jennifer
def struct Decision {
    proceed as bool,
    status as int,
    message as string,
    failures as list of validate.Failure
};
proceed
true if the request may run the handler
status
the HTTP status to answer when not proceeding
message
the error message to answer
failures
the field-level failures (validation only)

Identity

The result of authenticating a request. ok is false when the credential was absent or rejected; the other fields describe the caller when it is true.

jennifer
def struct Identity {
    ok as bool,
    subject as string,
    display as string,
    scopes as list of string
};
ok
whether the credential was accepted
subject
a stable identifier for the caller
display
a human-readable label
scopes
the permissions this caller holds

Mount

One version mount point. Exported only because Api.mounts exposes a list of them; programs build these through webapi.mount / alias, never directly.

jennifer
def struct Mount {
    version as int,
    path as string,
    sunset as string,
    since as string
};
version
the version label
path
the base path it serves under ("" = root)
sunset
the sunset date, sent as Sunset ("" = none)
since
the deprecation date, sent as Deprecation ("" = none)

Page

A page window parsed from a request's offset / limit query parameters by webapi.page.

jennifer
def struct Page {
    offset as int,
    limit as int
};
offset
the zero-based start index
limit
the page size

RouteDef

One registered route. Exported only because Api.routes exposes a list of them; programs build these through webapi.get / post / ..., never directly.

jennifer
def struct RouteDef {
    method as string,
    pattern as string,
    handler as func,
    feature as string,
    spec as Spec
};
method
the HTTP method
pattern
the un-prefixed route pattern
handler
the entry-program handler func value
feature
the discovery feature label (defaults to "METHOD /pattern")
spec
the route's specification

RouteEntry

One mount and route pair as the guard matches it: the route served under the mount, with the full pattern already split into segments. Exported only because Api.table holds a list of them; the builders keep it up to date.

jennifer
def struct RouteEntry {
    mount as int,
    route as int,
    method as string,
    segs as list of string
};
mount
the index into Api.mounts
route
the index into Api.routes
method
the route's HTTP method
segs
the mount path and the route pattern, as segments

Spec

The metadata attached to a route: what it needs and what it makes. A zero Spec (from webapi.public()) is an unauthenticated JSON route with no rules.

jennifer
def struct Spec {
    summary as string,
    auth as Auth,
    scopes as list of string,
    rules as map of string to list of validate.Rule,
    rateLimit as int,
    produces as Produces
};
summary
a one-line human description (used in discovery)
auth
the authentication requirement
scopes
the permissions the identity must hold
rules
per-field request validation
rateLimit
allowed requests per identity per window (0 = unlimited)
produces
the response content type policy

Enums

Auth

How a route authenticates. None is public (no credential); Bearer requires an Authorization: Bearer <token> the authenticator accepts.

Produces

What a route produces, driving content negotiation. Json always answers JSON, Html always HTML, Negotiate picks from the request's Accept.