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/loginreturns access/refresh pair;POST /admin/v1/auth/refreshrotates the access token;POST /admin/v1/auth/logoutrevokes 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-workerandcms-apivia 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 identifiermessage: human-readable summarydetails: 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_idand role permissions. - Public block: resolves tenant by host/route mapping first;
site_idmay 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=60ETag: hash of effective published payloadLast-Modified: based on latest content/template/settings update in resolved payloadVary: 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:
- Payload includes explicit
dataobject with primitive and nested fields used by templates. - Placeholders use dot notation (
{{content.title}},{{site.name}}). - Missing keys resolve to empty string (or configurable strict mode in worker), never crash rendering.
- API response includes optional
meta.bindingslist 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.yamldocs/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 ontopublic_v2_appinroutes/v2/__init__.py, mounted inmain.py. - Schemas:
src/cms_api/public/schemas/v2.py(strictextra="forbid"). - Store: the same
SqlPublicStore(prod) /MemoryPublicStore(tests) gain the v2 methods; shared payload shaping lives instore/v2_common.py. - Resolver:
resolve_site_any(site)triesint(site)->sites.idfirst, then the v1acronym OR domainpredicate. All v2 endpoints resolve through it. - Caching: every DB-backed endpoint emits
ETag,Last-Modified, andCache-Control: public, s-maxage=<n>, stale-while-revalidate=<2n>, and honorsIf-None-Match/If-Modified-Sincewith a 304. Per-endpoints-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 synchronousdef, mirroring v1. feature_flagsis returned as an empty object: the v3site_settingsschema has nofeature_flagscolumn. Populate once a column or derivation exists.meta.etagin the JSON body is leftnull; the authoritative ETag is the HTTPETagheader (computing it into the body would be self-referential).searchuses aLIKE/ilikesubstring match, not MySQLMATCH ... AGAINST: no fulltext index is declared inhq.sql_models. The list test skips withpytest.skipif a store cannot answer the search kind.