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
| Name | What it is |
|---|---|
alias | Additionally serve version at the bare root, so /v1/deck is also reachable as /deck. |
authenticator | Set the authenticator: an entry-program func(token as string) -> webapi.Identity value. |
delete | Register a DELETE route with a Spec. |
denied | Send a 403 error envelope. |
deprecate | Mark every mount of version deprecated with a sunset date: the discovery document lists it, and every res... |
deprecatedSince | Mark every mount of version deprecated as of since: the discovery document lists it, and every response... |
discovery | Build the discovery document from the route table, so the advertised versions and features cannot drift fro... |
evaluate | The pure core: decide whether a request bearing identity and data may proceed under spec, without tou... |
fail | Send the uniform error envelope {"error": message} at status. |
failWith | Send the error envelope with field-level failures detail:... |
feature | Set an explicit discovery feature label for the most recently added route (defaults to "METHOD /pattern"), ... |
formData | The form body (application/x-www-form-urlencoded) as a string map. |
get | Register a GET route with a Spec. |
guard | The Spec-enforcing guard. |
identity | Inside a handler: the authenticated identity for this request - the one the guard computed, kept on the req... |
install | Register every route on the web.App, once per mount path (via web.mount), with the guard as its web h... |
jsonData | The named top-level JSON body fields, flattened to strings (a nested or array-valued field is omitted; read... |
limitKey | Set how an unauthenticated request is keyed for rate limiting: an entry-program... |
limiter | Set the rate limiter: an entry-program func(key as string, limit as int) -> ratelimit.Result value - usua... |
mount | Serve this version's routes under path, returning a new Api. |
negotiate | Pick the media type the caller prefers from those the handler can send, by the request's Accept header (R... |
new | A fresh, empty API builder. |
notFound | Send a 404 error envelope. |
onError | Register a web.onError hook on app (it is web.onError). |
page | Parse the offset / limit query parameters into a Page. |
patch | Register a PATCH route with a Spec. |
post | Register a POST route with a Spec. |
public | A zero Spec: a public JSON route with no scopes, rules, or rate limit. |
put | Register a PUT route with a Spec. |
queryData | The named query parameters as a string map (absent names omitted). |
sendJson | Send an envelope-consistent JSON response. |
sendPage | Send a paged list response: {"items": [...], "offset", "limit", "total"}. |
unauthorized | Send a 401 error envelope with a WWW-Authenticate: Bearer header. |
validated | Inside a handler: the request data the route's rules were checked against (query, then the body's top-level... |
wants | What the caller wants from the Accept header: "json" or "html", by content negotiation (see... |
Api | struct: The built API description: its routes, mount points, and the authenticator / limiter func values. |
Decision | struct: The outcome of evaluating a Spec against a request: proceed, or halt with the status + message (and any v... |
Identity | struct: The result of authenticating a request. |
Mount | struct: One version mount point. |
Page | struct: A page window parsed from a request's offset / limit query parameters by webapi.page. |
RouteDef | struct: One registered route. |
RouteEntry | struct: One mount and route pair as the guard matches it: the route served under the mount, with the full pattern a... |
Spec | struct: The metadata attached to a route: what it needs and what it makes. |
Auth | enum: How a route authenticates. |
Produces | enum: What a route produces, driving content negotiation. |
Functions
alias
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
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
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
webapi.denied(ctx as web.Context, message as string)Send a 403 error envelope.
ctx- the request context
message- the error message
deprecate
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
deprecatedSincedate
deprecatedSince
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
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
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
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
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
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
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
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 (
:paramcaptures allowed) handler- the entry-program handler func value
spec- the route's specification
- Returns
Api - a new Api with the route added
guard
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
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
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
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
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
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
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
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
webapi.new()A fresh, empty API builder.
- Returns
Api - an API with no routes, mounts, or auth
notFound
webapi.notFound(ctx as web.Context, message as string)Send a 404 error envelope.
ctx- the request context
message- the error message
onError
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
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
limitoroffset
patch
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
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
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
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
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
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
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
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
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
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.
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
authenticatorfunc(token as string) -> Identity(only when hasAuthenticator)hasAuthenticator- whether an authenticator is set (else every route is public)
limiterfunc(key as string, limit as int) -> ratelimit.Result(only when hasLimiter)hasLimiter- whether a rate limiter is set (else no limiting)
limitKeyfunc(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.
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.
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.
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.
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.
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.
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.
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.