Skip to content

cms-api API architecture (AISD-90)

Purpose

This document defines the API contract boundaries for cms-api so downstream implementation work can proceed safely and independently:

  • Block A (/admin/v1) -- authenticated admin/editorial mutations
  • Block B (/public/v1) -- read-mostly public content delivery

It is intentionally design-first: endpoint behavior and payload contracts are fixed here; business implementation lands in AISD-91/AISD-92.

Block boundaries

flowchart LR
    subgraph Admin[Block A: /admin/v1]
      A1[Admin UI]
      A2[Editorial tools]
      A3[Publishing workflows]
    end

    subgraph Public[Block B: /public/v1]
      B1[comparison-app]
      B2[cms-worker]
      B3[Public clients]
    end

    AUTH[JWT + Redis session validation]
    API[cms-api]
    DB[(hq.sql_models / cms_db)]
    CACHE[CDN / edge cache]

    A1 --> AUTH
    A2 --> AUTH
    A3 --> AUTH
    AUTH --> API

    B1 --> CACHE --> API
    B2 --> CACHE
    B3 --> CACHE

    API --> DB

URL namespace convention

  • Admin namespace: /admin/v1/...
  • authenticated and role-gated (validate_admin)
  • routes include auth login and editorial/admin resources
  • Public namespace: /public/v1/...
  • unauthenticated read API
  • only published/read-model resources, no mutations
  • Health namespace: /api/status

Versioning rule: breaking changes require new major namespace (/admin/v2, /public/v2). Non-breaking additive changes stay in v1.

Auth model

Block A (/admin/v1)

  • Model: JWT bearer tokens backed by Redis sessions
  • Login flow: POST /admin/v1/auth/login returns access/refresh pair; POST /admin/v1/auth/refresh rotates the access token; POST /admin/v1/auth/logout revokes the session
  • Gate: all admin routes (except login) require valid admin role
  • Session state: token payload references session token; session/user resolved from Redis
  • Token claims: minimal session token reference (token), no large payloads

Block B (/public/v1)

  • Default: public, no end-user auth
  • Optional worker hardening (future): edge token between cms-worker and cms-api via header, validated server-side (not required for AISD-92)
  • No admin/session reuse: Block B must not expose or depend on admin token semantics

API behavior standards

Error shape

All non-2xx responses SHOULD follow this JSON shape:

{
  "error": {
    "code": "resource_not_found",
    "message": "Requested site was not found",
    "details": {
      "site_id": 12
    }
  }
}
  • code: machine-stable snake_case identifier
  • message: human-readable summary
  • details: optional structured metadata

Pagination

Collection endpoints SHOULD use cursor pagination (preferred) with fallback page/size support:

  • request: ?limit=20&cursor=<opaque>
  • response envelope includes next_cursor
  • stable ordering is required for deterministic pagination

Multi-tenant rules (site_id)

  • Every domain resource is tenant-scoped by site_id.
  • Admin block: may read/mutate by explicit site_id and role permissions.
  • Public block: resolves tenant by host/route mapping first; site_id may appear in internals but should not be required from public clients unless endpoint is explicitly site-keyed.

Caching strategy for Block B

Block B responses are cache-first and immutable-by-version where practical.

Recommended defaults:

  • Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=60
  • ETag: hash of effective published payload
  • Last-Modified: based on latest content/template/settings update in resolved payload
  • Vary: include tenant/language dimensions (Host, Accept-Language) where applicable

Invalidation model:

  • publish/unpublish/template change emits cache purge event for affected routes
  • fallback TTL expiry guarantees eventual consistency if purge is missed

cms-worker placeholder binding contract

Block B payloads must support deterministic placeholder interpolation by cms-worker.

Contract rules:

  1. Payload includes explicit data object with primitive and nested fields used by templates.
  2. Placeholders use dot notation ({{content.title}}, {{site.name}}).
  3. Missing keys resolve to empty string (or configurable strict mode in worker), never crash rendering.
  4. API response includes optional meta.bindings list for preflight tooling/debug.

Example payload fragment:

{
  "site": {"name": "Example", "domain": "example.com"},
  "content": {"title": "Article title", "slug": "article-title"},
  "meta": {"bindings": ["site.name", "content.title", "content.slug"]}
}

Resource inventory -> table groups

Table mapping follows hq/docs/cms-database.md model groups.

Resource area Block Primary table groups
Auth/session Admin core.users, core.site_users, Redis session store
Site config/settings Admin/Public core.sites, core.site_settings
Templates/blocks Admin/Public template.*
Taxonomy Admin/Public taxonomy.*, lookup tables
Content CRUD/publish Admin/Public content.*, lookup content_status, content_types

WordPress parity checklist (comparison-app needs)

This checklist tracks minimum parity before switching consumers to Block B:

  • [ ] Resolve page/article by slug + site
  • [ ] Navigation/menu model available in payload
  • [ ] SEO fields (title, description, OG image) present
  • [ ] Canonical URL and locale metadata present
  • [ ] Published-state filtering only (no drafts)
  • [ ] Stable cache headers + ETag present
  • [ ] Placeholder-compatible payload shape for cms-worker bindings

Downstream task split

  • AISD-91 -- implement Admin/editorial block (/admin/v1)
  • user/repo wiring, authz boundaries, CRUD/publish endpoints
  • AISD-92 -- implement Public block (/public/v1)
  • read models, slug resolution, cache headers, worker-facing payloads
  • AISD-105 (dependency for full authz) -- RBAC and user-role persistence

OpenAPI artifacts

  • docs/openapi-admin.yaml
  • docs/openapi-public.yaml

These are the source contracts for implementation and review.

Public API v2 (AISD-116)

The v2 surface (/public/v2) is the worker-optimized read API consumed by the cms-cf-worker (designed in AISD-115). It is mounted alongside v1 (/public/v1), which stays in place during rollout and is retired once v2 is live in prod. The canonical request/response shapes live in specs/AISD-115-api-design.md; this section is the repo-side field-to-table mapping that ships with the code.

Layout and conventions

  • Routes: src/cms_api/public/routes/v2/ (one file per endpoint) aggregated onto public_v2_app in routes/v2/__init__.py, mounted in main.py.
  • Schemas: src/cms_api/public/schemas/v2.py (strict extra="forbid").
  • Store: the same SqlPublicStore (prod) / MemoryPublicStore (tests) gain the v2 methods; shared payload shaping lives in store/v2_common.py.
  • Resolver: resolve_site_any(site) tries int(site) -> sites.id first, then the v1 acronym OR domain predicate. All v2 endpoints resolve through it.
  • Caching: every DB-backed endpoint emits ETag, Last-Modified, and Cache-Control: public, s-maxage=<n>, stale-while-revalidate=<2n>, and honors If-None-Match / If-Modified-Since with a 304. Per-endpoint s-maxage / swr: settings 300/86400, pages 300/600, authors 300/600, lists 120/600, sitemap 3600/3600, ping 0 (no cache, no DB).

Endpoints

# Method + path Purpose
1 GET /public/v2/sites/{site}/settings identity + merged settings + light categories/tags + resolved templates + active_template + ads_txt/robots_txt
2 GET /public/v2/sites/{site_id}/pages/{slug} one article + flat SEO + author + breadcrumbs + related; ?version=N reads content_history (gated by X-CMS-Preview)
3 GET /public/v2/sites/{site_id}/authors/{slug} author profile + computed SEO + stats
4 GET /public/v2/sites/{site_id}/lists?kind=... metadata-only cards, cursor-paginated
5 GET /public/v2/sites/{site_id}/sitemap flagged content URLs + static pages, cursor-paginated
6 GET /public/v2/ping liveness, no DB

Field -> table mapping (hq.sql_models)

Settings (/settings):

Field Source
site.{id,acronym,name,domain,default_language,tagline} core.Site (resolved by id, then acronym/domain)
site_settings.* (incl. ads_txt, robots_txt, nav_limit, contact_email, template_style_id, *_html) core.SiteSetting EAV, merge site over site_id=-1
site_settings.categories[] taxonomy.SiteCategory LEFT JOIN lookup.Category (by name)
site_settings.tags[] taxonomy.ContentTag JOIN content.Content JOIN lookup.Tag (DISTINCT, published)
site_settings.templates always {} (AISD-218; override chain dropped)
site_settings.active_template / active_style via template_style_id → template_styles → templates / styles registries

Article page (/pages/{slug}):

Field Source
content.* + flat SEO content.Content (content_type='article', status='published')
content.categories[] / tags[] taxonomy.ContentCategory / taxonomy.ContentTag
author core.Author by content.author_id
seo.structured_data computed from schema_type + the content row
breadcrumbs computed from site.name + first category + title
related[] content.Content self-join via shared content_categories
(?version=N) content.ContentHistory snapshot N, falling through to the live content row for NULL columns

Author (/authors/{slug}): core.Author + a func.count / func.max(published_at) aggregate over content.Content on (site_id, author_id, status).

Lists (/lists): driven by content.Content with a per-kind predicate (show_in_homepage / is_featured / is_trending / category join / author / related overlap / recent / q LIKE on title+description), LEFT JOIN core.Author for author_name / author_image, cursor over offset.

Sitemap (/sitemap): content.Content where is_featured OR show_in_homepage (optionally published_at >= since), plus static-page URLs from site_settings.navigation whose path maps to a lookup.TemplateElement of type='page'.

Known deviations from the AISD-115 design (recorded at implementation)

  • The design's asyncio.gather / async-SQLAlchemy language does not apply: the existing store is synchronous (session_scope() + session.query), so the v2 methods are synchronous def, mirroring v1.
  • feature_flags is returned as an empty object: the v3 site_settings schema has no feature_flags column. Populate once a column or derivation exists.
  • meta.etag in the JSON body is left null; the authoritative ETag is the HTTP ETag header (computing it into the body would be self-referential).
  • search uses a LIKE/ilike substring match, not MySQL MATCH ... AGAINST: no fulltext index is declared in hq.sql_models. The list test skips with pytest.skip if a store cannot answer the search kind.