HTTP API
Programs talk to Marginalia over /api/v1: JSON over HTTP with a bearer key. There is no other API; the UI calls the services
directly (see Architecture). The API runs the same commands the command bar and the agents
run, and a few administration calls: the version, the update of the installation and the
extensions.
Keys
A key belongs to a user and acts as that user: ApiKey (table api_keys, migration V31), an ExtendableEntity owned by the
user. Users create and revoke their keys in Settings → API keys (ApiKeysView); a user may have keys when they are an
administrator or have the permission API (PermissionType.API). The key is mrg_<prefix>_<secret> (12 characters a-z0-9, then
32 random bytes in base64url). ApiKeyService.create gives it once (CreatedKey.token); the database keeps only the prefix (to
find the key) and a SHA-256 of the whole key (the key has 256 random bits, a slow hash would add nothing). A revoked key is soft
deleted; the cleanup purges the keys with their user.
ApiKeyService.authenticate(token) (needs no current user) gives the Principal (key, user, access) or null: unknown, deleted,
expired, the user deleted, or the user neither an administrator nor holding the API permission any more. It writes lastUsed at
most once a minute.
What a key may do is a set of ApiScopes, any combination and at least one (stored by name in the extended attribute
ApiKey.scopes); every key may call /version and /me:
UPDATE and EXTENSIONS are administration scopes (isAdministration()): only an administrator gives them, and authenticate
drops them while the owner is not an administrator (the key keeps its other scopes). The services check AdminGuard again (from the
database) on every call. A deploy key can so be EXTENSIONS alone, or UPDATE + EXTENSIONS without access to any book.
The request context
The services take the current user from the session scoped user and sessionPoint beans. A call of the API has no browser and
gets no container session: ApiDispatcher makes an ApiRequestAttributes (a DetachedRequestAttributes, the base the
AgentRequestAttributes of agent runs share) with a copy of the user and an AgenticSessionPoint that holds the book of the call,
and runs the call inside it (InRequestScope). ThreadCopyRequestAttributes.create() hands a detached context on as it is, so an
async command started by the call sees the same user on its worker thread; the context is closed when the call answers, or for a
run when the command ends. Even the key is checked inside a detached context (with an empty user), so nothing a service touches can
open a container session. The language of the call is the user's (UserSetting).
ApiServlet (mapped to /api/* in WebappApplicationInitializer, before the /* of Vaadin) only reads the request: the body up
to 16 MB (256 MB for an extension JAR), the query string by hand (getParameterMap() would read a form body), and gives an
ApiRequest to the ApiDispatcher bean. The dispatcher returns an ApiResponse; the tests (ApiDispatcherTest) call it without
HTTP.
Calls
Every call needs Authorization: Bearer <key>; without a valid key the answer is 401. Errors are {"error": "..."} with
400 (bad arguments, bad JSON), 403 (a scope the key does not have, a service that refused), 404, 409 (a state that does not allow
it), 413 (too large), 422 (a command that reported an error, an extension that does not fit), 429 (too many runs), 500,
503 (no extensions in this process).
The body of a command call is a JSON object, every field optional:
{"arguments": {"name": "value"}, "confirm": false, "wait": 30}
arguments is an object (by name, CommandService.execute) or an array (by position, executePositional); a number, a text, a
boolean or null is passed as it is, an object or an array as its JSON text. confirm answers every question the command asks
(CommandScope.confirm; nobody can be asked, so no is the default). wait is how many seconds (0 to 300) the call waits for the
command: done in time, the answer is 200 with {"status": "done", "result": ...} (the result is the text the command returns),
{"status": "failed", "error": ...} with 400/403/422/500, or 409 cancelled; otherwise 202 with
{"status": "running", "run": "<id>", "progress": ...}, and the run is asked for by GET /runs/<id>. Runs are kept in memory (an
hour after they end, lost at a restart), at most 16 running per user.
The API page and the OpenAPI description
ApiDocs describes the API for people. Three things need no key (ApiDispatcher.handle answers them before the key is checked):
-
GET /api/v1/is the page (src/main/resources/api-docs/index.html;/api/v1without the slash redirects to it, so its files resolve next to it). It is Swagger UI from theorg.webjars:swagger-uiwebjar, served byApiDocs.pagefrom/api/v1/docs/<file>: only the files the page uses (swagger-ui-bundle.js,swagger-ui.css, the favicons) and the page's ownapi-docs.js/api-docs.css, everything else is404. No CDN: the desktop application may be offline. -
GET /api/v1/openapi.jsonwithout anAuthorizationheader is the OpenAPI 3.1 document of the fixed calls (ApiDocs.ROUTES). -
With a key,
openapi.jsongoes through the usual check (a wrong key is401) and also has aPOST /books/{book}/commands/<name>for every command the key may run (ApiDispatcher.runnable, the same rule asGET /commands), its arguments a JSON schema per form (typeSchema: integer, number, boolean, string, an enum's names;allowed,min,max, the default and whether it is optional), the texts in the language of the key's user.
The page's script keeps the key in a variable (never localStorage; persistAuthorization is off), fetches openapi.json with it,
points the server of the document at the page's own URL (a context path works) and adds the key to every call of Try it out
(requestInterceptor) unless the Authorize button of Swagger UI gave one. The validator badge is off (validatorUrl: null), so
the page calls nothing but this server.
ROUTES is the list of the calls; ApiDocsTest reads the call.is(...) of ApiDispatcher and fails when the two differ, so a
new call is documented when it is added. A call's description says its scope and whether it changes the server.
Plugins without a full update
/version gives the commit the server runs, so a client can tell whether plugins built from a checkout fit it:
tools/marginalia_api.py can-hot-install runs git diff <running commit> HEAD -- marginalia/src/main marginalia/pom.xml pom.xml;
when nothing changed (and nothing of it is uncommitted), plugins built from HEAD can be installed with
tools/marginalia_api.py install --plugins (the same check first, then a PUT per JAR). Otherwise the application needs a full
update (POST /admin/update or the Update tab). Whatever the client says, installPackage verifies every JAR against the running
application (see Extendable) and rolls back one that does not fit.
export MARGINALIA_URL=https://marginalia.example.org
export MARGINALIA_API_KEY_FILE=~/.marginalia-api-key
python3 tools/marginalia_api.py version
python3 tools/marginalia_api.py can-hot-install && python3 tools/marginalia_api.py install --plugins
python3 tools/marginalia_api.py run get-book-info --book <uuid>
The client reads the key from the environment or a file, never from the command line.