Authoring interactive pages via the public REST API (api-key)
Audience: anyone building a MeroFoundry app against the public REST API with an
X-API-Key (no admin session).
What this answers: “Does the platform cover simple client-side state (click a button, a hidden div appears) and does it cover AJAX so my app behaves like a SPA?”
Both, yes. A Reveal answer button that reloads the whole page (a full postback) is an authoring choice, not a platform limit. This doc shows the block JSON that avoids it and the exact REST calls to ship it.
1. The mental model (read this first)
Section titled “1. The mental model (read this first)”A published MeroFoundry app is server-rendered and then hydrated by SvelteKit.
- The backend does not emit HTML or JavaScript for your page. The render endpoint returns a
static JSON tree of blocks (
layout,style,customCss,params) — no scripts, no event handlers. - The published route is server-rendered and then hydrated by SvelteKit. For same-application
path changes, the browser uses the render endpoint to fetch the JSON tree (
layout,style,customCss,params) as a client-side navigation. Toggles, form submits, and data fetches happen client-side, with no full-page reload. - Behaviour fields (
on_click,show_when, formsource, data bindings) are opaque data the client interprets. You author interactivity by choosing the right blocks — you don’t “enable” it.
The API’s job is to store the layout JSON (and your models/records). The layout is
passthrough (dict[str, Any]) and not schema-validated — a typo in a block field fails silently
at render rather than erroring on save. The renderer is the source of truth; to check a shape you’re
unsure of, read back a page built in the UI with GET …/pages/{page_id}.
The root layout is an object with a blocks array, and every block nests its children under
blocks too (never children):
{ "blocks": [ { "id": "h", "type": "heading", "content": { "text": "Hello" } } ] }2. Auth, base URL, and what an api-key can do
Section titled “2. Auth, base URL, and what an api-key can do”Base URL and header
Section titled “Base URL and header”Base: https://<your-app-host>/api/v1/publicHeader: X-API-Key: mf_<marker>_<token> # on every requestEverything is scoped under an application:
/api/v1/public/applications/{application_id}/....
The capability gate
Section titled “The capability gate”The public API is gated by the public_api capability on the application. If it’s off you’ll get a
capability_disabled error whose message tells you the fix. Enable it once (needs a key with
applications:update — see tiers below):
BASE="https://app.example.com/api/v1/public"APP="00000000-0000-0000-0000-000000000000" # your application_idKEY="mf_live_REPLACE_ME"
curl -sS -X PATCH "$BASE/applications/$APP" \ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ -d '{ "capabilities": { "public_api": "enabled" } }'The one hard limit of api-key auth — know it up front
Section titled “The one hard limit of api-key auth — know it up front”You cannot mint an api-key with an api-key. POST /applications/{id}/api-keys is
admin/session-only. Create keys in the admin UI/API, then use them here.
Composite definitions are authorable with an api-key
Section titled “Composite definitions are authorable with an api-key”A reusable, parameterised composite definition ({"parameters": [...], "body": <block>},
instantiated by a page’s composite block) has its own public CRUD resource. It is a page-layout
artifact, so it is gated on the existing pages:* permissions — there is no separate
composites permission family:
| Operation | Route | Key permission |
|---|---|---|
| List | GET /applications/{application_id}/composites |
pages:read |
| Create | POST /applications/{application_id}/composites |
pages:create |
| Read one | GET /applications/{application_id}/composites/{composite_id} |
pages:read |
| Update | PATCH /applications/{application_id}/composites/{composite_id} |
pages:update |
| Delete | DELETE /applications/{application_id}/composites/{composite_id} |
pages:delete |
Every route runs the same public-API gate as pages: a valid X-API-Key, a key issued for this
application_id in the application’s tenant and workspace (otherwise 403 api_key_scope_mismatch), an active tenant, the public_api capability enabled, the key holding
the operation’s permission (otherwise 403 api_key_permission_denied), and the per-key rate
limit. The id-bearing routes also confirm the composite belongs to that application and answer
404 when it does not. Create additionally needs a key that records its creator (otherwise
403 api_key_creator_required). Request bodies are camelCase (styleId).
You still do not need a definition for interactivity: author the composite_scope block
directly in the page layout (see §3b). Use a definition for a named, reusable,
parameterised component shared across pages.
Permission tiers (what your key needs)
Section titled “Permission tiers (what your key needs)”| Tier | Includes | You need it for |
|---|---|---|
| data | records:*, models:read, app:read, files:* |
reading/writing records (the AJAX/data story) |
| authoring | pages:*, forms:*, models:create/update/…, fields:*, applications:update |
creating/updating pages and the schema |
| control | risky:outbound_destinations:configure |
outbound governance |
System roles map to these: data-reader, data-writer, schema-author. To author pages you
need an authoring-tier key (e.g. schema-author); to just read/write records a data-tier key is
enough. Also: creating a page requires the api-key to have a creator user on record, else you
get api_key_creator_required (403).
3. Client-side state: hide/show without a reload
Section titled “3. Client-side state: hide/show without a reload”The block JSON below is identical whether you POST it via REST or author it in the UI. Two levels — use the simplest that fits.
3a. Native interactive blocks (simplest)
Section titled “3a. Native interactive blocks (simplest)”collapsible, accordion, tabs show/hide their own content entirely client-side. A flash-card
Reveal answer is a one-block collapsible:
{ "id": "card-1", "type": "collapsible", "content": { "title": "What is the capital of France?", "content": "Paris" } }Clicking the title reveals content.content — no reload, no request. Richer body → put child
blocks under blocks (they render in the expanded region; the trigger is always content.title).
accordion—content.items=[{ "title", "content" }];display.type="single"|"multiple".tabs—content.items=[{ "label", "content" }];display.defaultTab="tab-1"(values aretab-<n>by position).
For a plain flash card, collapsible is the whole answer.
3b. General local state: composite_scope + set_field + show_when
Section titled “3b. General local state: composite_scope + set_field + show_when”Use when native blocks don’t fit — one button revealing several scattered blocks, state other blocks read, a swapped label. Three pieces:
- A
composite_scopeblock holds reactive state; initial values incontent.local_init; exposed to descendants under the namelocal. - A
buttonwithon_clickwrites state. Only directive:set_field; alocal.name writes into the scope. No network call. - Any block gated by
display.show_whenwith anexpr:againstlocal.
{ "id": "scope-1", "type": "composite_scope", "content": { "local_init": { "revealed": false } }, "blocks": [ { "id": "q", "type": "heading", "content": { "text": "Capital of France?" } },
{ "id": "reveal", "type": "button", "content": { "label": "Reveal answer" }, "display": { "show_when": "expr:!local.revealed" }, "on_click": [ { "set_field": { "name": "local.revealed", "value": true } } ] },
{ "id": "a", "type": "heading", "content": { "text": "Paris" }, "display": { "show_when": "expr:local.revealed" } } ] }Clicking Reveal answer flips local.revealed in the browser; the answer un-hides and the button
hides itself. All client-side, no reload.
show_when grammar (display.show_when):
| Value | Meaning |
|---|---|
omitted / "always" |
always shown |
"authenticated" / "unauthenticated" |
gated on login state |
"expr:local.revealed" |
shown when path is truthy |
"expr:!local.revealed" |
shown when path is falsy |
"expr:local.a == local.b" |
shown when the two paths are equal |
"expr:local.a != local.b" |
shown when they differ |
"expr:item.status == \"approved\"" |
compare with a quoted literal |
"expr:item.rank < 3" |
compare numeric values or numeric strings |
"expr:count(query.rows) > 0" |
show when an array has items |
"expr:(local.a && local.b)" |
group expressions explicitly |
Terms combine with && (shown when both terms hold) and || (shown when either term holds):
expr:(local.a || local.b) && local.cexpr:local.a && local.bexpr:local.a || local.bexpr:local.a || local.b && local.cEach side of && and || is one of the expr: forms in the table. && binds tighter than ||,
so the last line means local.a || (local.b && local.c). Parentheses can override this grouping. == and != compare primitive
values as strings, so a projected true or 3 equals the URL value "true" or "3"; an absent or
null operand only equals another absent or null operand. Either operand may be a whole
{{time.<path>}} token. Quoted strings, numbers, true, false and null are literals.
Ordering supports <, <=, > and >=: numeric operands compare numerically, other strings
lexically; absent values do not order. count(path) returns an array length or zero for a
non-array value. Other function calls are refused.
Bare words remain paths:
expr:item.status == approvedlooks upapproved. Useexpr:item.status == "approved"for a literal comparison. Falsy values are"",null,undefined,false,0, and the exact strings"false"and"0".
set_field targets: local.<key> writes scope state; any other name writes an enclosing form’s
field; with no form it’s silently dropped. set_field is the only click directive today.
4. AJAX / SPA behaviour: data without a reload
Section titled “4. AJAX / SPA behaviour: data without a reload”4a. Forms submit via fetch, not POST-and-redirect
Section titled “4a. Forms submit via fetch, not POST-and-redirect”A form block submits with fetch and updates the page in place. Config under source:
source field |
Meaning |
|---|---|
target_mode |
"create" (default), "edit" (PATCH), "delete", "login", "logout" |
model_id / record_id |
target model / record |
defaults |
initial field values |
on_success_toast |
toast text |
on_success_set_field |
[{ "name", "value" }] — writes state after success (local.* or fields) |
on_success_redirect |
optional href; navigates only if set (shallow for ?/#) |
On success the record enters the client cache, the toast shows, state writes run, and the page does
not reload unless on_success_redirect is set. Input blocks bind fields via binding.field:
{ "id": "add", "type": "form", "source": { "target_mode": "create", "model_id": "<model_id>", "on_success_toast": "Saved" }, "blocks": [ { "id": "in-q", "type": "input", "content": { "label": "Question" }, "binding": { "field": "question", "save_mode": "submit" } }, { "id": "go", "type": "button", "content": { "label": "Add" }, "display": { "type": "submit" } } ] }4b. Data blocks fetch on the client
Section titled “4b. Data blocks fetch on the client”record-list, data-table, stat, chart fetch their own data client-side and re-render when
records change (a form create/edit/delete updates them without navigation). Config under source:
{ "id": "cards", "type": "record-list", "source": { "model_id": "<model_id>", "page_size": 25, "sort": "created_at", "order": "desc" }, "content": { "title": "All cards", "columns": "question,answer" } }Repeat any block over data with binding.repeat_over (item_var defaults to item):
{ "id": "card", "type": "collapsible", "binding": { "repeat_over": { "source": "model", "model_id": "<model_id>" }, "item_var": "item" }, "content": { "title": "{{ item.question }}", "content": "{{ item.answer }}" } }One client-side collapsible per record — a full deck, reveal-on-click, zero reloads.
Same-tab updates versus live: true
Section titled “Same-tab updates versus live: true”Without live, these blocks update without refreshing only for changes made in the same tab:
a form create, edit or delete on the page re-renders them. Changes made by another viewer,
another browser tab, or an agent (an API-key client, an MCP tool, an automation) appear only after a
reload.
Add "live": true to a block’s model source, or to a "source": "model" binding.repeat_over,
and the published page will update without refreshing when anyone changes that model: other
viewers, other tabs and agents. Each change re-reads the block’s own query, keeping its filters,
sort, page size and aggregation.
{ "id": "tasks", "type": "record-list", "source": { "model_id": "<tasks model_id>", "page_size": 25, "sort": "created_at", "order": "desc", "live": true }, "content": { "title": "Tasks", "columns": "title,status" } }{ "id": "open-tasks", "type": "stat", "content": { "label": "Open tasks" }, "source": { "model_id": "<tasks model_id>", "aggregation": "count", "filters": { "status": "open" }, "live": true } }{ "id": "task", "type": "collapsible", "binding": { "repeat_over": { "source": "model", "model_id": "<tasks model_id>", "filter": { "status": "open" }, "live": true }, "item_var": "task" }, "content": { "title": "{{ task.title }}", "content": "{{ task.notes }}" } }liveis opt-in and must be a JSON boolean ("true"or1is rejected on save). Absent orfalseopens no connection.- It applies to
record-list,data-table,stat,chartanddnd-listwith amodel_idsource, and to a modelbinding.repeat_over. Saved-query, literal and page-parameter sources ignore it. - Every live block on a page that reads one model shares a single connection.
- Only published pages subscribe; the editor canvas and the admin preview never do.
- If the connection drops or is refused, the blocks keep their last data, show no error and reconnect with backoff.
- Anonymous-read rule: live updates follow the read access the page already has and never widen it. An anonymous visitor receives them only for a model whose anonymous READ access covers the whole model, and an anonymous subscription carries no field filters; a signed-in viewer of the application receives them for the rows they may read. A viewer who cannot read the model gets no updates. No record data travels over the connection: every update is a re-read through the normal governed endpoint.
A published record-list labels its columns with the model’s field labels, falling back to the
field name when a field has no label.
Parameterized saved-query bindings. A saved query whose AST references runtime inputs (a
":status" placeholder in a where/having rule value, or a structured JOIN reference
{"parameter": "team_id"}) is bound with one params mapping on the binding definition. The same
key is used on a block source (record_list, data-table, stat, chart) and on a container’s
binding.repeat_over:
{ "id": "open-tasks", "type": "record_list", "source": { "source": "saved_query", "saved_query_id": "<id>", "params": { "status": "{{query.status}}", "team_id": "{{params.record_id}}" } } }- Values. Each value is a string, number or boolean. A value that is exactly one
{{<namespace>.<path>}}token keeps the referenced value; a token inside other text is substituted as text ("s-{{query.tab}}"); anything else is a literal ("closed",5,true). Each binding resolves its own values, so two bindings of one saved query on the same page return independently filtered rows. - Namespaces.
params.*is the page’s route parameters (for exampleparams.record_idon a<page>/<record-id>path) andquery.*is the URL query string. They are never merged: a route parameter does not stand in for a missing URL query value or the other way round. Inside a repeat,{{<item_var>.<field>}}reads the enclosing row. - Unresolved values. If any referenced value is missing, the binding is unresolved: it is not executed, and it is not treated as an empty result.
- Required inputs are derived, not declared. Every parameter the saved query’s AST references
(where/having placeholders, including nested groups, and JOIN
{"parameter": ...}references) must be a key inparams. There is no separate required/optional parameter list. Page create and update reject a layout whose saved-query bindings, at any nesting depth (including a container’s empty branch), miss a required input, with a422naming the block and the parameter. - Server-bound identity.
current_user_id(and the temporalnow/timezone) are bound by the server and are never required.current_user_idcomes only from the validated consumer session; a binding that suppliescurrent_user_idis rejected on create and update, and refused at render. - Saved-query edits. Updating a saved query’s AST is rejected (
422, naming the page) when a page that already binds the query would no longer supply every required input. A compatible change is accepted. - Stored definitions. A binding stored before this validation, or written around it, that misses
a required input fails explicitly: the server render leaves the binding unresolved and logs
page_render.saved_query_binding.failed, and browser execution gets400 Missing query parameter. It never runs unbound and never reads as an empty result. - Authorization is unchanged. Values only fill parameters. The saved query must still be public and belong to the page’s application, and identity-scoped rows still depend on the validated session.
Empty result for a query-bound container. A container whose binding.repeat_over is a saved
query may add binding.empty, a list of blocks rendered once, in place of the repeated container,
after the query succeeds with zero rows. Use the empty block for the message:
{ "id": "task-rows", "type": "container", "binding": { "repeat_over": { "source": "saved_query", "saved_query_id": "<id>", "params": { "status": "{{query.status}}" } }, "item_var": "task", "empty": [ { "id": "no-tasks", "type": "empty", "content": { "title": "No matching tasks", "description": "Try another status" } } ] }, "blocks": [ { "id": "row", "type": "text", "content": { "text": "{{task.name}}" } } ] }The empty branch is not shown while the query is loading, after a failed execution, or while the
binding’s params are unresolved. A result with one or more rows renders the rows only.
4c. Navigation that doesn’t reload
Section titled “4c. Navigation that doesn’t reload”content.href starting with ? or # is routed shallowly (invalidateAll:false) — no
reload. An href that changes the path within the same application is client-side navigation;
use ? or # when the current page data should not reload.
5. The REST calls, end to end
Section titled “5. The REST calls, end to end”5a. Pages
Section titled “5a. Pages”Layout goes in the layout field. status transitions draft → published. When you change
status, resend layout so the tree is preserved.
# Create a page (authoring-tier key). Body accepts snake_case or camelCase (isHome / is_home).curl -sS -X POST "$BASE/applications/$APP/pages" \ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ -d '{ "name": "Home", "slug": "home", "title": "Study deck", "type": "custom", "isHome": true, "status": "draft", "layout": { "blocks": [ { "id":"t","type":"heading","content":{"text":"Study deck"} }, { "id":"deck","type":"collapsible", "binding":{ "repeat_over":{ "source":"model","model_id":"MODEL_ID" }, "item_var":"item" }, "content":{ "title":"{{ item.question }}", "content":"{{ item.answer }}" } } ] } }'# -> 201 { "id": "PAGE_ID", "slug": "home", "layout": {...}, "status": "draft", ... }
# Publish (resend layout)curl -sS -X PATCH "$BASE/applications/$APP/pages/PAGE_ID" \ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ -d '{ "status": "published", "layout": { "blocks": [ /* same tree */ ] } }'
# See what the renderer emits (composites expanded, bindings/style resolved). POST, any status:curl -sS -X POST "$BASE/applications/$APP/pages/PAGE_ID/render" -H "X-API-Key: $KEY"# Published-only variant (GET; requires app + page published):curl -sS "$BASE/applications/$APP/pages/PAGE_ID/published" -H "X-API-Key: $KEY"Page endpoints (all under $BASE/applications/$APP): POST /pages, GET /pages,
GET /pages/{id}, PATCH /pages/{id}, DELETE /pages/{id}, POST /pages/{id}/render,
GET /pages/{id}/published.
5a.i Visual verification through the hosted MCP
Section titled “5a.i Visual verification through the hosted MCP”An API-key authoring response and the published-page render endpoint do not provide browser pixels. After you create/populate, style/publish, and discover the public URL, use the hosted MCP’s published-site capture tools when they are available, inspect the evidence, repair, and recapture.
a successful authoring API response is not visual evidence
screenshots do not replace keyboard, accessibility, form-submission, or navigation tests
# Home, one page by ID, and one page by normalized application-relative path.capture_page_screenshot(application_id=APP)capture_page_screenshot(application_id=APP, page_id=PAGE_ID)capture_page_screenshot(application_id=APP, path="/catalog")
# The only initial caller-selected viewport names are desktop and mobile.capture_page_screenshot(application_id=APP, viewport="desktop", full_page=True)capture_page_screenshot(application_id=APP, viewport="mobile", full_page=True)
# Whole published site; max_pages can lower but cannot raise server bounds.capture_site_screenshots(application_id=APP)capture_site_screenshots(application_id=APP, viewport="desktop", max_pages=3)capture_site_screenshots(application_id=APP, viewport="mobile", max_pages=3)Inspect every returned site-manifest entry. Its CaptureDisposition is success, failed, or
omitted; mixed values are a partial site result. Fix and retry failed pages. An omitted page was
not attempted because of a server-owned whole-job bound; make another permitted capture if it
still needs evidence. Full-resolution artifact links are opaque, private, and short-lived; after
one expires, recapture instead of using it as a durable public URL.
Act on the five DiagnosticCounts fields: blank output or absent styling calls for checking
console_errors and page_errors; missing images and unloaded-image counts call for correcting
sources or trusted origins indicated by unloaded_images; console failures use console_errors;
blocked resources use blocked_requests and must be replaced with allowed resources; unavailable
requests use failed_requests. After each repair, capture again.
5b. Models and fields (schema for the data story)
Section titled “5b. Models and fields (schema for the data story)”Records require a published model. Standard CRUD under $BASE/applications/$APP/models and
.../models/{model_id}/fields (authoring-tier). Or build the schema in the UI and just write
records with a data-tier key.
5c. Records — the SPA data surface
Section titled “5c. Records — the SPA data surface”Bodies wrap fields in a data object. Nested under the model:
MODEL="11111111-1111-1111-1111-111111111111"
# Create (Idempotency-Key makes retries safe)curl -sS -X POST "$BASE/applications/$APP/models/$MODEL/records" \ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: seed-1" \ -d '{ "data": { "question": "Capital of France?", "answer": "Paris" } }'# -> 201 { "id": "REC", "data": {...}, "createdAt": ... }
# List (paged; filters/sort as query params)curl -sS "$BASE/applications/$APP/models/$MODEL/records?page=1&per_page=25&sort=created_at&order=desc" \ -H "X-API-Key: $KEY"# -> { "items":[...], "total":N, "page":1, "perPage":25 }
# Update / deletecurl -sS -X PATCH "$BASE/applications/$APP/models/$MODEL/records/REC" \ -H "X-API-Key: $KEY" -H "Content-Type: application/json" \ -d '{ "data": { "answer": "Paris (France)" } }'curl -sS -X DELETE "$BASE/applications/$APP/models/$MODEL/records/REC" -H "X-API-Key: $KEY" # 204Record endpoints: POST|GET .../records, GET|PATCH|DELETE .../records/{id}, and
POST .../records/search (vector similarity: { "field", "vector":[…], "top_k" }). List query
params: page, per_page (≤100), sort, order, resolve_references, ids= (comma-sep), plus
per-field filters. Only published, public-API fields are returned.
6. Why your Reveal answer button reloaded
Section titled “6. Why your Reveal answer button reloaded”A full postback means the button was authored as a path-navigating link — content.href
pointing at a path/URL — which the browser follows as a real navigation, re-running the loader and
repainting. It was not using a no-reload path: no on_click: set_field, no composite_scope +
show_when: "expr:local.*", and not a collapsible/accordion/tabs. Fix: §3a or §3b.
7. Quick reference
Section titled “7. Quick reference”| I want… | Author this |
|---|---|
| Click to reveal one hidden answer | collapsible (§3a) |
| One expandable section among several | accordion (§3a) |
| Switch between panes | tabs (§3a) |
| Button that reveals/toggles arbitrary blocks | composite_scope + button on_click set_field + show_when (§3b) |
| Submit data, stay on page | form, no on_success_redirect (§4a) |
| List/table/metric that updates after this tab’s form submits | record-list / data-table / stat / chart (§4b) |
| One card per record | any block + binding.repeat_over (§4b) |
| Update without refreshing when other viewers or agents change data | "live": true on the model source or binding.repeat_over (§4b) |
| Navigate without a reload | href starting with ? or # (§4c) |
Can’t do with just an api-key: mint api-keys (admin/session-only).
Can do: list, create, read, update and delete composite definitions through
/applications/{application_id}/composites with pages:read / pages:create /
pages:update / pages:delete (§2). Local state still goes inline as composite_scope.
Sibling doc: the same patterns via the MCP tools —
docs/authoring-interactive-pages-mcp.md.
