# API reference

Every `/api/v1/*` endpoint requires a Bearer token checked against scoped tokens in `api_tokens` (with legacy `READ_TOKEN` fallback only when zero active token rows exist), rate-limited via `API_LIMIT`, and logged to `api_audit_log`.

## Scoped authentication and rate limits

Tokens carry one of three hierarchical scopes: `read`, `write`, or `admin`. Missing or invalid tokens return `401`, insufficient scope returns `403`, and throttled callers return `429`.

```sh
curl -sS -H "Authorization: Bearer $READ_TOKEN" https://example.com/api/v1/counts?days=7
```

> Scope: READ | Vars: $READ_TOKEN, example.com | Expect: HTTP 200 (JSON with from, edge[], and beacon[])

## Read routes (TokenScope::Read)

Bounded list endpoints return truncated: true whenever their query cap is reached (5,000 rows on views, 50,000 rows on internal, and 500 rows on posts).

| Code | Symbol | Trigger | Meaning | Next move |
| --- | --- | --- | --- | --- |
| GET | /api/v1/counts | days (default 7) | Returns from, edge[], beacon[], and beacon_by_day[] series. | Start daily rollups here before paging raw views. Refs: #status-401, #status-429 |
| GET | /api/v1/citations | days (1..90), limit (1..200), state, meta=1 | Joins verified retrieval/training reads (.md twins folded) with confirmed and likely AI referrals per page. | Pass ?meta=1 for ledger provenance or ?state=zero-click-absorption to isolate unlinked pages. Refs: #api-counts, #status-401 |
| GET | /api/v1/campaigns | days (1..90), limit (1..200), channel, campaign | Returns registered /go/ links plus edge_clicks, preview_bots, beacon_visits, and null-safe landing_rate. | Filter ?channel= or ?campaign= to inspect dark-social drop-off rates. Refs: #api-counts, #status-401 |
| GET | /api/v1/hits | days, limit (max 500) | Returns raw aggregated edge and beacon hit rows up to limit. | Keep limit bounded so agent context avoids bloat. Refs: #api-views |
| GET | /api/v1/internal | days (default 7) | Returns from, truncated (50k cap), and internal[] referrer routes. | Narrow days window when truncated is true. Refs: #status-429 |
| GET | /api/v1/views | days or day=YYYY-MM-DD | Returns from, truncated (5k cap), and per-page views[] rows. | Switch to single day=YYYY-MM-DD when truncated is true. Refs: #api-links |
| GET | /api/v1/links | day=YYYY-MM-DD | Returns component outbound and internal link clicks per view. | Pass explicit YYYY-MM-DD date matching your target window. Refs: #api-components |
| GET | /api/v1/components | day=YYYY-MM-DD | Returns component interaction telemetry attached to page views. | Inspect active island click and interaction breakdowns by day. Refs: #api-links |
| GET | /api/v1/tools | days, tool | Returns edge-proxied tool invocation outcomes and status counts. | Filter by tool name to audit specific utility endpoints. Refs: #api-health |
| GET | /api/v1/geo | days (default 7) | Returns unlinked daily geo_hits (country, region, city, n). | Note geo rows are intentionally unlinked from visitor identity. Refs: #api-privacy |
| GET | /api/v1/goals | none | Returns up to 200 configured conversion goals. | Read existing goals before issuing a POST write. Refs: #api-write-goals |
| GET | /api/v1/posts | path, label | Returns posts[] metadata and truncated (500 cap) indicator. | Pass path to compute Day 1/7/30 scorecard trajectories. Refs: #api-counts |
| GET | /api/v1/privacy | none | Returns live config.raw_ip_opt_in and active privacy rows. | Verify Worker privacy stance matches public disclosure. Refs: #api-health |
| GET | /api/v1/health | none | Returns classifier canary report and Cloudflare free-plan limits snapshot. | Poll first if beacon counts look stale or quota alarms fire. Refs: #status-401, #status-429 |

## Write routes (TokenScope::Write)

Write endpoints accept Idempotency-Key headers persisted in D1 idempotency_keys. Replays return 200 with x-idempotent-replay: true; reusing the same key on a different route returns 409.

| Code | Symbol | Trigger | Meaning | Next move |
| --- | --- | --- | --- | --- |
| POST | /api/v1/goals | { name, kind, target } + write scope | Upserts conversion goal definition in D1 goals table. | Include unique Idempotency-Key header on every retryable call. Refs: #status-403, #status-409 |
| POST | /api/v1/import | { source: umami\|plausible, rows[<=500] } | Upserts imported daily aggregates into D1 visits table. | Chunk exports to <=500 rows per batch with per-batch Idempotency-Key. Refs: #status-403, #status-409 |
| POST | /api/v1/campaigns | { channel, slug, target_path, utm_*, status } | Upsert or archive a /go/<channel>/<slug> link. | Pass Idempotency-Key; bad targets return 400. Refs: #status-403, #status-409 |

## Auth, scope, and replay status codes

| Code | Symbol | Trigger | Meaning | Next move |
| --- | --- | --- | --- | --- |
| 401 | Unauthorized | Missing, malformed, or expired Bearer token | Worker rejected token against api_tokens and legacy READ_TOKEN. | Check Authorization header and active token rows. Refs: #api-health |
| 403 | Forbidden | Valid read token sent to a TokenScope::Write route | Insufficient token scope; expected state after kokumi handover. | Confirm least-privilege read posture or supply a write token. Refs: #api-write-goals |
| 409 | Conflict | Idempotency-Key reused against a different endpoint or contract | D1 idempotency_keys rejected cross-route key reuse. | Generate a fresh UUID per route and operation. Refs: #api-write-import |
| 429 | Rate Limited | Caller exceeded Worker API_LIMIT sliding rate cap | Throttled before querying D1 to protect free-plan budget. | Back off exponentially and widen polling intervals. Refs: #api-counts |

## Public beacon routes

POST `/api/hit`, `/api/engaged`, and `/api/events` accept unauthenticated browser beacons with CORS headers and respond `204`. Static beacon script lives at `GET /visit.js`.

## Related

- [CLI reference](/docs/cli)
- [Self-hosting guide](/docs/self-hosting)
- [Data and privacy ledger](/docs/data-and-privacy)