Headless API
Read this site's content from somewhere else
What this is
A read-only content API at /api/v1, authenticated with tokens rather than logins. The bundled admin and SPA are unchanged — this sits alongside them, so a blog can be served by the built-in frontend today and by a static site generator later without a rewrite.
There is no /api/v1 write surface. The admin API already has one, gated on roles, and a second path to the same mutations is a second place for an authorization bug to live.
Tokens
Issue one at /admin/tokens. The plaintext is shown once and never again — only a SHA-256 hash is stored, so a copy of the database does not hand over working credentials. Losing it means issuing another.
curl https://example.com/api/v1/posts \ -H "Authorization: Bearer bb_..."
The bb_ prefix is what lets one Authorization: Bearer header carry either a token or a user session — middleware picks the verifier from the prefix rather than trying both.
Scopes: content:read, content:write, media:read, media:write. A write scope grants the matching read. A token cannot manage tokens — otherwise a leaked read-only credential could mint itself a write-scoped one.
Endpoints
Every route is a GET, and only published content is returned. The scope is what an API token needs; a signed-in session passes without one.
| Path | Scope | Returns |
|---|---|---|
/api/v1/posts Published posts, newest first. | content:read | PublicPost[] |
/api/v1/posts/:slug One published post, by slug or id. | content:read | PublicPost |
/api/v1/pages Published pages, newest first. | content:read | PublicPage[] |
/api/v1/pages/:slug One published page, by slug or id. | content:read | PublicPage |
/api/v1/categories Every category, with post counts. | content:read | PublicCategory |
/api/v1/tags Every tag, with post counts. | content:read | PublicTag |
/api/v1/media/:id One media item, by id. | media:read | PublicMedia |
:slug also accepts a numeric id, since slugs are nullable on posts.
Comments are deliberately absent. That table stores author_email for unauthenticated commenters, and a public feed of reader addresses is an incident rather than a feature.
Query parameters
Accepted on the collection routes. Filtering happens in SQL rather than over the page that happened to load — filtering a page client-side gives an answer that depends on the page size.
| Name | Meaning |
|---|---|
| category | Filter posts by category slug or id. |
| format | `markdown` returns the source. Anything else returns rendered HTML. |
| page | Which page of results. Defaults to 1. |
| per_page | Results per page. Defaults to 10, clamped to 100. |
| search | Filter posts whose title or excerpt contains this text. |
| tag | Filter posts by tag slug or id. |
?format=markdown returns the source instead of rendered HTML. Every item reports the format it actually carries: a post written before HTML rendering existed has no cached HTML, and the API falls back to Markdown and says so rather than labelling Markdown as HTML for you to inject into a page. basicben content:rerender fills the cache.
What comes back
One envelope for everything, so a consumer writes the unwrapping once. meta.total_pages is computed for you: total / per_page is the sum people get wrong, and an off-by-one there means a paginating client either misses the last page or loops forever on an empty one.
{ "data": [<object>], "meta": { "page", "per_page", "total", "total_pages" } }{ "data": <object> }{ "error": "Not found" }A missing or unpublished item is a 404; a missing or insufficiently scoped credential is a 401; too many requests is a 429. There is no partial success — an error body carries error and no data.
PublicPost
A post as the content API returns it.
| Field | Type | Meaning |
|---|---|---|
| id | number | Stable identifier. Accepted anywhere a slug is. |
| slug | string | null | URL segment. Null on posts written before slugs existed. |
| title | string | Plain text, never markup. |
| excerpt | string | null | Short summary, if the author wrote one. |
| content | string | The body, in whichever `format` this item reports. |
| format | 'html' | 'markdown' | What `content` actually is — not what you asked for. See `?format=`. |
| featured_image_url | string | null | Absolute URL of the featured image, or null. |
| author | string | null | The author's display name. Never their address. |
| category | { id: number; name: string; slug: string } | null | The single category, or null when uncategorised. |
| tags | Array<{ id: number; name: string; slug: string }> | Every tag on the post. Empty when untagged. |
| meta_title | string | null | SEO title override, if set. |
| meta_description | string | null | SEO description override, if set. |
| published_at | string | When it was created, ISO 8601. Posts are ordered by this, newest first. |
| updated_at | string | When it last changed, ISO 8601. |
PublicPage
A page as the content API returns it. A post without the blog machinery.
| Field | Type | Meaning |
|---|---|---|
| id | number | Stable identifier. Accepted anywhere a slug is. |
| slug | string | URL segment. Required on pages, unlike posts. |
| title | string | Plain text, never markup. |
| content | string | The body, in whichever `format` this item reports. |
| format | 'html' | 'markdown' | What `content` actually is — not what you asked for. See `?format=`. |
| meta_title | string | null | SEO title override, if set. |
| meta_description | string | null | SEO description override, if set. |
| published_at | string | When it was created, ISO 8601. |
| updated_at | string | When it last changed, ISO 8601. |
PublicCategory
A category, with how many published posts sit in it.
| Field | Type | Meaning |
|---|---|---|
| id | number | Stable identifier. |
| name | string | Display name. |
| slug | string | URL segment. Accepted by `?category=`. |
| description | string | null | Longer description, if one was written. |
| post_count | number | Published posts in this category. Zero is returned, not omitted. |
PublicTag
A tag, with how many published posts carry it.
| Field | Type | Meaning |
|---|---|---|
| id | number | Stable identifier. |
| name | string | Display name. |
| slug | string | URL segment. Accepted by `?tag=`. |
| post_count | number | Published posts carrying this tag. |
PublicMedia
A media item.
| Field | Type | Meaning |
|---|---|---|
| id | number | Stable identifier. |
| url | string | Absolute URL of the file. |
| mime_type | string | MIME type as recorded at upload. |
| size | number | Size in bytes. |
| alt_text | string | null | Alt text, if an editor supplied one. |
| created_at | string | When it was uploaded, ISO 8601. |
Media URLs
Every URL the content API returns is absolute, resolved against APP_URL. That matters more here than anywhere else in the app: the bundled frontend can resolve /uploads/x.png because it is served from the same origin, and a static build on another host cannot — it would emit markup pointing at its own server.
With the default local driver the app serves those files itself, which works but puts every image request through your Node process. Object storage is the production answer, and publicUrl points the URLs at a CDN or custom domain rather than the bucket's own hostname.
storage: {
driver: 's3', // also r2, minio, spaces, b2
bucket: process.env.S3_BUCKET,
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
publicUrl: 'https://cdn.example.com' // what consumers receive
}The API does not refuse to serve media when the local driver is active. Refusing would break the same-origin case, which is legitimate, and would tell a consumer nothing useful — an absolute URL at least resolves wherever the app is reachable. What it does instead is warn once at the first request if the URL is still relative, which means APP_URL is unset.
Public reads
Off by default: /api/v1 requires a credential. Set public_api to true in settings to serve content anonymously — appropriate for a site whose content is public anyway, and for letting a browser-side consumer read it without shipping a token to the browser.
Caching
Every read carries an ETag and Cache-Control, and a request with If-None-Match gets a 304 with no body. A build step that re-fetches the same content repeatedly — which is what most consumers are — stops re-downloading it.
curl -H "Authorization: Bearer bb_..." \
-H 'If-None-Match: "1b2-uSkhG..."' \
https://example.com/api/v1/posts
# 304, zero bytesStatic files get the same treatment, plus Accept-Ranges and real 206 responses, so media can be seeked and resumed. Previously Last-Modified was sent and the If-Modified-Since that came back was ignored, so every conditional request was answered with the whole file.
Webhooks
Add receivers at /admin/settings, one URL per line. Each gets a POST when a post, page or media item is created, updated or deleted — which is what stops a consumer polling.
POST /your-hook
X-BasicBen-Event: post.created
X-BasicBen-Signature: sha256=<hex>
{ "event": "post.created", "id": 7, "slug": "hello", "at": "2026-08-18T…" }The signature is an HMAC of the exact body, keyed with your APP_KEY. Verify it over the raw bytes — a body that has been parsed and re-serialised does not reproduce it, because whitespace and number formatting are free to change. That is what bodyParser's skip option is for.
import { verify } from '@basicbenframework/core/webhooks'
// bodyParser({ skip: '/api/webhooks/' }) left the stream unread
let raw = ''
for await (const chunk of req) raw += chunk
if (!verify(raw, req.headers['x-basicben-signature'], process.env.APP_KEY)) {
return res.json({ error: 'Bad signature' }, 401)
}Delivery is at-most-once. A failure is logged and dropped; there is no retry queue, because a durable one needs a table and a worker and this framework has neither — an in-memory retry loop would lose everything on the next deploy while looking like a guarantee. Treat webhooks as a latency optimisation and poll as the backstop if you cannot miss an event.
Rate limits
120 requests a minute, per address. Every response carries RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset; a refused one adds Retry-After and a 429.
Per-token budgets would be the better accounting — a build server on a shared CI address would get its own — but a limiter has to run before authentication, or a flood of fabricated tokens is never limited at all. Before authentication the token is unverified, and keying on an unverified string hands an attacker a fresh budget per fabricated token. So the address it is. The limit is set high enough that sharing one rarely bites: a build fetching a thousand posts at the maximum hundred per page is ten requests.
CORS
A browser-side consumer on another origin needs an allowlist. The default is origin: '*', which works for public reads but cannot carry credentials.
export default {
cors: {
origin: ['https://blog.example.com', 'https://staging.example.com'],
credentials: true
}
}origin takes a string, an array, or a function of the request origin. Setting '*' together with credentials: true is refused with a warning rather than honoured: browsers reject that pairing outright, so it would break every credentialed request silently. An origin that is not on the list receives no Access-Control-Allow-Origin at all, which is what makes the browser refuse it.