# 10. REST API reference

Every route is under `/wp-json/jikji/v1` (or `/?rest_route=/jikji/v1/…` without permalinks). Request bodies are JSON. The route list below was taken from a running site (`rest_get_server()->get_routes('jikji/v1')`); `?` marks optional arguments with their defaults.

## 10.1 Authentication and permissions

- Authenticate like any WordPress REST client: an **application password** (`curl -u "user:xxxx xxxx xxxx xxxx xxxx xxxx"`), or a logged-in cookie session with the `X-WP-Nonce` header (what the editor uses).
- Check the site first: `wp eval 'var_dump( wp_is_application_passwords_available() );'` must be `true` (security plugins such as Wordfence can switch application passwords off — a site owner's decision), the `Authorization` header must reach PHP (`GET /wp-json/wp/v2/users/me?context=edit` returning 200 proves it), and a firewall that filters by User-Agent needs the agreed value.
- **Permission** on every editing, rendering and evaluating route is `jikji_compile` **plus** `edit_post` on the document (templates and parts: `edit_theme_options`). Listing routes need `jikji_compile`; the exceptions are noted per route. Failures are `401`/`403 jikji_forbidden`.
- Errors are WordPress REST errors: `{"code": "jikji_…", "message": "…", "data": {"status": 4xx, …}}`. Codes are listed in [10.9](#109-error-codes).

A minimal client:

```bash
SITE=https://example.com
AUTH="$WP_USER:$WP_APP_PASSWORD"
api() { # api METHOD PATH [JSON-FILE]
  curl -sS -u "$AUTH" -X "$1" "$SITE/wp-json$2" -H 'Content-Type: application/json' ${3:+--data-binary @"$3"}
}
```

## 10.2 Documents

| Route | Arguments | Response |
|---|---|---|
| `GET /content/{id}` | — | `{html, hash, idStyles, classStyles, postStatus, compileError}` — `hash` is the version used for locking |
| `POST /content/{id}` | `html` (required), `baseHash?=""`, `styles?=[]` (`[{name, type: "I"\|"C", css, baseCss?}]`), `existingClasses?="overwrite"\|"refuse"`, `strictCss?=false`, `aiSummary?=""` | `{hash, compiled, warnings, cssDropped, revision}`. Validates, sanitizes SVG, checks the compiled PHP syntax, maps styles, records a revision; compiles when the document is published. `existingClasses: "refuse"` rejects a class that already exists and was sent without `baseCss` (`409 jikji_class_exists`); `strictCss` refuses the save when any CSS would be dropped (`400 jikji_css_dropped`) |
| `POST /content/validate` | `html` (required), `styles?=[]`, `strictCss?=false` | `{valid, warnings, html, cssDropped, blockWarnings}` — the save's checks without writing; the same `400`s as a save. Permission: `jikji_compile` |
| `POST /content/{id}/import` | `dry_run?=true` | `{html, report, counts}`; with `dry_run: false` the result is also saved and the response carries `saved` — the **save result object** `{hash, compiled, warnings, cssDropped, revision}` (read the next lock token from `saved.hash`; `saved` is never a plain `true`). `post_content` is never changed. `jikji_nothing_to_import` for an empty post, `jikji_import_unsafe` when the compiled result does not pass the count check |
| `GET /content/{id}/revisions` | — | `{revisions: [{id, date, author, kind, …}]}` newest first |
| `GET /content/{id}/revisions/{rev}` | — | The revision with `html` and the style snapshot (`styles.ids`, class copies) |
| `POST /content/{id}/revisions/{rev}/restore` | `baseHash?=""` | A new save of the revision's HTML and ID styles (ID rows the snapshot does not define are removed unless another document uses them); class styles are not restored. Honours the lock |
| `POST /elements/ids` | `count?=10` (1–50) | `{ids: ["jk-…", …]}` unused IDs. Permission: `jikji_compile` |
| `GET /styles` | — | `{classStyles: [{name, type, css}]}` every global class. Permission: `jikji_compile` |
| `GET /shortcodes` | — | `{tags: [...]}` registered shortcode tags, sorted. Permission: `jikji_compile` |
| `GET /blocks` | `search?=""`, `attrs_only?=""\|"yes"\|"no"\|"unknown"` | `[{name, title, category, dynamic, attrsOnly, attributes}]` registered Gutenberg blocks. Permission: `jikji_compile` |

## 10.3 Rendering and evaluation

These run template code, so they require `jikji_compile` plus `edit_post` on `post_id` (the document that gives the context).

| Route | Arguments | Response |
|---|---|---|
| `POST /render/shortcode` | `post_id`, `shortcode` | `{html, warnings}` — `do_shortcode()` in the post's context, reduced to static HTML (scripts and handlers stripped). `422 jikji_shortcode_failed` on an exception |
| `POST /render/block` | `post_id`, `markup?=""` or `name?=""` + `attrs?={}`, `scope?=[]` | `{html, assets, context, warnings}` — one block rendered as the front end would, inside the given loop scope; `context.source` is `error` when a loop expression fails and `empty-loop` when it yields nothing |
| `POST /render/template-part` | `post_id`, `slug` | `{html, assets, …}` — a part rendered for the canvas; `400 jikji_invalid_part` for a bad slug |
| `POST /render/data` | `post_id`, `items` (≤ 200: `[{key, expr, mode: text\|html\|attr\|each\|if, attr?, scope?: [{each}]}]`) | `{results: {key: {value} \| {count, kind} \| {error} \| {skipped: true}}}` — expressions evaluated in the document's context (a template under its sample query), 5 s budget per request; resend skipped items. `400 jikji_too_many_items` |
| `GET /data/schema` | `post_id` | The data picker's schema for the document: post fields, meta, taxonomies, ACF/SCF fields; for a template the sample post's (or post types') schema plus `templateFields.site` and `.archive` |
| `POST /data/schema/context` | `post_id`, `scope` (`[{each: "…"}]`, outermost first) | The item kinds of the scope chain and the innermost context's schema. `jikji_invalid_scope` when a level is not a usable `j:each` |
| `GET /canvas/{id}/styles` | — | `{head, bodyClass}` — the theme's `<link>`/`<style>` tags and body classes for the document's front-end context (a template's sample query), used by the builder's canvas |

## 10.4 Templates, parts and patterns

Templates and parts require `jikji_compile` plus `edit_theme_options`; a pattern requires `jikji_compile` plus `edit_post` on the `wp_block` post.

| Route | Arguments | Response |
|---|---|---|
| `GET /templates` | — | `{blockTheme, theme, templates: [...], parts: [...], patterns: [...]}`. A template item: `{id: "<theme>//<slug>", wpId, type, slug, title, area, source: "theme"\|"custom", themeFileChanged, jikji: {managed, status, compiled, compileError, runtimeError}, editUrl, previewUrl, siteEditorUrl}`. A pattern item: `{id: "wp_block:<id>", wpId, type: "wp_block", slug, title, synced, jikji, editUrl, previewUrl, siteEditorUrl}` |
| `POST /templates/adopt` | `id` (`"<theme>//<slug>"`), `type?="wp_template"\|"wp_template_part"`, `import?=false` | The list item. Idempotent. A theme file becomes a customized post first. The first adoption also returns `import`: the conversion counts `{converted, island, skipped, warning}` (with `import: true`), `{error}` when it fell back to the skeleton, or `null` when the skeleton was asked for; a later call on a managed document has no `import` |
| `POST /templates/parts` | `title`, `slug?=""`, `area?="uncategorized"` (`header`, `footer`, `uncategorized`) | The new part's list item (`wpId`, `slug` suggested from the title) |
| `POST /templates/{id}/status` | `status` (`"publish"` or `"draft"`) | `{status, compileError}` — publish compiles first and keeps the old state on failure (`400 jikji_compile_failed`). Also for patterns |
| `POST /templates/{id}/sample` | `sample` (an object of `WP_Query` variables) | The stored sample and its `found` count |
| `GET /templates/{id}/samples` | — | `{current, found, candidates: [{label, vars}]}` — the stored sample, how many posts its main query finds, and the candidate samples (the template's default, Home, one per public post type, terms, search, 404) |
| `DELETE /templates/{id}/jikji` | — | Release: Jikji data and compiled output removed; the post and its blocks stay. Also for patterns |
| `GET /patterns` | — | `{patterns: [...]}` (items as above) — every pattern post with status `publish`, `draft` or `private`, **not** filtered per item by the caller's `read_post`. Permission: `jikji_compile` plus `edit_posts` (the per-item read check applies to `/site-editor/item` and the Site Editor data only) |
| `POST /patterns/{id}/adopt` | `import?=true` | The pattern item (+ `import` on the first adoption). Idempotent |
| `GET /site-editor/item` | `type` (`wp_template`, `wp_template_part`, `wp_block`), `id` (`"<theme>//<slug>"` or the pattern post ID) | `{item: {type, wpId, managed, published, synced, editUrl, builder} \| null}` — what the Site Editor script needs for a document made after its page loaded. Logged-in users with `edit_posts` (patterns) or `edit_theme_options` (templates); `null` for an unmanaged document to a non-builder and for a pattern the user may not read |

The core REST API is used alongside: `POST /wp/v2/pages` to create and publish pages, `POST /wp/v2/templates` to create a custom template, `POST /wp/v2/pages/{id}` with `template` to assign it, `POST /wp/v2/blocks` to create a pattern.

## 10.5 Settings

| Route | Arguments | Response |
|---|---|---|
| `GET /settings` | — | The settings object (`post_types`, `iconsets`, `breakpoints`, `remove_comments`, `revisions_to_keep`, `ai`). Permission: `jikji_compile` |
| `POST /settings` | The same object | The saved settings; `400 jikji_breakpoint_order` when the breakpoints do not strictly decrease. When breakpoints change every stylesheet is regenerated and the result is reported as `cssRegeneration`. Permission: `manage_options` |

## 10.6 AI

The editor's AI tab uses these; they are not a general model proxy ([The AI tab 7.4](07-ai.md#74-for-scripts-and-agents)). Permission: `jikji_compile` plus `edit_post` on `post_id`.

| Route | Arguments | Response |
|---|---|---|
| `GET /ai/status` | `post_id`, `refresh?=false` | `{available, reason, message, providers, model, modelError, accepts, fileLimits, tools, capabilities, limits, usage, remaining, connectorsUrl, settingsUrl, cssProperties, resultBudget, promptVersion}` |
| `POST /ai/turn` | `post_id`, `mode?="edit"\|"generate"`, `messages` (the conversation as core AI Client message DTOs) | `{message, finish, usage, remaining, model, tools, capabilities, …}` — one model call; `tools` names what the browser may execute. Errors: `jikji_ai_unavailable` 503, `jikji_ai_rate_limited` 429, `jikji_ai_budget`, `jikji_ai_length` 422, `jikji_ai_provider*`, `jikji_ai_timeout` 504, `jikji_ai_model_unavailable` |
| `POST /ai/fetch` | `post_id`, `url`, `method?="GET"\|"POST"`, `body?=""`, `content_type?="application/json"\|"application/x-www-form-urlencoded"\|"text/plain"` | `{url, finalUrl, hops, status, contentType, text, bytes, truncated}` plus, for HTML, `title`, `description`, `links`, `images`, and `note` for binary content — the whole normalized text (64 KB at most). The 4 KB paging (`offset`, `next`, `length`, `trust`) is done by the editor's `fetch_url` tool, not by this route. Errors: `403 jikji_ai_fetch_disabled` when the setting is off, `jikji_ai_fetch_url`, `jikji_ai_fetch_redirect`, `jikji_ai_fetch_unavailable`, `jikji_ai_fetch_rate_limited` |

## 10.7 A page from start to finish

```bash
# 1. Page (draft)
echo '{"title":"Agent Guide REST Page","status":"draft"}' > req.json
PAGE=$(api POST /wp/v2/pages req.json | jq -r .id)

# 2. Ids from the server pool
echo '{"count":3}' > req.json
read -r ID1 ID2 ID3 < <(api POST /jikji/v1/elements/ids req.json | jq -r '.ids | join(" ")')

# 3. The document's current version (lock token)
HASH=$(api GET /jikji/v1/content/$PAGE | jq -r .hash)

# 4. Save
cat > page.html <<HTML
<section id="$ID1"><h1 id="$ID2" j:text="jikji_post('title', \$post)">Title</h1><p id="$ID3">Saved through the REST API.</p></section>
HTML
jq -n --rawfile html page.html --arg hash "$HASH" --arg id1 "$ID1" \
  '{html: $html, baseHash: $hash, styles: [{name: $id1, type: "I", css: "padding:64px 24px;background:#ecfdf5;"}]}' > req.json
api POST /jikji/v1/content/$PAGE req.json | jq -c '{hash, compiled, warnings, code, message}'

# 5. Publish (core REST): save_post compiles
echo '{"status":"publish"}' > req.json
LINK=$(api POST /wp/v2/pages/$PAGE req.json | jq -r .link)

# 6. Compile state and the front end
api GET /jikji/v1/content/$PAGE | jq -c '{postStatus, compileError}'
curl -sS "$LINK" | grep -o "<h1 id=\"$ID2\">[^<]*</h1>"
```

Build request bodies with `jq` rather than escaping HTML by hand; in a heredoc write `$post` as `\$post`. A `409 jikji_conflict` means someone saved in between — read the hash again and resend.

## 10.8 A template and a part

```bash
THEME=$(api GET /jikji/v1/templates | jq -r .theme)          # blockTheme must be true
save_doc() { # save_doc WP_ID HTML_FILE STYLES_JSON
  local hash; hash=$(api GET /jikji/v1/content/$1 | jq -r .hash)
  jq -n --rawfile html "$2" --arg hash "$hash" --argjson styles "$3" '{html: $html, baseHash: $hash, styles: $styles}' > req.json
  api POST /jikji/v1/content/$1 req.json | jq -c '{compiled, code, message}'
}

# 1. Custom template (core REST); its blocks stay as the fallback
echo '{"slug":"agent-landing","title":"Agent Landing","content":"<!-- wp:post-content /-->"}' > req.json
api POST /wp/v2/templates req.json | jq -c '{id, wp_id}'

# 2. Manage it with Jikji: skeleton content, Jikji draft
jq -n --arg id "$THEME//agent-landing" '{id: $id, type: "wp_template"}' > req.json
TPL=$(api POST /jikji/v1/templates/adopt req.json | jq -r .wpId)

# 3. A new part (slug suggested from the title)
echo '{"title":"Agent Promo","area":"uncategorized"}' > req.json
read -r PART PART_SLUG < <(api POST /jikji/v1/templates/parts req.json | jq -r '"\(.wpId) \(.slug)"')
echo '{"count":4}' > req.json
read -r P1 T1 T2 T3 < <(api POST /jikji/v1/elements/ids req.json | jq -r '.ids | join(" ")')
cat > part.html <<HTML
<aside id="$P1"><a href="#" j:attr:href="jikji_site('url')" j:text="jikji_site('name')">Site</a></aside>
HTML
save_doc "$PART" part.html "[{\"name\":\"$P1\",\"type\":\"I\",\"css\":\"padding:12px;background:#fef3c7;\"}]"
echo '{"status":"publish"}' > req.json
api POST /jikji/v1/templates/$PART/status req.json | jq -c .

# 4. The template document: theme header/footer, the page, the new part
cat > tpl.html <<HTML
<div j:part="header"></div>
<main id="$T1"><h1 id="$T2" j:text="jikji_post('title', \$post)">Title</h1><div j:part="$PART_SLUG"></div><div id="$T3" j:html="jikji_post('content', \$post)"></div></main>
<div j:part="footer"></div>
HTML
save_doc "$TPL" tpl.html "[{\"name\":\"$T1\",\"type\":\"I\",\"css\":\"max-width:880px;margin:0 auto;padding:40px 24px;\"}]"

# 5. Publish the template, assign it to the page (core REST)
echo '{"status":"publish"}' > req.json
api POST /jikji/v1/templates/$TPL/status req.json | jq -c .      # {"status":"publish","compileError":""}
echo '{"template":"agent-landing"}' > req.json
api POST /wp/v2/pages/$PAGE req.json | jq -c '{template}'
```

Evaluating expressions over REST:

```bash
jq -n --argjson id "$TPL" '{post_id: $id, items: [
  {key: "title", expr: "jikji_post('"'"'title'"'"', $post)", mode: "text", scope: []},
  {key: "loop",  expr: "jikji_main_query()", mode: "each", scope: []},
  {key: "first", expr: "jikji_post('"'"'title'"'"', $item)", mode: "text", scope: [{each: "jikji_main_query() as $item"}]}
]}' > req.json
api POST /jikji/v1/render/data req.json | jq .results
# {"title":{"value":"…"}, "loop":{"count":3,"kind":"post"}, "first":{"value":"…"}}  — an error comes back as {"error":"…"}
```

## 10.9 Error codes

| Response | Meaning | Do |
|---|---|---|
| `200 {compiled: false}` | Saved as a draft (not compiled) | Publish, or set the template status to publish |
| `200 {compiled: true}` | Saved and compiled (live) | Check the front end |
| `200 {warnings: […]}` | SVG sanitizing, dropped CSS (`cssDropped`), a reference into a loop from outside, block warnings | Read; fix if needed |
| `400 jikji_invalid_markup` (`data.errors: [{id, message}]`) | A structure rule ([Syntax 8.7](08-syntax.md#87-what-a-save-refuses)) | Fix the element |
| `400 jikji_syntax_error` (`data: {id, attr, line, message}`) | A PHP syntax error in an expression | Fix `attr` of `id` |
| `400 jikji_invalid_style_name` · `jikji_selector_conflict` · `jikji_class_is_id` | Style name rules, type conflict, a class named like an ID | Rename |
| `400 jikji_css_dropped` (`data.dropped`) | `strictCss` and something would be dropped — nothing was written | Fix the property or move it to the theme CSS |
| `409 jikji_conflict` | The document version changed | Read again (`hash`) and reapply |
| `409 jikji_class_conflict` (`data.classes`) | `baseCss` differs from the current class | Read the class again and decide |
| `409 jikji_class_exists` (`data.classes`) | An existing class sent without `baseCss` (`existingClasses: "refuse"`, `wp jikji`) | Drop the row to only use the class, or send `baseCss` / `--update-classes` |
| `500 jikji_compile_failed` (`data.saved: true`) | Saved, but the compile failed — **the previous published version stays live** | Fix and save again |
| `POST /templates/{id}/status` → `400 jikji_compile_failed` | The template did not compile — state unchanged | Fix and publish again |
| `401` / `403 jikji_forbidden` | Authentication or permission | [10.1](#101-authentication-and-permissions) |
| `404 jikji_not_found` | No such document, template, pattern or revision | For a hierarchy template the theme lacks: `wp jikji template prepare` |
| `jikji_hierarchy_slug` · `jikji_template_exists` · `jikji_not_hierarchy` · `jikji_partial_failure` (`data.resume`) | `template create` / `prepare` rules (CLI) | [Templates 6.5](06-templates.md#65-which-template-to-use) |
| `jikji_eval_errors` · `jikji_eval_incomplete` · `400 jikji_too_many_items` | Evaluation errors, the time budget, more than 200 items | Read `data.results`; resend skipped items |
| `jikji_confirmation_required` · `jikji_no_admin` | CLI only: a site-wide change without `--yes`; no administrator to run as | `--yes` after a human confirms; `--user=<login>` |
