# BlogEngine Blog API: developer guide

Show the blog posts you write and publish in BlogEngine on **any website or app**: a Next.js or React site, WordPress,
PHP, a static site generator, a mobile app, or a plain HTML page. The API is **read-only**, served over HTTPS as JSON,
and every published post comes ready for search engines: rendered HTML, SEO title and description, canonical URL and
schema.org JSON-LD.

> **For AI coding agents.** This page is also available as plain Markdown at https://vox.bd/docs.md. Everything you need to
> build a complete blog (list page, post page, SEO tags, sitemap, RSS, cache refresh) is on this page. Ask the site
> owner for a public key (`be_pub_…`) and never invent endpoints or fields that are not listed here.

## Quick start

1. **Get a public key.** Sign in at https://app.vox.bd, open **Settings → Public API**, pick the website, and create a public key.
   It starts with `be_pub_` and is shown **once**, so copy it right away.
2. **Call the API.**

   ```bash
   curl -H "Authorization: Bearer be_pub_YOUR_KEY" "https://api.vox.bd/public/v1/posts?perPage=5"
   ```

3. **Render it.** Use `title` as the page's `<h1>`, put `html` under it, and copy the `seo` fields into the page's `<head>`.

Only posts that are **published** in BlogEngine are returned. Drafts, posts waiting for review and unpublished posts
are never visible.

## Base URL and authentication

```
https://api.vox.bd/public/v1
```

Send the key on every request, in either header:

```
Authorization: Bearer be_pub_YOUR_KEY
X-Api-Key: be_pub_YOUR_KEY
```

- **One key, one website.** A key reads the published posts of exactly one website. To show several blogs, create one
  key per website.
- **Server-side is best.** Call the API from your server (Next.js server components, PHP, a build script) so the key
  never reaches the browser.
- **Browser use is allowed** when the key lists your site under **Allowed origins** (for example
  `https://example.com` or `https://*.example.com`). Browser requests from any other origin get `403`. A request
  without an `Origin` header (server-to-server) is always allowed.
- **Rotate** a key from the dashboard if it leaks: the old key keeps working for a grace period, then stops. **Revoke**
  stops it at once.
- The key is read-only. It cannot create, edit or delete anything.

## Endpoints

All endpoints are `GET`, and all need the key except `media`.

| Endpoint | Returns |
|---|---|
| `/public/v1/posts` | A page of posts (newest first) |
| `/public/v1/posts/{slug}` | One post with its full content (`{id}` works too) |
| `/public/v1/tags` | Every tag with its number of posts |
| `/public/v1/categories` | Every category with its number of posts |
| `/public/v1/sitemap.xml` | An XML sitemap of all published posts |
| `/public/v1/rss.xml` | RSS 2.0 feed of the latest 50 posts, with full HTML |
| `/public/v1/llms.txt` | A Markdown index of the posts for AI assistants ([llms.txt](https://llmstxt.org)) |
| `/public/v1/media/{id}` | A cover image (PNG/JPEG/WebP). **No key**: it is linked from `coverImageUrl`, and only served while its post is published |

### List posts: `GET /public/v1/posts`

| Query parameter | Type | Default | Meaning |
|---|---|---|---|
| `page` | integer ≥ 1 | `1` | Page number |
| `perPage` | 1–50 | `20` | Posts per page |
| `tag` | string | | Only posts with this tag (exact match) |
| `category` | string | | Only posts in this category (exact match) |
| `q` | string | | Full-text search; results are ranked by relevance |
| `since` | ISO date | | Only posts published on or after this date, e.g. `2026-01-01` |
| `include` | `content` | | Also return `html` and `markdown` for every post (heavier; use for static builds) |

```bash
curl -H "Authorization: Bearer be_pub_YOUR_KEY" \
  "https://api.vox.bd/public/v1/posts?page=1&perPage=10&tag=kubernetes"
```

```json
{
  "data": [
    {
      "id": "8d3f0c7e-1b2a-4c5d-9e8f-0a1b2c3d4e5f",
      "slug": "kubernetes-cost-optimization",
      "title": "Kubernetes Cost Optimization: Seven Tactics That Work",
      "excerpt": "Cut your cluster bill without slowing teams down: right-sizing, autoscaling and spot nodes.",
      "keyword": "kubernetes cost optimization",
      "tags": ["kubernetes", "finops"],
      "categories": ["Guides"],
      "language": "en",
      "publishedAt": "2026-11-18T09:30:00.000Z",
      "updatedAt": "2026-11-18T10:02:11.000Z",
      "wordCount": 1840,
      "coverImageUrl": "https://api.vox.bd/public/v1/media/2b6e1f7a-9c3d-4e5f-8a1b-0c2d3e4f5a6b",
      "url": "https://example.com/blog/kubernetes-cost-optimization",
      "author": { "name": "Jane Doe", "url": "https://example.com/about", "bio": "Platform engineer." },
      "seo": {
        "metaTitle": "Kubernetes Cost Optimization: 7 Tactics",
        "metaDescription": "Cut your cluster bill without slowing teams down: right-sizing, autoscaling and spot nodes.",
        "canonicalUrl": "https://example.com/blog/kubernetes-cost-optimization",
        "jsonLd": [{ "@context": "https://schema.org", "@type": "BlogPosting", "headline": "…" }]
      }
    }
  ],
  "meta": { "page": 1, "perPage": 10, "total": 42 }
}
```

Use `meta.total` and `meta.perPage` to build pagination: `pages = ceil(total / perPage)`.

### Get one post: `GET /public/v1/posts/{slug}`

```bash
curl -H "Authorization: Bearer be_pub_YOUR_KEY" \
  "https://api.vox.bd/public/v1/posts/kubernetes-cost-optimization"
```

Returns `{ "data": post }` with every field above **plus** `html` and `markdown`. An unknown or unpublished slug
returns `404`.

### Tags and categories: `GET /public/v1/tags`, `GET /public/v1/categories`

```json
{ "data": [ { "name": "kubernetes", "count": 12 }, { "name": "finops", "count": 7 } ] }
```

## The post object

| Field | Type | Notes |
|---|---|---|
| `id` | string (UUID) | Stable id |
| `slug` | string | URL-safe, unique per website. Use it in your post URL |
| `title` | string | Render as the page's `<h1>` |
| `excerpt` | string | Short summary (the meta description); may be empty |
| `keyword` | string \| null | The post's focus keyword |
| `tags`, `categories` | string[] | |
| `language` | string | Language code, e.g. `en` |
| `publishedAt` | ISO date \| null | First publish time |
| `updatedAt` | ISO date | Last change |
| `wordCount` | integer \| null | |
| `coverImageUrl` | string \| null | Cover image, when the post has one. Usually served by VOX at `/public/v1/media/{id}`: use it directly in an `<img>`, no key needed |
| `url` | string \| null | Where the post lives on your site (see *Canonical URLs*) |
| `author` | object \| null | `{ name, url, bio }` from the website's author settings; `null` when none is set |
| `seo.metaTitle` | string | Use for `<title>` |
| `seo.metaDescription` | string | Use for `<meta name="description">` |
| `seo.canonicalUrl` | string \| null | Use for `<link rel="canonical">` |
| `seo.jsonLd` | object[] | schema.org blocks (`BlogPosting`, often `FAQPage`). Output each one in a `<script type="application/ld+json">` tag |
| `html` | string | Only on single posts or with `include=content`. The body as HTML, **without** the title |
| `markdown` | string | Only on single posts or with `include=content`. The body as Markdown; its first line is `# Title` |

### Rendering the body

- Render `title` yourself as the `<h1>`, then insert `html` (it starts at the first `<h2>`).
- The HTML uses plain tags only: headings, paragraphs, lists, tables, links, images, `<strong>`, `<em>`, code. Style it with
  your own CSS (for example Tailwind's `prose` class).
- Posts written by hand may contain HTML the author typed. If people you don't trust can write posts in your
  BlogEngine workspace, sanitize `html` before inserting it (for example with DOMPurify).

### Canonical URLs

`seo.canonicalUrl` and `url` are built from the website's **domain**, its **blog path** (default `/blog/`) and the
post's slug, for example `https://example.com/blog/kubernetes-cost-optimization`. Serve each post at exactly that
address, or change the blog path under **Websites → (your site) → Settings** in the dashboard so the two match. If they
differ, search engines are told the post lives at a page that does not exist.

## Errors

Errors are JSON in the RFC 7807 format, with a human-readable `detail`:

```json
{ "type": "about:blank", "title": "Not Found", "status": 404, "detail": "post not found" }
```

| Status | When | What to do |
|---|---|---|
| `400` | A query parameter is invalid (`detail` names it) | Fix the parameter |
| `401` | Key missing, wrong, expired, or rotated past its grace period | Check the key; create a new one |
| `403` | Browser request from an origin the key does not allow, or the account is suspended | Add the origin to the key, or call from your server |
| `404` | Post not found or not published | Show your 404 page |
| `429` | Over the key's rate limit (default 120 requests per minute) | Wait for `Retry-After` seconds; cache responses |
| `503` | The rate limiter is briefly unavailable | Retry after a few seconds |

## Caching and limits

- Every response has a strong `ETag` and `Cache-Control: public, max-age=60, stale-while-revalidate=300`.
- Send `If-None-Match: <etag>` to get `304 Not Modified` when nothing changed. Publishing or editing a post changes the
  ETag, so a revalidating client sees the change within about a minute.
- **Cache on your side.** Pages that render posts should be cached or statically generated and refreshed every few
  minutes (or on a webhook, below), not fetched on every visitor request. This keeps you far below the rate limit.

## Recipes

### Next.js (App Router)

```ts
// lib/blog.ts — server-only: the key stays on the server
const API = "https://api.vox.bd/public/v1";
const headers = { Authorization: `Bearer ${process.env.BLOG_API_KEY}` };

export async function getPosts(page = 1) {
  const res = await fetch(`${API}/posts?page=${page}&perPage=12`, { headers, next: { revalidate: 300, tags: ["blog"] } });
  if (!res.ok) throw new Error(`Blog API ${res.status}`);
  return res.json() as Promise<{ data: Post[]; meta: { page: number; perPage: number; total: number } }>;
}

export async function getPost(slug: string) {
  const res = await fetch(`${API}/posts/${encodeURIComponent(slug)}`, { headers, next: { revalidate: 300, tags: ["blog"] } });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Blog API ${res.status}`);
  return (await res.json()).data as Post;
}

export interface Post {
  id: string; slug: string; title: string; excerpt: string; tags: string[]; categories: string[];
  publishedAt: string | null; updatedAt: string; coverImageUrl: string | null; url: string | null;
  author: { name: string; url: string | null; bio: string | null } | null;
  seo: { metaTitle: string; metaDescription: string; canonicalUrl: string | null; jsonLd: object[] };
  html?: string;
}
```

```tsx
// app/blog/page.tsx — the list
import Link from "next/link";
import { getPosts } from "@/lib/blog";

export default async function BlogIndex() {
  const { data: posts } = await getPosts();
  return (
    <main>
      <h1>Blog</h1>
      {posts.map((p) => (
        <article key={p.id}>
          <h2><Link href={`/blog/${p.slug}`}>{p.title}</Link></h2>
          <p>{p.excerpt}</p>
        </article>
      ))}
    </main>
  );
}
```

```tsx
// app/blog/[slug]/page.tsx — one post, with full SEO
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getPost } from "@/lib/blog";

type Props = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const post = await getPost((await params).slug);
  if (!post) return {};
  return {
    title: post.seo.metaTitle,
    description: post.seo.metaDescription,
    alternates: post.seo.canonicalUrl ? { canonical: post.seo.canonicalUrl } : undefined,
    openGraph: { type: "article", title: post.seo.metaTitle, description: post.seo.metaDescription, images: post.coverImageUrl ? [post.coverImageUrl] : [] },
  };
}

export default async function BlogPost({ params }: Props) {
  const post = await getPost((await params).slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.title}</h1>
      {post.coverImageUrl && <img src={post.coverImageUrl} alt="" />}
      <div className="prose" dangerouslySetInnerHTML={{ __html: post.html ?? "" }} />
      {post.seo.jsonLd.map((block, i) => (
        <script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(block) }} />
      ))}
    </article>
  );
}
```

```ts
// app/blog/sitemap.xml/route.ts — re-serve the sitemap from your own domain
export async function GET() {
  const res = await fetch("https://api.vox.bd/public/v1/sitemap.xml", {
    headers: { Authorization: `Bearer ${process.env.BLOG_API_KEY}` },
    next: { revalidate: 3600 },
  });
  return new Response(await res.text(), { headers: { "content-type": "application/xml" } });
}
```

Do the same for `rss.xml` and `llms.txt` if you want them on your domain. Set `BLOG_API_KEY` in your hosting
provider's environment variables.

### Plain HTML (any site builder)

For WordPress (Custom HTML block), Wix, Squarespace, Webflow or a hand-written page. The dashboard generates this code
for you: **Settings → Public API → Get the code** creates a key that only works on your domain and fills it in.

```html
<div id="blog-posts">Loading posts…</div>
<script>
(async function () {
  var API = "https://api.vox.bd/public/v1", KEY = "be_pub_YOUR_KEY"; // key must allow this page's origin
  var box = document.getElementById("blog-posts");
  var esc = function (s) { var d = document.createElement("div"); d.textContent = s || ""; return d.innerHTML; };
  var get = function (p) { return fetch(API + p, { headers: { Authorization: "Bearer " + KEY } }).then(function (r) { return r.json(); }); };
  var slug = new URLSearchParams(location.search).get("post");
  if (slug) {
    var post = (await get("/posts/" + encodeURIComponent(slug))).data;
    document.title = post.seo.metaTitle;
    box.innerHTML = "<article><h1>" + esc(post.title) + "</h1>" + post.html + "</article>";
  } else {
    var list = (await get("/posts?perPage=20")).data;
    box.innerHTML = list.map(function (p) {
      return "<article><h2><a href='?post=" + encodeURIComponent(p.slug) + "'>" + esc(p.title) + "</a></h2><p>" + esc(p.excerpt) + "</p></article>";
    }).join("");
  }
})();
</script>
```

Posts rendered in the browser are harder for search engines to index. For the best SEO, render on the server
(the Next.js or PHP recipes).

### PHP

```php
<?php
// blog.php — /blog.php lists posts, /blog.php?post=slug shows one
const API = 'https://api.vox.bd/public/v1';
function blog_get(string $path) {
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('BLOG_API_KEY')]]);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    return [$status, json_decode($body, true)];
}

$slug = $_GET['post'] ?? null;
if ($slug) {
    [$status, $res] = blog_get('/posts/' . rawurlencode($slug));
    if ($status === 404) { http_response_code(404); exit('Not found'); }
    $post = $res['data'];
    echo '<title>' . htmlspecialchars($post['seo']['metaTitle']) . '</title>';
    echo '<meta name="description" content="' . htmlspecialchars($post['seo']['metaDescription']) . '">';
    if ($post['seo']['canonicalUrl']) echo '<link rel="canonical" href="' . htmlspecialchars($post['seo']['canonicalUrl']) . '">';
    foreach ($post['seo']['jsonLd'] as $block) echo '<script type="application/ld+json">' . json_encode($block) . '</script>';
    echo '<h1>' . htmlspecialchars($post['title']) . '</h1>' . $post['html'];
} else {
    [, $res] = blog_get('/posts?perPage=20');
    foreach ($res['data'] as $p) {
        echo '<h2><a href="?post=' . rawurlencode($p['slug']) . '">' . htmlspecialchars($p['title']) . '</a></h2>';
        echo '<p>' . htmlspecialchars($p['excerpt']) . '</p>';
    }
}
```

Cache responses (for example in APCu or a file for 5 minutes) so every page view does not call the API.

### Static sites (Astro, Hugo, Eleventy, Gatsby)

At build time, page through `/public/v1/posts?include=content&perPage=50` until `page * perPage >= total`, write one
page per post, then rebuild when a webhook arrives (below).

## Webhooks: refresh your site the moment a post changes

In the dashboard, **Websites → (your site) → Publishing → Add webhook** takes your endpoint URL and shows a signing
secret (`whsec_…`). BlogEngine then sends a `POST` with a JSON body for every change:

| Event | Sent when |
|---|---|
| `article.published` | A post goes live |
| `article.updated` | A live post is edited or published again |
| `article.unpublished` | A post is unpublished or deleted |

Headers: `X-BlogEngine-Event`, `X-BlogEngine-Delivery` (unique id), `X-BlogEngine-Timestamp` (Unix seconds) and
`X-BlogEngine-Signature: sha256=<hex>`.

The body:

```json
{
  "event": "article.published",
  "deliveryId": "5b1c…",
  "occurredAt": "2026-11-18T09:30:00.000Z",
  "post": {
    "id": "8d3f0c7e-…", "title": "…", "slug": "kubernetes-cost-optimization",
    "canonicalUrl": "https://example.com/blog/kubernetes-cost-optimization",
    "metaTitle": "…", "metaDescription": "…", "keyword": "…", "tags": ["kubernetes"],
    "html": "<h2>…</h2>…", "markdown": "# …", "jsonLd": [],
    "coverImage": null
  }
}
```

`coverImage`, when present on `article.published`, carries the image itself as `{ contentType, alt, width, height, dataBase64 }`.

**Verify every request** before trusting it. The signature is an HMAC-SHA256 of `"<timestamp>.<raw body>"` with your
secret. Reject anything older than 5 minutes.

```ts
// Next.js: app/api/blog-webhook/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { revalidateTag } from "next/cache";

export async function POST(req: Request) {
  const raw = await req.text();
  const ts = Number(req.headers.get("x-blogengine-timestamp"));
  const sig = req.headers.get("x-blogengine-signature") ?? "";
  if (!ts || Math.abs(Date.now() / 1000 - ts) > 300) return new Response("stale", { status: 400 });
  const expected = "sha256=" + createHmac("sha256", process.env.BLOG_WEBHOOK_SECRET!).update(`${ts}.${raw}`).digest("hex");
  const ok = expected.length === sig.length && timingSafeEqual(Buffer.from(expected), Buffer.from(sig));
  if (!ok) return new Response("bad signature", { status: 401 });

  revalidateTag("blog"); // the fetches in lib/blog.ts carry this tag
  return new Response(null, { status: 204 });
}
```

```php
<?php
$raw = file_get_contents('php://input');
$ts  = (int) ($_SERVER['HTTP_X_BLOGENGINE_TIMESTAMP'] ?? 0);
$sig = $_SERVER['HTTP_X_BLOGENGINE_SIGNATURE'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $ts . '.' . $raw, getenv('BLOG_WEBHOOK_SECRET'));
if (abs(time() - $ts) > 300 || !hash_equals($expected, $sig)) { http_response_code(401); exit; }
// clear your blog cache here
http_response_code(204);
```

Answer with any `2xx` quickly; do slow work after responding. `article.published` is retried with backoff if your
endpoint fails; `article.updated` and `article.unpublished` are sent once. The dashboard keeps a delivery log.

## SEO checklist

- [ ] Each post is served at its `seo.canonicalUrl` (or you changed the website's blog path to match your routes).
- [ ] `<title>` = `seo.metaTitle`; `<meta name="description">` = `seo.metaDescription`; `<link rel="canonical">` = `seo.canonicalUrl`.
- [ ] Every `seo.jsonLd` block is in the page as `<script type="application/ld+json">`.
- [ ] One `<h1>` per page (the title); the body `html` brings its own `<h2>`/`<h3>` structure.
- [ ] Posts are rendered on the server or at build time, not only in the browser.
- [ ] `sitemap.xml` is served from your domain and listed in your `robots.txt`.
- [ ] Optional: `rss.xml` linked with `<link rel="alternate" type="application/rss+xml">`; `llms.txt` at your domain root.
- [ ] Pages are cached and refreshed on webhooks.

## Checklist for AI agents integrating this API

1. Ask the site owner for a public key (`be_pub_…`) and store it as the environment variable `BLOG_API_KEY`. Never
   commit it to the repository.
2. Detect the framework. Use the matching recipe above (Next.js, PHP, static build, or plain HTML for site builders).
3. Create a list page (`/blog`) and a post page (`/blog/{slug}`) that match the website's blog path in BlogEngine.
4. Fetch on the server with caching (about 5 minutes). Handle `404` as not found and `429` by backing off.
5. Output `title` as `<h1>`, then `html`; add the SEO tags and JSON-LD from `seo`.
6. Add pagination from `meta`, and optionally tag/category pages (`?tag=`, `?category=`) and search (`?q=`).
7. Re-serve `sitemap.xml` (and optionally `rss.xml` and `llms.txt`) from the site's own domain.
8. Optional: add a webhook endpoint that verifies the signature and refreshes the cache.
9. Test: a known slug renders with the right `<title>` and canonical; an unknown slug returns 404.

## Support

Questions or problems: sign in at https://app.vox.bd and use the dashboard, or see the pricing and plan limits at https://vox.bd/pricing.
