Setup and architecture
Use this flow: your browser → your authenticated backend → Axion API. Your backend checks the user's CAD permissions before calling Axion. The integration credential represents the installation, not the individual website user. Return only the data that user is allowed to see.
Axion does not return Access-Control-Allow-Origin on /api/external/*, including in development. Direct cross-origin browser requests therefore fail CORS even with a valid key and all permissions. Adding your website to Allowed embed origins only authorizes private viewer embeds; it does not enable browser API calls or change credential authentication. Make external API requests from your backend.
For live preview and playback, your backend creates a private viewer session and returns its embed_url to the authorized browser. The Axion iframe handles media access; your website does not need to implement a recorder or upload footage.
Enable AXION_EXTERNAL_API_ENABLED=true on the API deployment. The community owner creates an installation in Community settings → Integrations → Bodycam API, approves its scopes, registers exact embed origins, and copies a credential. API access is disabled by default. No pricing or retention changes are introduced.
Keep ax_live_… credentials on the CAD or website's backend. Human session and native device tokens are rejected by the external API. Rotate by issuing a replacement, updating the integration, then revoking the old key. Keys expire after 90 days. Revocation, scope removal, suspension and owner changes apply to existing viewer sessions as well as new calls; a new owner must approve the installation again.
Set AXION_API=https://getaxion.xyz for production and keep the credential in AXION_KEY. 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. The website and API origins can differ.
The contract is available at /api/external/openapi.json on an enabled API, and in external-openapi.json. A dependency-free server-side TypeScript helper is in sdk/typescript/axion.ts.
Quickstart
These examples use POSIX shell syntax; on Windows use curl.exe with your shell's environment-variable syntax. IDs and domains are placeholders. First check your installation, scopes and limits:
curl "$AXION_API/api/external/v1/installation" \
-H "Authorization: Bearer $AXION_KEY"
Run this check from your integration backend or a terminal. GET /installation requires a valid credential and an available, approved installation, but no resource scope or registered embed origin. A 200 confirms authentication for that request; it does not prove a later capture or viewer request will succeed. If it fails, follow Connection diagnostics.
Read community members:
curl "$AXION_API/api/external/v1/members" \
-H "Authorization: Bearer $AXION_KEY"
Resolve a member's Axion ID from this installation's community. A unit assignment accepts exactly one member_id or linked roblox_user_id; it never enrolls an outside account.
curl "$AXION_API/api/external/v1/unit-mappings/officer-104" \
-X PUT -H "Authorization: Bearer $AXION_KEY" \
-H 'Content-Type: application/json' -H 'Idempotency-Key: mapping-104-v1' \
--data '{"member_id":"AXION_MEMBER_ID","callsign":"A-12","badge_number":"104","department":{"external_id":"pd","name":"Police"}}'
Only one active unit may point to a member within an installation. Revising an active assignment requires expected_revision. Captures, evidence and timeline events retain the accepted assignment's labels. Mapping changes cannot redirect an already-open preview.
curl "$AXION_API/api/external/v1/capture-requests" \
-X POST -H "Authorization: Bearer $AXION_KEY" \
-H 'Content-Type: application/json' -H 'Idempotency-Key: cad-case-82-capture-1' \
--data '{"external_unit_id":"officer-104","pre_ms":60000,"external_case_id":"case-82"}'
Capture returns 202 with a request ID. Poll /capture-requests/{id} or consume capture_request.updated. States are accepted, delivered, acknowledged, upload_queued, ready, failed, and expired. Only verified upload completion supplies a ready clip ID; acknowledgments alone do not. An undelivered instruction expires after 30 seconds. Queued uploads preserve request identity across reconnects.
The requested duration is clamped to the device buffer held during verified community presence. Read effective_pre_ms. Capture requires a fresh, recording, connected native client advertising capture_result_v1 and community_capture_v1; older clients return client_upgrade_required. A 10-second per-member community cooldown applies across installations. Associating a case during capture additionally requires evidence:write and clips:read.
Read the returned request.id from the { "request": ... } envelope and poll it:
curl "$AXION_API/api/external/v1/capture-requests/REQUEST_ID" \
-H "Authorization: Bearer $AXION_KEY"
Treat ready, failed and expired as terminal capture states. A ready clip remains subject to retention and current permissions.
Requests and retries
Send Authorization: Bearer YOUR_API_KEY on external requests and Content-Type: application/json for JSON bodies. Every mutation requires a non-empty Idempotency-Key of at most 128 characters, except POST /webhook-endpoints/{endpoint_id}/verify. For mutations with no fields, an empty JSON object is sufficient.
Reuse the same key, method, path and JSON inputs on retries. Successful saved responses survive restart for 24 hours; different inputs with the same key return 409 idempotency_conflict. Keys identify an action, not a credential, so rotation does not duplicate work. After the retry window expires, reconcile resource state before repeating an action that could duplicate work. A new viewer needs a new key; replaying its creation response does not renew its expiry or bootstrap.
When deployment rate limiting is enabled, metadata is limited to 120 requests/minute per installation and captures to 10/minute. Shared community limits are 360 metadata requests and 30 captures per minute. Read RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. Honor Retry-After when present on 429; otherwise use bounded backoff (at least the 10-second member cooldown for capture_cooldown). Retry uncertain network failures using the original action key.
API timestamps and durations use milliseconds. Webhook signature timestamps use seconds. Encode IDs used in paths with encodeURIComponent.
Permissions and reads
| Scope | Access |
|---|---|
bodycams:read | Community member IDs and current status |
bodycams:preview | Live JPEG preview viewers |
bodycams:capture | Capture requests and progress |
units:read / units:write | Installation-specific unit assignments |
clips:read | Ready, retained community footage and playback viewers |
clips:original:read | Explicit access to original footage when edit metadata exists |
evidence:write | Link/unlink footage to this installation's CAD cases |
timeline:read / timeline:write | Case chronology / CAD event append, correction and tombstone |
events:read | Event feed, callback registration and delivery history |
Using external_unit_id for capture, preview or a CAD event also requires units:read. Timeline viewers require timeline:read; add clips:read to include footage. clips:original:read supplements clips:read for edited clips and grants access to the original, not a rendered or redacted copy.
Member, unit, clip and evidence lists accept limit (1–100, default 50) and an opaque cursor, and return items plus next_cursor. Stop when next_cursor is null. Filter members by roblox_user_id, units by member_id, callsign or department (department external ID), and clips by member_id, from, to or event_type. Evidence reads require external_case_id. Webhook endpoints and deliveries return bounded items lists without pagination. The event feed uses after instead of the list cursor.
Bodycam status is offline, unknown, idle or recording. Use preview_available and capture_available to enable actions; recording alone does not guarantee they will succeed. observed_at and stale_after_ms describe freshness (currently 45 seconds), and unavailable_reason explains capture eligibility. Display unknown presence as unknown. Stale or unavailable previews fail closed.
Edited footage is unavailable to ordinary integration viewers because Axion stores edit metadata alongside the original MP4, rather than a rendered derivative. Read playback_available and clearly label original_footage when original access is granted. Evidence and timeline links do not extend retention.
Endpoint reference
Paths are relative to /api/external/v1. Additional selector and footage scopes are described above. The OpenAPI contract supplies complete schemas.
| Method and path | Scopes | Success response |
|---|---|---|
GET /installation | Valid credential | 200 {installation, features, limits} |
GET /members | bodycams:read | 200 {items, next_cursor} |
GET /members/{member_id}/bodycam | bodycams:read | 200 bodycam object |
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} (inactive) |
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 | Depends on resource | 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} |
GET /cases/{external_case_id}/timeline | timeline:read | 200 timeline object |
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} (tombstoned) |
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} |
DELETE /webhook-endpoints/{endpoint_id} | events:read | 204 (no body) |
GET /webhook-deliveries | events:read | 200 {items} |
POST /webhook-deliveries/{delivery_id}/replay | events:read | 202 {accepted} |
Private viewers
Create /viewer-sessions with origin and one of:
{"resource_type":"clip","clip_id":"CLIP_ID","origin":"https://cad.example"}
{"resource_type":"preview","external_unit_id":"officer-104","origin":"https://cad.example"}
Preview viewers accept quality: "low" (default) or quality: "high". Low uses JPEG frames up to 640×360 at 65% encoding quality. High uses frames up to 1280×720 at 85% encoding quality and requires the community's Power plan plus an updated desktop app advertising live_view_quality_v1. Both refresh about once a second, preserve the captured aspect ratio, and never upscale the source. These are live still-frame views, without audio.
{"resource_type":"preview","quality":"high","external_unit_id":"officer-104","origin":"https://cad.example"}
session.quality confirms the selected mode. Quality is fixed for the session; create a new session with a new Idempotency-Key to switch modes. quality is invalid for clip and timeline viewers. GET /installation advertises live_view_low_quality and, on Power communities, live_view_high_quality. A high-quality request below Power returns 403 plan_required; an older desktop app returns 409 client_upgrade_required. The server rechecks Power on creation retries and every high-quality viewer page, redemption and frame request, so a downgrade stops existing high-quality sessions immediately. Low-quality sessions remain available under the existing scope and recording rules.
{"resource_type":"timeline","external_case_id":"case-82","origin":"https://cad.example"}
Pass the returned embed_url to the authorized CAD browser and set it as an iframe's source. The bootstrap secret is in the fragment, expires after 60 seconds, and redeems once. Sessions last five minutes and bind to the installation, originating credential, exact parent origin and selected resource. Issue a new session before expiry. Never write capability URLs to analytics, webhook payloads or ordinary request logs.
An origin contains only scheme, hostname and optional port: https://cad.example, with no path or trailing slash. Production requires HTTPS; non-production also allows HTTP on localhost or 127.0.0.1. Register the actual parent website origin and send that exact value.
For example, https://relaycad.net and https://www.relaycad.net are different origins. Register each parent origin you actually use and send the matching value in the viewer request's JSON origin field. A bare domain such as relaycad.net is not an origin. This check applies to viewer creation and access, not to GET /installation or ordinary metadata reads.
curl "$AXION_API/api/external/v1/viewer-sessions" \
-X POST -H "Authorization: Bearer $AXION_KEY" \
-H 'Content-Type: application/json' -H 'Idempotency-Key: preview-open-104-1' \
--data '{"resource_type":"preview","external_unit_id":"officer-104","origin":"https://cad.example"}'
Render <iframe id="bodycam-viewer" title="Axion bodycam viewer"></iframe> with a suitable width and height. If your parent website uses a Content Security Policy, allow the actual Axion API origin in frame-src.
The parent completes the origin-checked handshake:
const apiOrigin = new URL(embedUrl).origin;
const iframe = document.querySelector('#bodycam-viewer');
window.addEventListener('message', event => {
if (event.source === iframe.contentWindow && event.origin === apiOrigin &&
event.data?.type === 'axion.viewer.ready') {
iframe.contentWindow.postMessage({ type: 'axion.viewer.open' }, apiOrigin);
}
});
iframe.src = embedUrl;
The iframe handles seeking, scoped media capabilities and fresh preview demand internally. Five active preview sessions across both qualities are admitted per installation. Frame requests are coalesced per device, community and quality; quality caches are separate. Delivered JPEG bytes count against shared deployment budgets of 8 MiB/minute for low and 64 MiB/minute for high, so high traffic does not consume the low budget. Missing frames do not consume byte budgets. Footage expiry or removal takes effect without waiting for the retention reaper. Timeline child clips must remain linked and authorized. These private sessions do not create public share links.
Incident timelines
Append CAD events to /cases/{external_case_id}/events using an external_event_id unique within that case and installation, type, occurred_at, optional note, and optional member/unit selector. A first event, evidence link or case-associated capture creates a case; there is no separate case-creation endpoint. Correct a CAD event with PATCH, or tombstone it with DELETE, including its expected_revision. Use Axion's event id in that path, not the CAD's external_event_id. Axion-generated events cannot be rewritten through those routes. Prior revisions remain in bounded history.
To attach an existing ready clip, send POST /evidence-links with { "clip_id": "CLIP_ID", "external_case_id": "case-82" } and an action key. Unlink using the returned link id in DELETE /evidence-links/{link_id}. This removes the association, not the recording.
GET /cases/{id}/timeline returns case revision, ordered events, historical unit snapshots, available footage intervals and timing quality. Optional revision rejects stale snapshots with 409 timeline_changed. A late upload or correction advances the case revision. The viewer provides a shared case-time slider and camera selection; unknown timestamps remain explicitly unsynchronized. Synchronization is approximate and uses the existing native clock offset/RTT metadata. Missing footage is shown as unavailable and does not extend retention.
Events and callbacks
GET /events?after=EVENT_CURSOR supplies a durable, monotonically ordered feed. Keep the returned cursor even when its page contains no authorized events. The replay window is seven days; an expired or foreign cursor returns 410 and requires a fresh resource snapshot. Resource revisions let receivers recover from duplicate or out-of-order delivery.
Register a HTTPS endpoint with /webhook-endpoints, choose event subscriptions, and retain the returned whsec_… signing secret. Then call /{endpoint_id}/verify: verify the signed webhook.verification body and echo its challenge in the Axion-Webhook-Challenge response header. Real deliveries start after that check succeeds.
Headers follow Standard Webhooks: webhook-id, webhook-timestamp, webhook-signature. Decode the portion after whsec_ as base64 and verify HMAC-SHA256 over id.timestamp.raw_body, using a timing-safe comparison and a timestamp tolerance. Verify before parsing or acting. Retries retain the event ID and receive a new timestamp/signature. Acknowledge quickly and deduplicate by event ID.
Delivery is at least once, backed by the same durable transaction as its event. Retry backoff runs for up to 24 hours/15 attempts. Redirects and private, loopback, reserved, link-local or mixed public/private DNS destinations are refused; each attempt validates DNS and pins its TLS connection to a public address. Failed callbacks do not block capture. /webhook-deliveries exposes bounded diagnostics; /{id}/replay requires an idempotency key and current authorization. Scope changes and revocation cancel unauthorized queued payloads.
Supported subscriptions are bodycam.status_changed, capture_request.updated, clip.ready, clip.unavailable, evidence_link.created, evidence_link.deleted, unit_mapping.updated, unit_mapping.removed and case.timeline_updated. Delivery also requires each event's resource scopes. Callback URLs must use public HTTPS on port 443 with no URL credentials or fragment.
TypeScript integration
Download the backend TypeScript helper. It uses fetch, has no dependencies and accepts the API origin without the versioned path. It does not automatically poll or retry.
import { Axion } from './axion';
const axion = new Axion(process.env.AXION_API!, process.env.AXION_KEY!);
// First authenticate your website user and check their CAD permissions.
const { request } = await axion.capture(
{ external_unit_id: 'officer-104', pre_ms: 60000 },
'cad-action-104-capture-1',
);
// Persist request.id; poll with bounded backoff until ready, failed or expired.
const result = await axion.captureResult(request.id);
if (result.request.status === 'ready' && result.request.clip_id) {
const viewer = await axion.viewer(
{ resource_type: 'clip', clip_id: result.request.clip_id, origin: 'https://cad.example' },
'cad-action-104-viewer-1',
);
// Return viewer.embed_url only to the authorized user; do not log it.
}
// Failed calls throw AxionError with status, code, message and retryAfter.
Errors and troubleshooting
Errors have the shape { "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 error.code; messages describe the cause and recovery step and are for display, not parsing. Common codes below are not an exhaustive enum.
Authentication messages distinguish missing or malformed headers, malformed keys, live/test mismatches, unrecognized keys, revoked keys, expired keys, disabled API access, missing or revoked installations, and missing communities. Expiry and revocation details are returned only after the key's secret is verified; unknown keys and incorrect secrets receive the same unrecognized-key message. Approval messages distinguish changed community ownership from an owner account suspension. Capture and preview failures explain the current eligibility problem and what the member or owner needs to do.
| Status / code | Resolution |
|---|---|
400 bad_input | Check JSON, selectors, integer durations and the idempotency header. |
401 unauthorized | Check the full Bearer credential, expiry/revocation, live/test API pairing, and installation availability on the receiving deployment. Human/device tokens cannot be used. |
403 forbidden | The owner must grant the scope, including any unit selector scope. |
403 approval_required | The current community owner must reapprove the installation. |
403 origin_not_allowed | Register the exact parent website origin. |
404 not_found | Check community/installation ownership, readiness and retention. |
409 device_offline, presence_unknown, outside_community, not_recording, buffer_unavailable | Refresh status and wait for an eligible recording device. |
409 client_upgrade_required | Update the native client. |
409 preview_unavailable | Refresh status; preview requires online community recording. |
409 edited_clip_unavailable | No rendered derivative exists; original access requires explicit approval. |
409 revision_conflict, timeline_changed | Fetch current state, reconcile, and use a new key for changed input. |
409 idempotency_conflict | Restore original inputs or use a new key for a new action. |
409 unit_already_assigned | End/revise the existing assignment before assigning another unit. |
409 callback_unverified | Verify the signature and echo the challenge response header. |
410 cursor_expired | Fetch resource snapshots and restart the event feed. |
410 viewer_expired, 401 viewer_revoked | Create a newly authorized session with a new key. |
429 rate_limited, capture_cooldown, viewer_limit | Respect retry timing; reduce volume or active previews. |
Handle additive fields and unknown future states without crashing. Clip endpoints return metadata; private viewer sessions provide playback. Do not invent permanent MP4 URLs. Keep API keys and signing secrets out of public builds and logs; only the scoped viewer URL reaches the authorized browser.
Connection diagnostics
Do not turn every failure into “invalid key” or “copy the key again.” Authentication, scope approval, embed-origin approval and browser CORS are separate checks.
- Identify the failing operation and whether it runs in the browser or on your backend. Move direct browser API calls to an authenticated backend route that checks the user's CAD permissions.
- From that backend, call
GET /installationon the configured Axion API. Production useshttps://getaxion.xyz/api/external/v1with anax_live_key; anax_test_key requires the sandbox project's API. When using the TypeScript helper, pass only the API origin because it appends/api/external/v1itself. - Check that the backend retrieves the intended full key and sends exactly
Authorization: Bearer <key>, without quotes, an extraBearerprefix, or embedded whitespace. Confirm any proxy preserves the header and the request reaches the intended deployment. Avoid redirects; use the final API origin directly. - Record the upstream method, path, HTTP status and
error.code/error.messagein restricted diagnostics. Never record the Authorization header, key, private viewer URL or full request/response payloads. If the failure is a timeout, network error, CORS error or non-JSON proxy response, report that category rather than inventing an Axion authentication error. - If
/installationsucceeds, inspect the original operation's response.403 forbiddenneeds the stated scope,403 approval_requiredneeds the current owner's approval, and403 origin_not_allowedneeds the exact viewer parent origin. Handle rate limits and service failures separately.
A 401 unauthorized can mean an invalid, missing, expired, revoked or wrong-environment credential, or an unavailable installation. A correct stored key may still fail if the caller sends a different value or the receiving server does not have its credential/installation records. Recopying the same key does not resolve routing or installation failures.
Developer playground deployment
The playground is /developers/playground. It authenticates the developer through the regular Axion session and calls a fixed sandbox bridge. Production footage and platform admin/debug routes are unavailable inside the sandbox.
Run a separate sandbox service process from server/:
AXION_SANDBOX_ROOT=/srv/axion-sandbox/data
AXION_SANDBOX_PUBLIC_URL=https://sandbox-api.example
AXION_SANDBOX_MASTER_KEY=SEPARATE_RANDOM_SECRET_AT_LEAST_32_CHARACTERS
AXION_SANDBOX_BRIDGE_SECRET=SHARED_RANDOM_BRIDGE_SECRET_AT_LEAST_32_CHARACTERS
AXION_SANDBOX_ADDR=:8081
node ../dist/server/sandbox/index.js
Set AXION_SANDBOX_URL=https://sandbox-api.example and the same bridge secret on the regular API process. Reverse-proxy the sandbox hostname to its loopback listener. The sandbox root must be separate from the live database and blob directories, and its master key must differ. It runs no live PRC, Roblox, Discord, billing or role-sync workers. Use npx tsx src/sandbox/index.ts during development.
Each developer owns one isolated project and ax_test_… installation. Live/test credentials are rejected in the opposite environment. Load sample generates a four-second H.264 MP4 and JPEG in the browser, then sends them through normal reservation, byte upload, hash verification and completion. Chrome, Edge or Safari with MP4 recording support is required to generate the sample. No native recorder or ER:LC key is needed.
The sample supplies recording, idle and offline units, two overlapping cameras and a fictional dispatch. The runner accepts only documented methods and sandbox-relative paths, keeps its credential on the backend, and displays/export examples with placeholders. It supports unit reassignment, successful/failed/queued capture, unavailable devices, stale presence, missing scopes, expired keys/sessions/footage and unsynchronized footage. Callback registration is opt-in and uses the same public-destination and signing checks as live service.
Webhook timeout, duplicate, and out-of-order scenarios use a project-owned simulated receiver inside the sandbox process. They exercise the normal signed outbox: timeout leaves a persisted retry; duplicate loses the first acknowledgment, then verifies and deduplicates the repeated event ID; out-of-order delivers revision 2 before revision 1 and applies only the newer revision. The scenario response shows signature verification, received IDs/revisions, application decisions and delivery attempts. The reserved .invalid callback never contacts another service. Public callback URLs continue through normal destination checks.
Reset removes sample resources, pending deliveries, scenarios and viewers, advances the generation, and clears resource idempotency results while preserving project-control retry records and credentials. Resetting one project cannot affect another. Rotation/revocation remain separate actions. New media/resources receive new IDs.
For a disposable local UI preview without OAuth or production configuration, run npx tsx scripts/preview-integrations.mts from server/ and the normal web dev server from web/. The preview uses only in-memory stores and temporary blob directories, on API ports 8080/8081; its temporary sign-in data is for automated local review, not production deployment.
Before enabling live access, update the native client, configure the sandbox bridge and public callback networking, and verify capture/playback load on the deployment hardware. The feature flag is the rollout gate; deployment and a real CAD pilot are separate operational steps.
/metrics includes axion_integration_worker_last_success_seconds, axion_integration_worker_failures_total, and a pending-delivery gauge capped at 1000. Use the delivery endpoint for individual failures and replay.