REST API
Complete reference for all API endpoints.
CMS exposes a REST API at /api for all CRUD operations, authentication, and media uploads.
By default, all endpoints require authentication. The auth-flow routes (/api/auth/request, /api/auth/create, /api/auth/logout, /api/health) always pass through so the login flow can bootstrap.
To make entity data publicly accessible — e.g. for a website fetching content without per-request credentials — define a role with public: true in your config. Unauthenticated requests then run as that role, and its permissions decide what’s reachable. A typical setup grants read with a filter: { status: "published" } so anonymous callers see only published rows. See Permissions for the full shape.
API reference
The @cms/openapi plugin documents the API from the loaded config. It’s optional: TypeScript consumers using @cms/client already get typed access.
// cms.config.ts
import { openapi } from "@cms/openapi";
export default config({
plugins: [openapi()],
// ...
});
With it registered:
| Endpoint | Description |
|---|---|
GET /openapi.json |
OpenAPI 3.1 spec (machine-readable) |
GET /docs |
Interactive API explorer (Scalar UI) |
Both are public: they need no auth and no public role. The spec includes all entity routes (plugin entities included), auth, assets, and API key endpoints, with request/response schemas derived from the config, and is built on the first request. Use it to import into Postman/Insomnia, generate typed clients in other languages (Python, Go, Ruby), or browse available endpoints.
Without the plugin, both endpoints return 404.
Entity endpoints
Every entity gets these endpoints automatically:
GET /api/:entity
GET /api/:entity/:id
POST /api/:entity
PUT /api/:entity/:id
DELETE /api/:entity/:id
GET /api/:entity/:id/referrers
List records
GET /api/posts?filter[status]=published&sort=-createdAt&limit=10
Response (200):
{
"data": [
{ "id": "...", "title": "...", "status": "published" }
],
"meta": {
"total": 42,
"limit": 10,
"offset": 0
}
}
Get single record
GET /api/posts/uuid-here?resolve[author]=name,bio
Response (200):
{
"data": {
"id": "uuid-here",
"title": "My Post",
"author": {
"id": "author-uuid",
"name": "Pedro",
"bio": "Design engineer"
}
}
}
Returns 404 if the record doesn’t exist.
Create record
POST /api/posts
Content-Type: application/json
{
"title": "New Post",
"slug": "/blog/new-post",
"status": "draft"
}
Response (201):
{
"data": {
"id": "new-uuid",
"title": "New Post",
"slug": "/blog/new-post",
"status": "draft",
"createdAt": "2025-06-01T00:00:00Z",
"updatedAt": "2025-06-01T00:00:00Z"
}
}
On a translatable entity, locale picks the new document’s locale (default: the default locale), and translationOf (a document id) creates it as that document’s translation, in its translation group. See Translation endpoint.
Update record
PUT /api/posts/uuid-here
Content-Type: application/json
{
"title": "Updated Title"
}
Response (200): Returns the full updated record. Only send the fields you want to change.
Delete record
DELETE /api/posts/uuid-here
Response (200):
{
"data": { "id": "uuid-here" }
}
Deletes the record and any related junction table rows. Optional relations that point at it are cleared.
If a required relation on another document points at the record, the delete is refused with 409 and nothing is deleted. details lists each referrer: field is <entity>.<relation>, message names the referring document’s id. Point those documents at another record, or delete them, then retry.
Replace, then delete
DELETE /api/posts/uuid-here?replaceWith=other-uuid
Points every referrer at other-uuid first, in the same transaction as the delete: relation columns, multiple relations, relations inside blocks, objects and rich text, and referrers’ pending drafts. The replacement must be a record of the same entity that you can read, in the same locale, and you must be allowed to update every referrer and the fields it points from, before and after the rewrite (otherwise 403, nothing changed). A referrer saved while the replace runs answers 409; try again. A pointer the replacement itself holds to the deleted record isn’t moved, so it never points at itself. A relation field is treated as without replaceWith: cleared, or refusing the delete if it’s required. A pointer inside blocks or rich text, or one only its pending draft holds, would point at nothing, so the delete answers 400 and changes nothing; it names those fields when you can read them all: remove the links or pick another replacement. A required relation then no longer blocks the delete. A referrer whose pending draft was rewritten gets a new updatedAt, as a rewritten record does. A referrer that would break a unique rule of its entity answers that rule’s 400, nothing changed. Each rewritten referrer gets an update entry in the audit log; its hooks and observers don’t run, and no new version is saved for it. An entity configured with replacement: false refuses replaceWith with 400. The response lists each document it moved in rewritten (empty without replaceWith):
{
"data": { "id": "uuid-here", "rewritten": [{ "entity": "menus", "id": "menu-uuid" }] }
}
Relations inside JSON (blocks, rich text) aren’t cleared by a plain delete: they keep the deleted id until the referrer is saved again. Check the referrers first, and replace when there are any.
Referrers
GET /api/posts/uuid-here/referrers
Response (200):
{
"data": [
{
"entity": "pages",
"id": "page-uuid",
"locale": null,
"fields": [
{ "path": "blocks.cta.target", "draft": false },
{ "path": "related", "draft": true }
]
}
],
"meta": { "total": 3, "hidden": 2 }
}
The records with a relation pointing at this one, and the field each points from, in the same dot notation as resolve (a block’s type is part of the path). draft: true marks a field only the referrer’s pending draft holds. Older versions aren’t counted. A referrer you can’t read (its entity, your read filter, or excluded fields) is counted in meta.hidden and not listed. A field only a pending draft holds is listed only with versions.read on the referrer’s entity. Requires read on the entity; a record you can’t read answers 404.
Bulk delete
POST /api/posts/_bulk-delete
Content-Type: application/json
{ "ids": ["uuid-1", "uuid-2"] }
Send exactly one of ids (up to 1000) or filter (same syntax as list filters). Everything is deleted in one transaction. If a required relation points at any record in the batch, the whole batch is refused with 409, the same as a single delete.
Response (200):
{
"data": { "deleted": 1, "ids": ["uuid-1"], "skipped": ["uuid-2"] }
}
skipped lists the requested ids that weren’t deleted, because they don’t exist or the role’s delete permission filter excludes them.
On a translatable entity, "allLocales": true (only with ids) adds every translation of the requested records to the batch. The 1000-row limit applies after that, and translations the role can’t delete come back in skipped.
Globals endpoints
Globals are mounted in the same /api namespace as entities, but expose only two endpoints (no ID, no list, no delete):
GET /api/:global
PUT /api/:global
Get global
GET /api/site-settings
Response (200):
{
"data": {
"id": "uuid",
"siteName": "My Site",
"siteDescription": "...",
"logo": "media-uuid",
"createdAt": "...",
"updatedAt": "..."
}
}
Returns { "data": null } if the global has required fields and has never been saved.
Update global
PUT /api/site-settings
Content-Type: application/json
{ "siteName": "New Name" }
Response (200): Returns the full updated record. Performs an upsert — creates the row if it doesn’t exist yet.
Search endpoint
GET /api/search?q=<query>&limit=<n>
Searches across all entities the caller has read permission for. A field the caller’s role excludes is never matched, as well as left out of the result.
| Parameter | Type | Default | Description |
|---|---|---|---|
q |
string | — | Required. The search term (substring match, case-insensitive). |
limit |
integer | 5 |
Max results per entity. Clamped to 1–20. |
Which fields are searched:
- When an entity marks no field
searchable: true: every top-leveltext,slugandselectfield with column-backed storage. - When it marks any: only those — top-level
text,slugandselectfields, andtextfields nested inside anobject()field (mark the nested field itself, not the parentobject()).
Marking fields narrows the search; an entity is searchable without it. The admin’s list and relation-picker search use the same fields.
Response (200):
{
"query": "hello",
"results": [
{
"entity": "posts",
"global": false,
"document": {
"id": "uuid",
"_entity": "posts",
"createdAt": "2025-06-01T00:00:00Z",
"updatedAt": "2025-06-01T00:00:00Z",
"title": "Hello world"
}
}
]
}
Each document includes id, _entity, createdAt, updatedAt, and the searched fields the caller’s role can see (a nested match returns its whole object() field). Results per entity are ordered by updatedAt descending.
Permissions: Role-based access is fully honoured — entities the caller cannot read are excluded from results, permission filters are applied, and fields the caller’s role excludes are omitted from each document.
Custom routes
<method> /api/custom/:name
Project-defined server-side endpoints registered via routes in cms.config.ts — the escape hatch for logic that needs a server-only secret (proxying a third-party API, signing a URL, etc.) but doesn’t fit the entity/global model. Reachable by admins always, plus any role listed in the route’s roles, or by anyone when the route sets public: true. See Config reference — Routes for the full RouteDef shape.
A route that declares a query or body schema checks it after the access check and before its handler runs. The query string is parsed into an object first (?filter[tag]=a → { filter: { tag: "a" } }), and the body must be JSON, at most 1 MB (413 PAYLOAD_TOO_LARGE otherwise); no body is checked as undefined. A failure answers 400 VALIDATION_ERROR, with a detail per issue whose field is its path under query or body:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid query",
"details": [{ "field": "query.path", "message": "Invalid input: expected string, received undefined" }]
}
}
Plugin routes
<method> /api/plugins/:plugin/:name
Routes a plugin contributes, mounted under the plugin’s instance name (/api/plugins/redirects-eu/resolve for an instance named redirects-eu). They follow the same rules as custom routes, schema checks included: admins always, plus any role listed in the route’s roles, or anyone when the route is public (such as @cms/redirects’ resolve). Entities a plugin contributes are served at /api/:entity like your own. See Plugins → Contributions.
A plugin can also serve an exact public path outside /api for a widely followed convention — @cms/openapi serves /openapi.json and /docs this way.
Authentication endpoints
POST /api/auth/request
POST /api/auth/create
POST /api/auth/logout
GET /api/auth/me
POST /api/auth/refresh
Authentication uses a two-step email OTP flow — there are no passwords.
Request login code
POST /api/auth/request
Content-Type: application/json
{ "email": "admin@example.com" }
Response (200): Always returns 200 — the server sends a one-time code to the email if the user exists, but the response is the same either way to prevent user enumeration. The email matches its user whatever its case (Ana@example.com signs in ana@example.com).
One code per email per 30 seconds: asking again sooner returns 429 TOO_MANY_REQUESTS with a Retry-After header (seconds), whether or not the email has an account. A code that failed to send (500) doesn’t count. The response’s resendIn gives that wait in seconds, the same for every email, so a form can count down to its “Resend” button:
{ "data": { "authRequestId": "uuid", "resendIn": 30 } }
Signup. When the public role has signup, send "signup": true to let someone without an account create one: the code goes to the email whether or not it has a user, and verifying it with POST /api/auth/create creates the user with the signup role. The email must then be a valid address (400 otherwise). An email that already has a user just signs in. When the project’s signup.allow refuses an email, it gets no code, with the same 200. Without the flag, or with signup off (the flag is then ignored), an unknown email gets no code, as above; the admin’s login never sends it, so it can’t create accounts.
{ "email": "customer@example.com", "signup": true }
Locale. Send "locale" with the locale the person is reading in, such as "pt", and the code
email is written in it (see email.templates); a signup also
stores it as the new user’s preferredLocale. It’s a hint: a value that isn’t one of the
project’s locales ("pt-BR" against "pt") is ignored, never refused, and the email falls back
to the user’s preferredLocale, then the default locale. A locale that isn’t a string is a
400. The admin’s login sends none.
{ "email": "customer@example.com", "signup": true, "locale": "pt" }
Create session
POST /api/auth/create
Content-Type: application/json
{
"authRequestId": "uuid-from-email",
"code": "123456",
"transport": "cookie"
}
transport decides how the client carries the session:
"cookie"(default) — for the admin and other same-site browser apps. Sets acms_sessionHTTP-only cookie."token"— for web servers and native apps. Sets no cookie and returns the session token in the body, to send asAuthorization: Bearer <token>.
name (optional, at most 200 characters) is stored on a user the code creates through signup, and ignored otherwise.
Response (200):
{
"data": {
"user": {
"id": "user-uuid",
"email": "admin@example.com",
"name": "Admin",
"role": "admin"
},
"expiresAt": "2026-12-04T12:00:00.000Z",
"created": false,
"token": "cms_s_…"
}
}
token is only present with "transport": "token". It is shown once: the server stores only its hash. Store it as you would a password (a server-side secret store, the platform keychain on a device). created is true when the code was a signup code and its user was created now, so a site can send new users to onboarding. Returns 400 if the code is invalid or expired, or if it’s a signup code verified after signup was turned off.
Bearer authentication
Server-to-server and app callers pass a bearer token instead of the session cookie:
Authorization: Bearer <token>
The token is either an API key (cms_k_…, bound to a role, no user) or a session token (cms_s_…, from "transport": "token", acting as the signed-in user with their role). The prefix decides which.
If a Bearer token is present, it must be valid — the server returns 401 immediately on an invalid or expired token. There is no fallback to the session cookie or to the public role.
Signing in from an external app
With @cms/client, this is cms.auth.* — see Signing in. Over HTTP:
POST /api/auth/requestwith the user’s email.POST /api/auth/createwith the emailed code and"transport": "token"; keepdata.token.- Send
Authorization: Bearer <token>on every request. The user’s role and permissions apply. - Call
POST /api/auth/refreshwith the same header to slide the expiry (30 days from the call). POST /api/auth/logoutwith the same header ends the session.
Session tokens are user credentials: keep them on the server or in the device’s secure storage, never in a public bundle. For read-only site content, use a public role or an API key instead.
Sessions
GET /api/_sessions # your sessions; ?userId= (admins) for another user's
DELETE /api/_sessions/:id # revoke one
DELETE /api/_sessions # revoke all; ?userId= (admins), ?except=current
Each listed session is { id, transport, userAgent, createdAt, lastUsedAt, expiresAt, current }, never its token; current marks the session making the request, and lastUsedAt is updated at most once an hour. A non-admin gets 404 for another user’s session and 403 for ?userId= of someone else. The current session can’t be revoked here (400): log out instead. An API key has no sessions (403). Revokes are recorded in the audit log, and deleting a user deletes their sessions.
Logout
POST /api/auth/logout
Deletes the session sent as the bearer token or the cookie, and clears the cookie when the session came from it.
Current user
GET /api/auth/me
Returns the authenticated user and their role, from the bearer session token or the cookie. Returns 401 if not authenticated (an API key has no user, so it gets 401 here too).
Refresh session
POST /api/auth/refresh
Extends the session to 30 days from now and returns the new expiresAt. A cookie session gets its cookie re-set; a bearer session keeps using the same token.
Translation endpoint
For translatable entities:
GET /api/pages/uuid-here/translate?locale=pt
Prepares a translation of the document in the target locale and saves nothing. Returns { data, warnings }: data is a create body (relations pointed at their translations in that locale, a suggested slug, locale and translationOf set), and warnings lists the relations left without a translation. Create it with POST /api/pages, keeping translationOf. A locale the document already has is a 409.
POST /api/pages/uuid-here/translate
Content-Type: application/json
{ "locale": "pt" }
Prepares the translation and creates it as is, returning { data, warnings } with a 201. See Creating translations.
Asset upload
POST /api/assets/upload
Content-Type: multipart/form-data
file: <binary>
alt: "Optional description" (stored only for images)
The file is routed to the correct entity by MIME type: image/* → _image, video/* → _video, everything else → _file. Returns the created asset record with image dimensions extracted automatically (for images). Deduplicates by SHA-256 hash within the same entity.
Needs create on the target entity (an unauthenticated caller acting as the public role too), and update when a duplicate’s new alt rewrites the existing record; otherwise 403. The record comes back without the fields the role’s read excludes, and the upload is written to the audit log. If storing the file fails, no record is left behind.
See the Assets guide for full response shapes and querying.
Asset cleanup
GET /api/assets/cleanup/unused
POST /api/assets/cleanup
Content-Type: application/json
{ "ids": ["<uuid>", "..."] }
GET lists the assets nothing references ({ data: { assets, count, totalSize } }) and deletes nothing. POST deletes those of the given ids that are still unused and returns the deleted ones in the same shape. Both need a role with assets: { cleanup: true } (admins have it), otherwise 403. Assets created in the last hour are never listed or deleted. See the Assets guide.
Image transforms
GET /api/assets/:filename?w=400&format=webp
GET /api/assets/:filename?w=800&fit=cover&format=avif&q=75
Serves the original file with no query params, or a transformed image with w, fit, format, and q parameters. See Assets guide for full parameter reference.
Health check
GET /api/health
Returns 200 OK (plain text) when healthy, 503 Service Unreachable otherwise — no further detail in the body by design. See Deployment for the full set of health endpoints.
TypeScript client
@cms/client provides a typed wrapper around the REST API. Install it in your frontend project:
npm install @cms/client
Setup
import { createClient } from "@cms/client";
import type cmsConfig from "./cms.config";
export const cms = createClient<typeof cmsConfig>({
url: "https://your-cms.example.com",
token: process.env.CMS_API_KEY,
});
Pass the config as a type-only generic — the runtime never imports it. Entity names (both collections and globals) become a checked union, and every response is inferred from the selection you pass.
Collection methods
// Find one record matching a filter (returns null if not found)
const { data: post } = await cms.find("posts", {
filter: { slug: "/blog/my-post" },
});
// List records with filtering, sorting, and pagination
const { data: posts, meta } = await cms.list("posts", {
filter: { status: "published" },
sort: "-createdAt",
limit: 10,
offset: 0,
});
// Get a record by ID
const { data: post } = await cms.get("posts", "uuid-here");
// Create
const { data: created } = await cms.create("posts", {
title: "New Post",
status: "draft",
});
// Update
const { data: updated } = await cms.update("posts", "uuid-here", {
title: "Updated Title",
});
// Delete
await cms.delete("posts", "uuid-here");
Global methods
Globals use the same methods as collections but without an ID:
// Get a global (returns null if never saved and has required fields)
const { data: settings } = await cms.get("site-settings");
// Update a global (upserts)
const { data: updated } = await cms.update("site-settings", {
siteName: "My Site",
});
The client detects the call pattern at runtime: two arguments (name + params) → global, three arguments (name + id + params) → collection.
Runtime config
// Update client options at runtime (e.g. switch API key)
cms.config({ token: newKey });
Custom and plugin routes
// Typed from the config: the path, method, query and body are checked, and the result is the
// route's routeJson() data.
const { data } = await cms.route("/custom/reviews-search", { query: { q: "cheese" } });
See cms.route().
Raw requests
// Untyped escape hatch for any path. The client adds /api, so this calls /api/custom/my-route.
const result = await cms.request<MyType>("/custom/my-route", {
method: "POST",
body: { foo: "bar" },
});
Admin config
GET /api/admin/config
Returns the full CMS configuration for the admin UI (entity definitions, field types, locales, admin config). Stripped of hooks and internals.
Rate limiting
All endpoints are rate-limited per IP:
| Scope | Limit |
|---|---|
| General API | 200 requests/minute |
Auth endpoints (/api/auth/*) |
10 requests/minute |
When exceeded, the server returns 429 Too Many Requests with a Retry-After header.
Login codes also have a per-email limit, kept in the database so it holds across instances and IPs: one code per email per 30 seconds (see Request login code).
Rate limiting is in-memory and per-process — it is not shared across multiple instances. For production deployments with multiple processes, use a reverse-proxy rate limiter (nginx, Cloudflare) in front of the CMS.
Error responses
All errors follow a consistent format:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed",
"details": [
{ "field": "title", "message": "Required" },
{ "field": "slug", "message": "Must be unique" }
]
}
}
Error codes
| Code | HTTP Status | When |
|---|---|---|
VALIDATION_ERROR |
400 | Invalid input data, or a before* hook threw a HookError (see Hooks) |
VERSION_INCOMPATIBLE |
400 | Stored version’s data no longer parses against the current schema |
UNAUTHORIZED |
401 | Missing or invalid session |
FORBIDDEN |
403 | Role lacks permission |
NOT_FOUND |
404 | Document or entity not found |
CONFLICT |
409 | A slug or locale already taken, or a delete refused because a required relation points at the record. A value a unique rule refuses is a VALIDATION_ERROR on the rule’s fields |
PAYLOAD_TOO_LARGE |
413 | Upload exceeds the asset size limit |
TOO_MANY_REQUESTS |
429 | Rate limit exceeded |
SERVICE_UNAVAILABLE |
503 | No database connection freed up in time (see Deployment) |
INTERNAL_ERROR |
500 | Unexpected server error |
Previous
Synced blocks
Next
Client