Skip to content

Public API ​

The Public API (/api/v1/public/) is an edge-native, hardened endpoint designed for external consumers — headless frontends, mobile apps, static site generators, and public form submissions. All error responses conform to RFC 9457 Problem Details (Content-Type: application/problem+json).


Permission Model ​

Access is controlled across three distinct layers:

Level 1 — Seed Capability Flags ​

Defined in each Seed blueprint schema:

typescript
interface Seed {
  allowPublicRead?: boolean;   // Enables GET /api/v1/public/:seed
  allowPublicPost?: boolean;   // Enables anonymous POST /api/v1/public/:seed/add (form submissions)
  defaultPublicStatus?: 'draft' | 'review' | 'published'; // Status of an anonymous submission. Default: 'draft'
  allowPublicEdit?: boolean;   // Enables PUT & PATCH /api/v1/public/:seed/edit/:id
}

If a capability flag is false or absent, the endpoint fails closed regardless of credentials. A seed with no public flag at all, and a seed whose allowPublicRead is false on a read, answer the same 404 (seed-not-found) as a seed that does not exist, so a public caller cannot learn which private seeds exist. A seed that is public for another operation answers 403 Forbidden (operation-not-allowed) on a write it does not allow. allowPublicPost gates anonymous submissions only: on a seed that has at least one public flag, a request with the secret key creates entries without it. A draft entry and a missing entry answer the same 404.

Level 2 — Key Roles & Zero-Secret Mode ​

  1. Authenticated Requests (X-API-Key header):

    KeyVariableAllowsLocal value
    PublishableBEECH_PUBLISHABLE_KEYGET / HEAD / OPTIONSbeech_pk_dev
    SecretBEECH_SECRET_KEYEvery method, server onlybeech_sk_dev

    The key authenticates, Level 1 still authorizes. The API denies a request in four cases:

    CaseStatusProblem type
    The key is wrong401public-api-key-unauthorized
    A publishable key is sent on a write403public-api-secret-key-required
    No secret key is configured on a write, or neither key on a read403public-api-not-configured
    The secret key is beech_sk_dev while ENV is not development403public-api-dev-secret-key

    For the last case the Worker also logs a warning once per refused request. The log never prints the key.

  2. Zero-Secret Public Form Mode:

    • Public frontends can create entries via POST /api/v1/public/:seed/add without exposing any secret API key by utilizing the built-in Time-Trap token anti-bot mechanism (_timeTrapToken) and hidden honeypot fields.
    • These routes need no key: GET /api/v1/public/health, GET /api/v1/public/timetrap/token, GET /api/v1/public/:seed/schema and POST /api/v1/public/:seed/add. PUT / PATCH /api/v1/public/:seed/edit/:id always needs the secret key.
    • A key sent on POST /add is checked: a publishable key gets 403, and the secret key skips the Time-Trap and honeypot checks.

Level 3 — Published-Only Filter ​

By default, all public read queries automatically filter by AND status = 'published' (PUBLIC_PUBLISHED_ONLY !== 'false'). Content in draft or review status is invisible to external consumers. To expose drafts publicly, explicitly set PUBLIC_PUBLISHED_ONLY=false.

Level 4 — Trashed-Row Exclusion ​

On every Seed, every public read additionally filters by AND deleted_at IS NULL. The predicate is compiled by the engine's single SQL compiler and defaults to active-only, so it covers list reads, single reads, relation expansion (?include=), and relation subquery filters at once — a trashed parent can never surface through a subquery, and there is no opt-out on any public route. Trashed entries are reachable only through the authenticated Trash endpoints. Unlike the published-only filter, this one has no environment variable and cannot be disabled.

A live row never carries a deleted_at key, so active-row payloads are unaffected by the Trash. See Trash, Soft Delete & GDPR Purge.


Rate Limiting ​

The Public API uses Cloudflare's native Rate Limiting API (with an in-engine Token Bucket fallback):

jsonc
// wrangler.jsonc
{
  "ratelimits": [
    { "name": "PUBLIC_READ_RATE_LIMITER",  "namespace_id": "1003", "simple": { "limit": 120, "period": 60 } },
    { "name": "PUBLIC_WRITE_RATE_LIMITER", "namespace_id": "1004", "simple": { "limit": 20,  "period": 60 } }
  ]
}

The rate limit key is <client_ip>:<seed>:<publicApiRead|publicApiWrite>. On limit breach, the endpoint returns:

http
HTTP/1.1 429 Too Many Requests
Content-Type: application/problem+json

{
  "type": "https://beechcms.dev/problems/rate-limit-exceeded",
  "title": "Too Many Requests",
  "status": 429,
  "detail": "Too many requests",
  "instance": "/api/v1/public/articoli"
}

Seed Schema — GET /api/v1/public/:seed/schema ​

Returns the public schema for a single seed. Useful for frontend dynamic form generation and client-side validation. Zero-secret: no API key required.

Privacy Filtering: Branches with policies.public: false, internal, or restricted classifications are automatically stripped from the schema.

Request

http
GET /api/v1/public/posts/schema

Response 200 OK

json
{
  "slug": "posts",
  "label": "Post",
  "labelPlural": "Posts",
  "allowPublicRead": true,
  "allowPublicPost": true,
  "allowPublicEdit": false,
  "branches": [
    {
      "alias": "title",
      "type": "text",
      "label": "Title",
      "requiredOnCreate": true,
      "policies": { "public": true, "visibility": "full" }
    },
    {
      "alias": "body",
      "type": "richtext",
      "label": "Body",
      "requiredOnCreate": false,
      "policies": { "public": true, "visibility": "full" }
    },
    {
      "alias": "priority",
      "type": "tags",
      "label": "Priority",
      "options": [
        { "label": "low", "value": "low", "color": "#64748b" },
        { "label": "high", "value": "high", "color": "#ef4444" }
      ],
      "multiple": false,
      "requiredOnCreate": false,
      "policies": { "public": true, "visibility": "full" }
    }
  ]
}

Branch keys specific to tags:

KeyValuePresent when
optionsArray<{ label: string; value: string; color: string }> — label equals valuethe branch declares options
multipleboolean — false = single choice, true = multiple choicetype is tags

The value of a tags branch is always an array of strings, single choice included. A value outside options, a duplicate, or more than one value on a single-choice branch is rejected with 400 content-validation-failed.

Tag values are normalized on write (invisible/control characters removed, whitespace collapsed, trimmed, Unicode NFC; case preserved). A field holds at most 10 tags of 25 characters each; a longer tag or a larger array is rejected with 400 content-validation-failed, never truncated. See Tag values.


Read — GET /api/v1/public/:seed ​

Reads entries for a seed. Requires allowPublicRead: true and the publishable or the secret key.

Query parameters:

ParameterDescription
idFetch a single entry by UUID
slugFetch a single entry by its unique slug
page / limitPagination (limit clamped to max 100)
all=trueReturns up to 100 entries ignoring pagination
latest=NReturns the N most recent entries (clamped 1–100, default 10)
searchFull-text search across content fields and slug
orderBy / orderDirSorting by field alias or system timestamp (asc | desc)
filterJSON-encoded filter object (see below)
fieldsComma-separated list of aliases to project
includeComma-separated relation aliases to expand at depth 1 (max 3 includes)
langResponse language for localized fields: a locale code (en, pt-BR) or all. See Localization

Filter syntax:

json
{
  "logic": "AND",
  "where": [
    { "field": "status",     "op": "eq",          "value": "published" },
    { "field": "budget",     "op": "gte",         "value": 1000 },
    { "field": "tags",       "op": "has_any_tag", "value": ["design", "dev"] }
  ]
}

Supported filter operators (snake_case required):eq, neq, gt, gte, lt, lte, contains, not_contains, starts_with, ends_with, is_empty, is_not_empty, in, not_in, has_tag, has_any_tag, has_all_tags.

On a tags field, eq, contains and in test membership of the stored array, and neq, not_contains and not_in are their negation.

has_tag, has_any_tag and has_all_tags on a tags field normalize each requested tag with the same rule used on write, so " design " matches design. A tag that cannot be normalized (blank, too long) matches nothing, and has_all_tags containing one matches no entry. A list of more than 50 tags is a malformed filter and is ignored.

Single entry request:

http
GET /api/v1/public/articoli?slug=my-article
X-API-Key: beech_pk_dev

Response 200 OK (single entry):

json
{
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "slug": "my-article",
    "status": "published",
    "created_at": 1713600000,
    "updated_at": 1713600000,
    "title": "My Article",
    "body": { "schemaVersion": 1, "doc": { "type": "doc", "content": [] } },
    "cover_image": "https://api.beech.local/api/media/1713600000-cover.jpg"
  },
  "meta": { "seed": "articoli" }
}

Note: The response is flat — content fields are projected at the root of data alongside system properties (id, slug, status).

List request:

http
GET /api/v1/public/articoli?page=1&limit=10&orderBy=created_at&orderDir=desc
X-API-Key: beech_pk_dev

Response 200 OK (list):

json
{
  "data": [
    { "id": "...", "slug": "...", "status": "published", "title": "..." }
  ],
  "meta": {
    "total": 24,
    "page": 1,
    "limit": 10,
    "returned": 10,
    "seed": "articoli"
  }
}

Relation Expansion — ?include= ​

The include query parameter enables server-side resolution and expansion of related entries in a single request. Expanded targets are returned under the _includes object on each entry.

Request with relation expansion:

http
GET /api/v1/public/posts?slug=my-first-post&include=category_id,related_posts
X-API-Key: beech_pk_dev

Response 200 OK with _includes:

json
{
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "slug": "my-first-post",
    "status": "published",
    "title": "My First Post",
    "category_id": "8a01f92e-3367-42f2-8ce1-b9242a7fa5bc",
    "related_posts": ["661e8400-e29b-41d4-a716-446655440111"],
    "_includes": {
      "category_id": {
        "id": "8a01f92e-3367-42f2-8ce1-b9242a7fa5bc",
        "slug": "technology",
        "name": "Technology",
        "status": "published"
      },
      "related_posts": [
        {
          "id": "661e8400-e29b-41d4-a716-446655440111",
          "slug": "second-post",
          "title": "Second Post",
          "status": "published"
        }
      ]
    }
  },
  "meta": { "seed": "posts" }
}

Operational Limits & Invariants ​

  • Depth 1 Only: Nested dot paths (e.g., include=category_id.author) are rejected with 400 Bad Request (invalid-include).
  • Maximum 3 Includes: A single request may request at most 3 distinct include branches. Requests with >3 branches return 400 Bad Request.
  • Target ID Clamping: Sub-queries for included entries are bounded at a maximum of 200 target IDs per branch.
  • Access Policies: A relation branch is expandable only if its resolved policy allows public read (resolvePolicies(branch).public) and the target seed specifies allowPublicRead: true.
  • Projection Independence: Relation expansion works seamlessly with ?fields=. Even if the foreign key alias is omitted from ?fields=, _includes is still populated.

Relation Subquery Filters ​

A relation subquery filters the collection by a condition evaluated against the target of a relation branch, instead of against the parent entry itself. It is a nested object in the value position of an existing in condition inside the filter query parameter — no new query parameter is introduced.

Request — posts in the category named "Tech":

http
GET /api/v1/public/posts?filter={"logic":"AND","where":[
  {"field":"category_id","op":"in","value":{"logic":"AND","where":[{"field":"name","op":"eq","value":"Tech"}]}}
]}
X-API-Key: beech_pk_dev

The nested value is { where: [...], logic?: 'AND' | 'OR' }; where entries share the ordinary {field, op, value} shape and are validated against the target seed, through the same public + filterable policy gate as a top-level filter. An in condition on a relation alias whose value is a plain array of ids (rather than a subquery object) stays legal and is routed through the same resolver — this also fixes a multi-relation in filter that answered 500 before this endpoint existed.

Operational Limits & Invariants ​

  • Relation Reachability: field must be a publicly reachable relation branch of the queried seed — the same five checks ?include= enforces. Both single and multi relations are accepted.
  • Operator: op must be in. Any other operator paired with an object value returns 400 (invalid-subquery).
  • Depth 1 Only: A nested condition whose own value is an object (a subquery inside a subquery) returns 400.
  • Request Bound: At most 2 relation subqueries per request; each inner where carries at most 5 conditions.
  • Published Only: The inner query resolves against published entries only, matching ?include=.
  • Refused, Not Truncated: A resolved target-id set larger than 200, or a resolved parent-id set larger than 500 (multi-relation fan-out), is refused with 400 — never silently truncated, since truncation would silently drop matching parent rows.
  • Composability: A subquery filter composes with ?include= in the same request; the filtered set is resolved first, then relations are expanded on the surviving entries.

Error Responses ​

  • 400 invalid-subquery: the relation is not publicly reachable, the operator/shape is wrong, or a resolved id set exceeds its cap.
  • 400 invalid-filter: an inner where condition names a field on the target seed that is not public or not filterable — the same contract an ordinary top-level filter enforces.

Localization ​

When a seed has localized fields, every Public API endpoint that returns entry data negotiates a response language. If no seed in the project has a localized branch, none of this applies: lang and Accept-Language are ignored, no settings are read, and no language headers are added.

Language negotiation ​

The response language is the first match of:

  1. ?lang=<code> — if the code is registered in the project's content languages. An exact match wins, then the primary language subtag (?lang=en-US resolves to en when only en is registered). Codes are case-normalised (EN-us → en-US).
  2. Accept-Language — each tag in preference order (q descending, header order among equals), with the same exact-then-primary lookup. *, q=0 and malformed entries are skipped.
  3. The default locale of the project.

A well-formed lang that the project does not register (for example after a language was removed) is not an error: negotiation falls through to Accept-Language and then the default, so a stale frontend keeps rendering. A malformed lang is refused:

json
{
  "type": "invalid-lang",
  "title": "Bad Request",
  "status": 400,
  "detail": "'lang' must be a language code such as 'en' or 'pt-BR', or 'all'."
}

Single language (default) ​

Localized fields are returned as plain values in the resolved language, following the fallback chain requested locale → default locale → first stored translation → null:

http
GET /api/v1/public/products?slug=trail-shoe&lang=en
X-API-Key: beech_pk_dev
json
{
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "slug": "trail-shoe",
    "status": "published",
    "name": "Trail shoe",
    "price": 129
  },
  "meta": { "seed": "products" }
}

Every language — ?lang=all ​

?lang=all (or ?lang=*) returns each localized field as its full { locale: value } dictionary, including translations for locales no longer registered. A legacy plain value is returned as { "<defaultLocale>": value }, an empty field as null:

json
{
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "slug": "trail-shoe",
    "name": { "it": "Scarpa da trail", "en": "Trail shoe" },
    "price": 129
  },
  "meta": { "seed": "products" }
}

Filters, sort, search and includes ​

  • filter and orderBy on a localized field compare the value resolved to the response language — what the reader sees. Under ?lang=all they compare the default-locale value.
  • search matches every translation.
  • include expands related entries in the same language as the parent response; relation subquery filters resolve in that language too.
  • Field policies apply per translation: under ?lang=all a masked field masks every entry of its dictionary.

Response headers and caching ​

HeaderWhenValue
Content-LanguageSingle-language responsesThe locale the response resolved to (use it to detect a fallback)
VaryEvery negotiated responseIncludes Accept-Language
Cache-ControlSuccessful reads (200) served through the edge cachepublic, max-age=60, the same on a cache miss and a cache hit

The edge cache keys each read on the URL plus the resolved language, so two visitors sending different Accept-Language headers never share a cached response.

A cached read lives 60 seconds at each Cloudflare location. Publishing, editing or deleting an entry does not purge it: after you press Publish, a read of the same URL can return the previous content for up to 60 seconds per location (browsers and CDNs in front of your site honour the same max-age). Plan for that window, for example by revalidating a static page after 60 seconds rather than right after publishing. Error responses are never cached.

Writing localized fields ​

POST /add and PUT/PATCH /edit/:id accept, for each localized field, either a plain value or a dictionary. Writes are merged into the stored translations:

Value sentEffect
Plain value ("Trail shoe")Sets the default-locale translation
Dictionary ({ "en": "Trail shoe" })Sets each named registered locale; unnamed locales are kept; unregistered keys are dropped
{ "fr": null }Clears that locale only
null for the fieldClears every translation
http
PUT /api/v1/public/products/edit/550e8400-e29b-41d4-a716-446655440000?lang=en
X-API-Key: beech_sk_dev
Content-Type: application/json

{
  "data": {
    "name": { "en": "Trail running shoe" }
  }
}

The data echoed in the response follows the same negotiation as a read (lang, then Accept-Language, then the default), and a malformed lang is a 400 invalid-lang before anything is written. requiredOnCreate checks the default-locale translation only.

Concurrency. An edit that merges a localized field is a read-modify-write, so it is version-guarded: if the entry changed between the read and the write, the request fails with 409 entry-update-conflict instead of silently dropping a translation. Re-read the entry and retry.


Schema Revision Header — X-Schema-Revision ​

All responses emitted across the Public API surface (/api/v1/public/*) carry the X-Schema-Revision response header:

http
X-Schema-Revision: v2:a1b2c3d4e5f60718293a4b5c6d7e8f90
  • Format: v<version>:<32_hex_sha256>.
  • Ubiquity: Injected early by schemaRevisionMiddleware on all status codes (200, 201, 400, 401, 404, 429).
  • Cache Memoization: Computed once from computeSchemaFingerprint and cached per isolate via a WeakMap on the SeedRegistry instance.
  • Drift Detection: @beechcms/client compares it with the schemaFingerprint passed to the client (the generated SCHEMA_FINGERPRINT) and returns a 409 schema_drift problem on mismatch, without out-of-band polling.

Anti-Bot Helper — GET /api/v1/public/timetrap/token ​

Generates an encrypted, single-use Time-Trap token for zero-secret form submissions.

Response 200 OK

json
{
  "token": "ey...",
  "minDeltaSeconds": 1.5
}

Create — POST /api/v1/public/:seed/add ​

Creates an entry via the Public API. An anonymous submission requires allowPublicPost: true; a request with the secret key does not.

Status of the new entry

CallerStatus
Anonymous (Time-Trap token, no key)defaultPublicStatus of the seed, draft when unset. A status in the body is ignored. Set defaultPublicStatus: 'published' only for a seed where unmoderated public content is intended.
Secret keystatus in the body, else defaultPublicStatus, else published.

Authentication Modes:

  1. Authenticated Mode: Send X-API-Key with the secret key (beech_sk_dev locally). A publishable key answers 403 public-api-secret-key-required.
  2. Zero-Secret Form Mode: Include _timeTrapToken in the payload (or x-time-trap header) and ensure the anti-bot honeypot fields (fax_number, website_url, middle_name, secondary_phone, _gotcha, honeypot) remain empty.

Request

http
POST /api/v1/public/articoli/add
X-API-Key: beech_sk_dev
Content-Type: application/json
Idempotency-Key: my-client-request-id-001

{
  "status": "published",
  "slug": "my-article",
  "data": {
    "title": "My Article",
    "body": "Content here"
  }
}

Response 201 Created

json
{
  "success": true,
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "slug": "my-article",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "slug": "my-article",
    "status": "published",
    "title": "My Article",
    "body": "Content here"
  },
  "meta": {
    "seed": "articoli"
  }
}

Idempotency guarantees:

  • Same key, same payload: Replays cached 201 Created response.
  • Same key, different payload: Fails with 409 Conflict (idempotency-key-conflict).
  • TTL: Defaults to 24 hours (PUBLIC_IDEMPOTENCY_TTL_SECONDS).

Update — PUT & PATCH /api/v1/public/:seed/edit/:id ​

Partially updates an existing entry. Requires allowPublicEdit: true and the secret key.

Merge semantics:

  • Fields present in data overwrite existing values.
  • Omitted fields retain current values.
  • Fields explicitly sent as null are cleared in SQLite.

Request

http
PUT /api/v1/public/articoli/edit/550e8400-e29b-41d4-a716-446655440000
X-API-Key: beech_sk_dev
Content-Type: application/json

{
  "status": "published",
  "data": {
    "title": "Updated Title",
    "body": null
  }
}

Response 200 OK

json
{
  "success": true,
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "slug": "my-article",
  "data": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "slug": "my-article",
    "status": "published",
    "title": "Updated Title",
    "body": null
  },
  "meta": {
    "seed": "articoli"
  }
}