# Axion Bodycam API — AI implementation reference Purpose: implement Axion bodycam integration in an external CAD or department website. This document describes the implemented external API, not the native recording protocol or a proposed roadmap. API major version: v1. OpenAPI document version: 1.0.0. ## Sources and discovery - Human guide: /docs/bodycam - This reference: /llms-full.txt - Discovery index: /llms.txt - Machine-readable contract: /docs/openapi.json - Downloadable backend TypeScript helper: /docs/axion.ts - Authenticated sandbox UI: /developers/playground - API deployment's runtime contract: {API_ORIGIN}/api/external/openapi.json Fetch the OpenAPI contract alongside this reference for full field and response schemas. The production API_ORIGIN is https://getaxion.xyz, and the versioned base URL is https://getaxion.xyz/api/external/v1. For sandbox integrations, use the sandbox project's base_url; for self-hosted deployments, use the API origin provided by the operator. Do not assume the website origin equals the API origin for those deployments. Source files in this repository: server/src/integrations/contract.ts, server/src/http/external*.ts and server/src/integrations/*.ts. Regenerate the contract from server/ using npx tsx scripts/generate-external-contract.mts, then run npm run docs:generate from web/ to refresh the public guide, AI reference, contract and SDK bundle. ## Architecture and authorization 1. Website browser calls your authenticated backend. 2. Your backend checks that website user's CAD/community permissions. 3. Your backend calls {API_ORIGIN}/api/external/v1 using Authorization: Bearer AXION_KEY. 4. Your backend returns only authorized data or a scoped embed_url to the browser. 5. The browser embeds Axion's private iframe and completes the postMessage handshake below. Keep AXION_KEY on the backend in environment variables or a secret store. Never put it in NEXT_PUBLIC_* variables, browser code, browser storage, URLs, analytics, examples or logs. The installation credential does not authenticate individual website users. Validate the user's requested member/case/clip on YOUR backend before invoking Axion. Do not create an unauthenticated arbitrary Axion proxy. Axion omits Access-Control-Allow-Origin on /api/external/* in every environment, including development. Direct cross-origin browser fetch calls fail CORS even with a valid key and all scopes. Allowed embed origins authorize private viewers only; they do not enable browser API CORS, validate the key or grant scopes. External API requests must run on your backend. The community owner creates and approves an installation under Community settings → Integrations → Bodycam API. Register scopes and exact parent embed origins. API deployment must enable AXION_EXTERNAL_API_ENABLED=true; otherwise external routes are not registered. No public docs login is needed, but sandbox and community setup require an Axion account. Live credentials start ax_live_; sandbox credentials start ax_test_. Opposite-environment keys, human sessions and native device tokens are rejected. Credentials expire after 90 days. Rotate by issuing a replacement, updating your backend, then revoking the old key. Owner changes require approval from the current owner. Revocation, suspension and scope/origin removal also affect active viewers. ## Request rules - JSON body: Content-Type: application/json. - Encode every variable path segment with encodeURIComponent. - All timestamps and durations use milliseconds unless explicitly stated otherwise. Webhook signature timestamp uses Unix seconds. - All mutations require Idempotency-Key (non-empty, max 128 characters), EXCEPT POST /webhook-endpoints/{endpoint_id}/verify. - Retries use the SAME installation, method, path, action key and JSON inputs. Successful stored responses last 24 hours across restarts and credential rotation. Changed inputs under the same key return 409 idempotency_conflict. - New logical action or reconciled revision update: use a NEW key. New viewer session: use a NEW key. Replaying viewer creation does not renew it. - After 24 hours, reconcile state before retrying a potentially duplicated action. - Honor Retry-After on 429 when supplied. Otherwise use bounded backoff. Member capture cooldown is 10 seconds across all installations in a community. - When rate limiting is enabled: installation metadata 120/minute, capture 10/minute; community metadata 360/minute, capture 30/minute. RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset report budgets. X-Axion-Environment identifies live/test. - Paginated reads /members, /unit-mappings, /clips, /evidence-links accept limit 1–100 (default 50) and opaque cursor. Response: {items, next_cursor}; stop when next_cursor is null. Keep cursor opaque. - /events uses after instead of cursor. Webhook endpoint/delivery lists have no pagination cursor. - Preserve unknown fields; handle unknown future states without crashing. Do not invent unsupported endpoints or media URLs. ## Scopes bodycams:read — member roster and current bodycam status. bodycams:preview — private live JPEG preview viewers. bodycams:capture — recent-buffer capture and result polling. units:read — read assignments; additionally required whenever capture/preview/CAD events select external_unit_id. units:write — create, revise and end unit assignments. clips:read — ready retained clip metadata, clip playback, evidence reads and timeline footage. clips:original:read — additional explicit grant to access original footage with edit metadata; does not replace clips:read. evidence:write — link/unlink footage; also required for case-associated capture together with clips:read. timeline:read — case chronology and timeline viewers; clips:read adds footage. timeline:write — append/correct/tombstone CAD events. events:read — durable feed and callbacks; event delivery ALSO requires the event's resource scopes. ## Endpoint inventory All paths below are relative to /api/external/v1. Success envelopes are significant. | Method and path | Scope | Success | |---|---|---| | GET /installation | credential | 200 {installation, features, limits} | | GET /members | bodycams:read | 200 {items, next_cursor} | | GET /members/{member_id}/bodycam | bodycams:read | 200 bodycam object (no wrapper) | | GET /unit-mappings | units:read | 200 {items, next_cursor} | | GET /unit-mappings/{external_unit_id} | units:read | 200 {unit} | | PUT /unit-mappings/{external_unit_id} | units:write | 200 {unit} | | DELETE /unit-mappings/{external_unit_id} | units:write | 200 {unit} (active:false) | | GET /clips | clips:read | 200 {items, next_cursor} | | GET /clips/{clip_id} | clips:read | 200 {clip} | | POST /capture-requests | bodycams:capture | 202 {request} | | GET /capture-requests/{request_id} | bodycams:capture | 200 {request} | | POST /viewer-sessions | resource-dependent | 201 {session, embed_url} | | POST /evidence-links | evidence:write + clips:read | 201 {link} | | GET /evidence-links | clips:read | 200 {items, next_cursor} | | DELETE /evidence-links/{link_id} | evidence:write | 200 {removed:true} | | GET /cases/{external_case_id}/timeline | timeline:read | 200 {external_case_id, revision, updated_at, events, footage} | | POST /cases/{external_case_id}/events | timeline:write | 201 {event} | | PATCH /cases/{external_case_id}/events/{event_id} | timeline:write | 200 {event} | | DELETE /cases/{external_case_id}/events/{event_id} | timeline:write | 200 {event} (deleted:true) | | GET /events | events:read | 200 {items, next_cursor, replay_window_ms} | | GET /webhook-endpoints | events:read | 200 {items} | | POST /webhook-endpoints | events:read | 201 {endpoint, signing_secret} | | POST /webhook-endpoints/{endpoint_id}/verify | events:read | 200 {verified:true} | | DELETE /webhook-endpoints/{endpoint_id} | events:read | 204 (no response body) | | GET /webhook-deliveries | events:read | 200 {items} | | POST /webhook-deliveries/{delivery_id}/replay | events:read | 202 {accepted:true} | ## Member identity and status GET /members returns {id, roblox_user_id, name, bodycam} items. Filter with roblox_user_id if needed. A member ID is an Axion user ID belonging to this installation's community, not a Roblox ID. Do not enroll an outside account via this API. Bodycam fields: member_id, status, observed_at, stale_after_ms, in_community, buffer_ms, preview_available, capture_available, unavailable_reason. Status: offline | unknown | idle | recording. Current freshness threshold: 45000 ms. Gate buttons on preview_available/capture_available; recording alone does not imply eligibility. Presence unknown is not proof of offline status. Re-check on failure since status can change after a read. ## Unit mapping PUT /unit-mappings/{external_unit_id} accepts EXACTLY ONE member_id or roblox_user_id. Optional callsign and badge_number max 48 characters in runtime; department.external_id max 128, department.name max 80. Existing active assignment requires expected_revision equal to the current unit revision. This is a replacement-style assignment: omitted optional labels become empty strings, so send labels you intend to retain. One active unit per member per installation; maximum 500 mappings. DELETE ends the assignment and returns its new revision. Example body: {"member_id":"AXION_MEMBER_ID","callsign":"A-12","badge_number":"104","department":{"external_id":"pd","name":"Police"}} Filters for GET /unit-mappings: member_id, callsign, department (external department ID). Historical accepted labels are retained by captures/evidence/events. Reassignment does not redirect an already-open preview. ## Capture workflow POST /capture-requests body: EXACTLY ONE member_id or external_unit_id; optional pre_ms (integer 1000–1800000, default 60000), external_case_id, external_actor_id. Selecting external_unit_id adds units:read. Supplying external_case_id adds evidence:write and clips:read. Example: {"external_unit_id":"officer-104","pre_ms":60000,"external_case_id":"case-82"} Response 202: {"request":{"id":"REQUEST_ID","status":"accepted","requested_pre_ms":60000,"effective_pre_ms":5000,"expires_at":1791216030000,"clip_id":null}}. IDs, times and effective duration here are illustrative. Persist request.id; poll GET /capture-requests/{request_id} with bounded backoff or process capture_request.updated events. States: accepted, delivered, acknowledged, upload_queued, ready, failed, expired. Terminal: ready/failed/expired. Only verified completed upload establishes ready; an acknowledgment is NOT a playable clip. Read request.failure_code on failure. Queued uploads retain request identity across reconnects. The 30-second instruction deadline does not mean all uploads must finish within 30 seconds. Capture requires a fresh recording device, current verified presence in this community, an online native connection, and capabilities capture_result_v1 and community_capture_v1. effective_pre_ms is clamped to the buffer accumulated during verified presence. This requests past buffered footage, not arbitrary historical video or a future recording. ## Clips and evidence GET /clips filters: member_id, from, to, event_type; times are epoch ms. Only ready, retained clips belonging to this community are available. GET /clips/{clip_id} returns metadata, NOT a permanent MP4 URL. Use a clip viewer for playback. Check playback_available. Edited clips require clips:original:read until a rendered derivative exists. Original footage is unredacted: honor original_footage and label it accurately. Do not claim browser edit overlays protect source bytes. POST /evidence-links: {"clip_id":"CLIP_ID","external_case_id":"case-82"}. GET /evidence-links requires external_case_id query. DELETE uses the link's Axion id and unlinks without deleting video. unavailable evidence can return only id, external_case_id, available:false. Always test available before using clip_id. Links do not extend retention. ## Private viewer workflow POST /viewer-sessions requires origin and resource_type: - Clip: {"resource_type":"clip","clip_id":"CLIP_ID","origin":"https://cad.example"}; scope clips:read. - Preview: {"resource_type":"preview","external_unit_id":"officer-104","origin":"https://cad.example"}; scopes bodycams:preview + units:read. Alternatively use member_id without units:read. Exactly one member/unit selector. - Timeline: {"resource_type":"timeline","external_case_id":"case-82","origin":"https://cad.example"}; scope timeline:read, plus clips:read for footage. Preview quality is `low` (default, up to 640×360 JPEG at 65%) or `high` (up to 1280×720 JPEG at 85%). Both refresh about once a second, preserve aspect ratio, never upscale, and have no audio. Add `"quality":"high"` to the preview creation body; `session.quality` confirms the mode. High requires the community's Power plan and device capability live_view_quality_v1; failures are 403 plan_required or 409 client_upgrade_required. Power is checked on creation/retry, viewer page, redemption and each frame request, so downgrade immediately blocks high sessions. Low remains available under existing preview rules. GET /installation features includes live_view_low_quality and includes live_view_high_quality only on Power. Quality is fixed per session; create a new session and key to switch. Quality is invalid for clip/timeline. Older stored preview sessions without quality use low. Separate deployment byte budgets charge delivered frames: low 8 MiB/minute, high 64 MiB/minute. Frame caches and demand coalescing are separated by quality. origin must match a registered exact scheme/host/port, with no path or trailing slash. Production requires HTTPS. Non-production also supports HTTP localhost/127.0.0.1. For example, https://relaycad.net and https://www.relaycad.net are distinct parent origins; relaycad.net alone is invalid. Send the actual registered parent origin in the viewer request's JSON origin field. Origin registration is not checked by GET /installation or ordinary metadata reads. Response: {session:{id,resource_type,expires_at,bootstrap_expires_at},embed_url}. Bootstrap fragment redeems once within 60 seconds; session expires after 5 minutes. Request a new session using a new key for renewal or reopening. Maximum 5 active previews per installation; requests share a deployment byte budget. Only embed URLs from the configured trusted API origin, and preserve the fragment. Register the listener before assigning src. Give the iframe a title and usable dimensions. If the parent has CSP, allow the API origin in frame-src. Do not log/store the URL as a public link. A private viewer is not a public share. ```js const iframe = document.querySelector('#bodycam-viewer'); const apiOrigin = new URL(configuredApiOrigin).origin; if (new URL(embedUrl).origin !== apiOrigin) throw new Error('Unexpected viewer origin'); function onMessage(event) { if (event.source === iframe.contentWindow && event.origin === apiOrigin && event.data?.type === 'axion.viewer.ready') { iframe.contentWindow.postMessage({ type: 'axion.viewer.open' }, apiOrigin); } } window.addEventListener('message', onMessage); iframe.src = embedUrl; // On component unmount: window.removeEventListener('message', onMessage). ``` Preview is JPEG frame polling inside the iframe, not WebRTC. Current authorization and device freshness are rechecked. Scope removal, credential revocation, resource expiry or unavailable presence can invalidate playback immediately. Timeline child clips must remain linked and authorized. ## Incident timeline A first CAD event, evidence link or associated capture creates the case. There is no POST /cases endpoint. Case IDs are installation-scoped. POST /cases/{case_id}/events requires external_event_id (unique within this case and installation), type (max 64 chars), occurred_at (epoch ms, no more than one day in the future). Optional note (max 2000 chars) and member_id OR external_unit_id. The latter requires units:read. Example: {"external_event_id":"dispatch-1","type":"dispatch","occurred_at":1791216000000,"note":"Units dispatched"}. PATCH/DELETE use Axion's event.id, not external_event_id, and require expected_revision in JSON. PATCH can change note/occurred_at. Only source:cad entries are editable. DELETE tombstones; prior bounded revision history persists. GET /cases/{case_id}/timeline returns ordered events, revision, updated_at and footage. Optional revision query detects change with 409 timeline_changed. Re-fetch and reconcile after a late upload/correction. Footage entries can be {link_id,available:false}; do not assume clip or timestamps exist. Without clips:read footage is empty and event clip IDs are hidden. start_ms/end_ms can be null. timing_quality is approximate or unknown; never claim exact synchronized footage for unknown times. ## Event feed and callbacks GET /events?after=CURSOR&limit=50 returns {items,next_cursor,replay_window_ms}. Save next_cursor even when items is empty due to scope filtering. Replay window: 7 days. Expired/foreign cursor: 410 cursor_expired; fetch fresh resource snapshots, then restart the feed. Handle duplicates and out-of-order updates using event id and resource_revision. Subscriptions: bodycam.status_changed, capture_request.updated, clip.ready, clip.unavailable, evidence_link.created, evidence_link.deleted, unit_mapping.updated, unit_mapping.removed, case.timeline_updated. Status events describe meaningful changes rather than every heartbeat. POST /webhook-endpoints: {"url":"https://cad.example/hooks/axion","events":["capture_request.updated","clip.ready"]}. Save signing_secret (whsec_ + base64 secret) securely. Configure receiver before POST /webhook-endpoints/{endpoint_id}/verify. Verify the signed body {"type":"webhook.verification","challenge":"CHALLENGE"} and echo its top-level challenge in Axion-Webhook-Challenge response header. Normal events start only after verification. Signature headers: webhook-id, webhook-timestamp, webhook-signature. Compute HMAC-SHA256 with the base64-decoded secret after whsec_, over id + '.' + timestamp + '.' + RAW_BODY. Compare against base64 signatures labeled v1 using a timing-safe comparison. Enforce a bounded timestamp tolerance (e.g. 5 minutes). Verify raw bytes before parsing/acting. Retries retain event id but use a fresh timestamp/signature. Deduplicate by id; acknowledge quickly with 2xx. Callbacks are at least once, with retry backoff up to 24 hours/15 attempts. URL must be public HTTPS on port 443, no credentials/fragment. Private/reserved/loopback/link-local addresses, mixed DNS and redirects are denied; DNS is validated per attempt. Max 5 endpoints. Failed callbacks do not block capture. GET /webhook-deliveries returns bounded diagnostics; POST /webhook-deliveries/{delivery_id}/replay requires current authorization and an action key. ## Error handling Failure body: {"error":{"code":"unauthorized","message":"This integration API key has expired. Keys expire after 90 days; issue a new credential in Community settings > Integrations > Bodycam API and replace the key stored on your backend."}}. Branch on HTTP status and code, not message. Messages explain the cause and recovery step; display or preserve them rather than replacing all failures with an invalid-key message. Authentication distinguishes header/key format, environment, unrecognized/expired/revoked keys, disabled API access and missing/revoked installations or communities. Expiry/revocation details require a verified secret; unknown keys and incorrect secrets share one message. Approval messages distinguish owner changes from account suspension, and capture/preview messages explain device/presence/recording/buffer eligibility. Common codes (not exhaustive): - 400 bad_input: validate JSON/selectors, required action key, integer duration; bad_cursor: invalid list cursor. - 401 unauthorized: missing, malformed, expired, revoked or wrong-environment credential, or an unavailable installation on the receiving deployment. - 403 forbidden: missing scope; approval_required: current owner must reapprove; origin_not_allowed: register exact origin. - 404 not_found: outside authorized community/installation, missing, expired or not-ready resource. - 409 device_offline / presence_unknown / outside_community / not_recording / buffer_unavailable: refresh eligibility, wait for recording presence. - 409 client_upgrade_required: update native client. - 409 preview_unavailable: device no longer eligible; edited_clip_unavailable: derivative absent and original not granted. - 409 revision_conflict / timeline_changed: read current state, reconcile, use new action key for changed input. - 409 idempotency_conflict: restore original input or use a new key for an intentional new action. - 409 unit_already_assigned: end/revise previous assignment; callback_unverified: check signature/challenge receiver. - 410 cursor_expired: resnapshot; viewer_expired or 401 viewer_revoked: obtain new authorized session. - 429 rate_limited / capture_cooldown / viewer_limit: respect timing and reduce demand. ### Connection diagnostics Do not map all failures to “invalid key” or “copy the key again.” Trace the failing request and distinguish authentication, scopes, owner approval, embed origins, network/CORS, rate limits and service failures. 1. Check whether the call runs in the browser; move external API calls to an authenticated, permission-checked backend route. 2. Call GET /installation from that backend with its stored key. This endpoint requires a valid credential and an available, approved installation, but no resource scopes or embed origins. A 200 verifies that request's authentication only. 3. Check the API URL and environment pairing, stored-key retrieval, exact Authorization: Bearer construction, and proxy header forwarding. Do not include quotes, duplicate Bearer prefixes or embedded whitespace. Avoid redirects; use the final API origin. The TypeScript helper accepts the origin and appends /api/external/v1, so do not pass the versioned base URL to it. 4. Keep the upstream method, path, status and error.code/error.message in restricted diagnostics, excluding credentials, Authorization headers, capability URLs and full payloads. A timeout, network/CORS failure or non-JSON proxy response is not evidence that Axion rejected the credential. 5. If /installation succeeds, inspect the original operation's status/code for its scope, origin or resource failure. A correct stored key can still fail if the transmitted value differs or the receiving deployment lacks the credential/installation records. Recopying it does not fix those conditions. ## Sandbox and implementation acceptance Use /developers/playground for an isolated developer project, its sandbox base_url and ax_test_ installation. Load sample creates fictional recording/idle/offline units and clips. No native recorder or ER:LC key is needed. Live keys/resources do not work in sandbox. Reset invalidates sample resources; refresh IDs instead of caching them across reset. The operator must configure a separate sandbox process/storage/master key and the regular API's bridge. Sandbox availability is a deployment prerequisite, not guaranteed by public docs. A missing bridge should produce a setup message, not a fallback to production footage. Verify: own-site authorization; backend-only credential; correct API origin; correct scopes including unit selectors; opaque pagination; stable mutation retry keys; capture accepted-to-ready with failure UI; clip expiry/edited restrictions; exact-origin iframe handshake; fresh viewer renewal; revision conflicts; signed webhook verification/deduplication; cursor expiry recovery; no secret or capability URL logging. Use actual OpenAPI types, and distinguish sandbox tests from verified live capture. The downloadable Axion TypeScript helper accepts the API ORIGIN, adds /api/external/v1, uses fetch with a 15-second timeout and redirect rejection, and throws AxionError with status/code/retryAfter. It does not automatically retry/poll. Methods: request, mapUnit, capture, captureResult, viewer, appendEvent, linkEvidence.