# Using the API

> How AppHelm's REST API works - base URL, server keys and scopes, product scoping, pagination, errors, idempotency, rate limits, versioning, the browser collector and signed webhooks - with curl and SDK examples.

Source: https://apphelm.dev/docs/api-overview

Everything you can do in AppHelm's app you can also do over HTTP: send events, evaluate and change flags, read insights and issues, run SQL, manage experiments, surveys, pipelines and imports. This page explains the rules every endpoint shares. The [API reference](https://apphelm.dev/docs/api) lists each endpoint with its parameters and answers, and lets you try them.

| | |
| --- | --- |
| Base URL | `https://apphelm.dev/api/v1` |
| Authentication | `Authorization: Bearer ahl_live_…` (a server key) |
| Format | JSON in and out, UTF-8 |
| OpenAPI 3.1 document | `https://apphelm.dev/api/openapi.json` |
| Request ids | Every answer carries `X-Request-Id`; quote it to support |

## A first request

```bash
export APPHELM_API_KEY=ahl_live_…

curl https://apphelm.dev/api/v1/auth/key -H "Authorization: Bearer $APPHELM_API_KEY"
# { "data": { "workspace": { "id": "org_…", "name": "…" }, "name": "…", "scopes": [ … ], "productIds": [ … ] } }

curl https://apphelm.dev/api/v1/products -H "Authorization: Bearer $APPHELM_API_KEY"
```

`GET /api/v1/auth/key` needs no scope: use it to check which workspace, scopes and products a key has.

## Authentication

The REST API takes **server keys** (`ahl_live_…`), sent as a Bearer token. Create one in **Settings → API keys** (or with `apphelm login` from the [CLI](https://apphelm.dev/docs/cli)). It is shown once; AppHelm keeps only a digest of it and can't show it again.

- Keep server keys on servers and in CI secrets. Never put one in a browser bundle, a mobile app you ship to the public, or git.
- Browser and mobile code use a **browser key** (`ahl_pub_…`) on the [browser collector](#the-browser-collector) instead. Browser keys don't work on `/api/v1`.
- A missing, mistyped, revoked or expired key answers `401` with `WWW-Authenticate: Bearer`.

### Scopes

Each endpoint needs a scope, named in the reference and in the `403` it answers without one (`scope_denied` or `insufficient_scope`). A key created without a scope list gets every scope except the **explicit-only** ones, which an owner or admin must tick by name because they change what live users see or reach outside AppHelm: `products:write`, `flags:write`, `experiments:write`, `surveys:write`, `analytics:write`, `cohorts:write`, `pipelines:write`, `imports:write`, `alerts:write`, `monitors:write`, `members:read`, `members:write` and `audit:read`.

The common ones:

| Scope | For |
| --- | --- |
| `events:write` | Sending events, deploys, check-ins, source maps and symbols |
| `products:read` | Products, flag configs (local evaluation) |
| `analytics:read` | Saved insights, dashboards, recent events, SQL |
| `metrics:read` | Metrics and the query endpoint |
| `issues:read`, `issues:write` | Error issues, events, traces, releases; triage |
| `logs:read` | Log search |
| `flags:write` | Creating and changing flags (explicit-only) |

[Keys, scopes and environments](https://apphelm.dev/docs/keys-and-environments) lists every scope and explains rotation.

Writes made through an explicit-only scope are made **in the name of the person who created the key**, and are audited as theirs. Many also need that person to be an owner or admin. If their role or product access changes, those writes are refused (`403`) even though the key still holds the scope; create a new key from someone who has the access.

## Workspaces and products

A key belongs to one **workspace** (`org_…`) and sees only that workspace's data. Within it, a key is either for **all products** or limited to a list of **products** (`prd_…`).

- Most endpoints take a `productId`, in the query string for reads and in the body for writes.
- A product outside the key's list answers `403` with `product_scope_denied`, on every endpoint that takes a `productId`. A product that isn't in the workspace at all answers `404` (`not_found`, or `product_not_found` on some ingest and logs endpoints). An endpoint that needs a workspace server key answers `403 workspace_key_required` to any other caller. A key for some products can't call endpoints that act on the whole workspace (for example creating a product, or the team and audit log endpoints); those answer `403` and say a key for every product is needed.
- Ingest bodies also carry `workspaceId`. It must be the key's workspace.
- The workspace's **demo product** is never readable or writable over the API, whatever the key: naming it answers `403 product_scope_denied` (ingest such as feedback, traces, check-ins and deploys answers `409 demo_product_read_only`), and a record that belongs to it answers `404` like one that doesn't exist.

## Requests and answers

Successful answers wrap their content in `data`:

```json
{ "object": "list", "data": [ … ], "pagination": { "nextCursor": "k", "hasMore": true } }
```

### Pagination

List endpoints take `limit` and an opaque `cursor`. Most default to 20 items and allow up to 100; the reference gives each endpoint's own limits. Pass `pagination.nextCursor` back as `cursor` to get the next page, until `hasMore` is `false` (and `nextCursor` is `null`). Treat a cursor as opaque: don't build or change one.

```bash
curl "https://apphelm.dev/api/v1/issues?productId=prd_…&limit=50" -H "Authorization: Bearer $APPHELM_API_KEY"
curl "https://apphelm.dev/api/v1/issues?productId=prd_…&limit=50&cursor=<nextCursor>" -H "Authorization: Bearer $APPHELM_API_KEY"
```

### Errors

Every error has the same shape, a stable `code` to branch on and a `message` that says what to do:

```json
{ "error": { "code": "scope_denied", "message": "flags:write is required. An owner or admin can create a workspace API key with it in Settings → API keys." } }
```

| Status | Common codes | What to do |
| --- | --- | --- |
| `400` | `invalid_request`, `idempotency_required` | Fix the request; the message names the field |
| `401` | `unauthorized` | Send a valid server key |
| `402` | | The plan doesn't include this feature; see Billing |
| `403` | `scope_denied`, `insufficient_scope`, `product_scope_denied`, `workspace_key_required` | Use a key with the scope or product, or a workspace key |
| `404` | `not_found`, `product_not_found`, `flag_not_found`, `issue_not_found` … | Check the id; list endpoints find it |
| `409` | `idempotency_conflict`, `idempotency_in_flight`, `flag_changed`, `product_archived` … | Read the current state and retry, or use a new idempotency key |
| `413` | | The body is too large; send less per request |
| `422` | `invalid_flag`, `invalid_survey_program`, `missing_fields` … | The body failed validation; `issues` (when present) lists each problem |
| `429` | `rate_limited`, `rate_limit_exceeded`, `flag_evaluation_limit` … | Wait and retry; see [Rate limits](#rate-limits) |
| `5xx` | | Retry with backoff; check https://apphelm.dev/status |

## Safe retries

### Idempotency-Key

Endpoints that create or change something take an `Idempotency-Key` header, and many require it: flags, experiments, surveys, saved insights and dashboards, cohorts, pipelines, imports, products and browser keys, team changes, Beam investigations. A key is 8 to 160 characters of letters, digits and `. _ : -`; a UUID is ideal.

- Sending the same key with the same body again returns the **first answer** instead of acting twice, with `Idempotency-Replayed: true` and `"replayed": true` in the body. Replays are kept for 24 hours.
- The same key with a **different** body answers `409 idempotency_conflict`. Use a new key for a new change.
- A key whose first request is still running answers `409 idempotency_in_flight`. Retry in a moment for its answer.
- Secrets in a first answer (a new browser key, a webhook signing secret) are never repeated on a replay.

```bash
curl -X POST https://apphelm.dev/api/v1/flags \
  -H "Authorization: Bearer $APPHELM_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","flagKey":"new-checkout","name":"New checkout","rolloutPercent":10}'
```

Generate one key per logical change and reuse it on every retry of that change, for example after a timeout.

### expectedVersion

Some objects carry a version, and their update endpoints take an optional `expectedVersion` (flags) or `expectedUpdatedAt` (saved insights). If someone changed the object since you read it, the update is refused with `409` (for a flag, `flag_changed`) instead of overwriting their change. Read it again, reapply your change and retry.

```bash
curl -X PATCH https://apphelm.dev/api/v1/flags/flg_… \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"rolloutPercent":50,"expectedVersion":4}'
```

### Ingest is deduplicated

Events carry an event id. Send the same event again (same id) and it is stored and billed once, so give each event its id before the first attempt and keep it on retries. The Node client does this for you.

## Rate limits

Limits are per endpoint family, chosen so normal use never meets them. A limited request answers `429` with a code and, where there is one, `Retry-After` in seconds.

| What | Limit |
| --- | --- |
| Browser collector (`/api/events`, replay, surveys, flag bootstrap, feedback) | 240 requests a minute per client address and 2,400 a minute per browser key, per Cloudflare location |
| Query endpoint (`/api/v1/query`) | 60 queries a minute per key |
| SQL (`/api/v1/query/sql`) | 60 runs a minute per workspace, one at a time (`sql_busy` while another runs) |
| Error event search and span search | 60 searches a minute per key |
| Deploys (`/api/v1/deploys`) | 20 an hour per product |
| Source map uploads | 600 an hour per product |
| Monthly event allowance | When it is used up, ingest answers `429` until the next month or a plan change; nothing is stored |
| Monthly flag evaluations | Past the plan's cap, `/api/v1/flags/evaluate` answers `429 flag_evaluation_limit`: evaluate locally instead |

When you get a `429`:

1. Wait for `Retry-After` seconds when it is present, otherwise back off (for example 1, 2, 4, 8 seconds, with some randomness).
2. Retry the same request, with the same `Idempotency-Key` for a write.
3. If it keeps happening, batch more per request (events support batches; traces take many spans per request) or cache reads.

Monthly allowances are not cleared by waiting: raise the plan, or for flags switch to [local evaluation](https://apphelm.dev/docs/feature-flags#evaluate-locally-on-a-server).

## Versioning

The API is versioned in the path: `/api/v1`. Within v1, changes are additive: new endpoints, new optional fields and new fields in answers. Ignore fields you don't know, and branch on `error.code`, not on the message text. The OpenAPI document's `info.version` is the current revision. A change that would break v1 clients would come as a new path version.

## The browser collector

Browser code doesn't call `/api/v1`. It posts to `/api/events` (and the other `/api/*` collector routes the browser SDK uses) with a **browser key**:

```http
POST /api/events
Origin: https://app.example.com
X-Apphelm-Key: ahl_pub_…
Content-Type: application/json

{"workspaceId":"org_…","productId":"prd_…","eventName":"signup_completed","privacyMode":"strict"}
```

- The request's `Origin` must exactly match one of the key's allowed origins, and the key's workspace and product must match the body.
- Bots and headless browsers are answered `202 {"accepted":false,"reason":"bot_filtered"}` and stored nothing; a paused workspace answers `202` with `collection_paused`. These are not errors: don't retry them.
- Identity, account, goal and outcome signals need a server key and are refused from the browser.

Use the browser SDK rather than calling the collector yourself: it batches, retries, waits for consent and keeps ids. See [Install and configure](https://apphelm.dev/docs/install).

## CORS

`/api/v1` answers browsers only from AppHelm's own origins: server keys must never be in a browser, so calling the API from your web page won't work and shouldn't. Call it from your server. The browser collector answers any origin's preflight, then checks the origin against the browser key on the request itself. CORS is not authentication; a server or script without an `Origin` header is fine as long as it sends a valid key.

## Webhooks

AppHelm can call your endpoints: workspace webhooks (**Settings → Webhooks**) for alerts and other notifications, and webhook destinations in [data pipelines](https://apphelm.dev/docs/data-pipelines). Each request is a JSON `POST` signed with your endpoint's secret:

| Header | Meaning |
| --- | --- |
| `X-Apphelm-Timestamp` | Unix seconds when it was signed |
| `X-Apphelm-Signature` | `v1=` and the hex HMAC-SHA256 of `<timestamp>.<raw body>` with your secret |
| `X-Apphelm-Event-Id`, `X-Apphelm-Event-Type` | The delivery's event id (deduplicate on it) and type, on workspace webhooks |

Check the signature over the raw body before parsing it, reject old timestamps (a few minutes is plenty), and compare in constant time:

Node.js — verify-webhook.ts:
```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verify(rawBody: string, headers: Headers, secret: string) {
  const timestamp = headers.get("x-apphelm-timestamp") ?? "";
  const signature = headers.get("x-apphelm-signature") ?? "";
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const expected = "v1=" + createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex");
  return signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
```

Python — verify_webhook.py:
```python
import hashlib, hmac, time

def verify(raw_body: bytes, headers, secret: str) -> bool:
    timestamp = headers.get("x-apphelm-timestamp", "")
    signature = headers.get("x-apphelm-signature", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
        return False
    expected = "v1=" + hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)
```

Answer with a `2xx` quickly and do the work afterwards. Redirects are not followed and count as a failure; failed deliveries are retried, and the delivery log in settings lets you send one again. A pipeline webhook's signing secret is shown once, when you create it.

## Examples

### Send an event from a server

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"workspaceId":"org_…","productId":"prd_…","eventName":"invoice_sent","properties":{"distinct_id":"user-123","amount":42}}'
```

Node.js:
```ts
import { Apphelm } from "@sansavision/apphelm";

const apphelm = new Apphelm({ apiKey: process.env.APPHELM_API_KEY!, workspaceId: "org_…", productId: "prd_…" });
await apphelm.capture({ distinctId: "user-123", event: "invoice_sent", properties: { amount: 42 } });
```

Python:
```python
apphelm.capture("org_…", "prd_…", distinct_id="user-123", event_name="invoice_sent", properties={"amount": 42})
```

Go:
```go
client.Capture(apphelm.Capture{DistinctID: "user-123", Event: "invoice_sent", Properties: apphelm.Properties{"amount": 42}})
```

Ruby:
```ruby
APPHELM.capture(distinct_id: "user-123", event: "invoice_sent", properties: { amount: 42 })
```

PHP:
```php
$apphelm->capture(distinctId: 'user-123', event: 'invoice_sent', properties: ['amount' => 42]);
```

.NET (C#):
```csharp
apphelm.Capture("user-123", "invoice_sent", new Dictionary<string, object?> { ["amount"] = 42 });
```

Rust:
```rust
apphelm.capture(Event::new("user-123", "invoice_sent").property("amount", 42))?;
```

Elixir:
```elixir
Apphelm.capture("user-123", "invoice_sent", %{amount: 42})
```

Java / Kotlin (JVM):
```kotlin
apphelm.capture("user-123", "invoice_sent", mapOf("amount" to 42))
```

The SDKs fill in the ids and the person hashing for you, so prefer them to raw HTTP for ingest.

### Evaluate a flag

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/flags/evaluate \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","distinctId":"user-123","flagKey":"new-checkout"}'
```

Node.js:
```ts
const on = await apphelm.isEnabled("new-checkout", "user-123");
```

Every server SDK has this call; see [Feature flags](https://apphelm.dev/docs/feature-flags) for each language.

### Read and triage issues

HTTP (curl):
```bash
curl "https://apphelm.dev/api/v1/issues?productId=prd_…&query=is:unresolved%20level:error&limit=25" \
  -H "Authorization: Bearer $APPHELM_API_KEY"

curl -X POST "https://apphelm.dev/api/v1/issues/$ISSUE_ID" \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"status":"resolved","inNextRelease":true}'
```

Node.js:
```ts
const issues = await apphelm.listIssues({ productId: "prd_…", status: "unresolved", limit: 25 });
await apphelm.updateIssue(issues.data[0].id as string, { status: "resolved", inNextRelease: true });
```

The Node client also wraps products (`listProducts`, `getProduct`), insights (`listInsights`, `getInsight`), metrics (`queryMetric`), session search, customers, incidents, flag configs and Beam (`investigate`). Its errors are `ApphelmError` with `status`, `code` and `requestId`. The other server SDKs cover ingest, flags, check-ins, deploys and errors; for the rest, call the HTTP API.

### Run SQL

HTTP (curl):
```bash
curl -X POST https://apphelm.dev/api/v1/query/sql \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","query":"SELECT event, count(*) AS events FROM events GROUP BY event ORDER BY events DESC LIMIT 10","days":7}'
```

See [Insights, dashboards and SQL](https://apphelm.dev/docs/insights) for the tables and functions.

### From the command line and from AI tools

The [`apphelm` CLI](https://apphelm.dev/docs/cli) wraps the common calls (flags, experiments, surveys, issues, releases, uploads) and prints the next step for every error. The [MCP server](https://apphelm.dev/docs/mcp) exposes the same operations to AI assistants with the same keys and scopes.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| `401 unauthorized` | No `Authorization: Bearer` header, a mistyped or revoked key, or a browser key | Send an active server key (`ahl_live_…`); `GET /api/v1/auth/key` shows what a key is |
| `403 scope_denied` | The key lacks the scope in the message | Create a key with that scope; explicit-only scopes must be ticked by name |
| `403 product_scope_denied` | The key is limited to other products, or the id is the demo product's | Use one of its products (`/api/v1/auth/key` lists them) or a key for this one |
| `403 workspace_key_required` | The caller isn't a workspace server key (a Sansa Auth caller or workload identity) | Create a server key (`ahl_live_…`) in Settings → API keys |
| `404 not_found` for a `productId` | The product isn't in this workspace | Copy the id from `GET /api/v1/products` |
| `403` on a write with the right scope | The key's creator is no longer an owner or admin, or lost access to the product | Ask an owner or admin to create the key |
| `400 idempotency_required` | A write that needs `Idempotency-Key` didn't send one | Add the header with a new UUID |
| `409 idempotency_conflict` | An idempotency key was reused for a different change | Use a new key for each new change |
| `409 flag_changed` | Someone changed the flag after you read it | Read it again, reapply and retry with the new `expectedVersion` |
| The browser can't call `/api/v1` (CORS error) | Server endpoints don't answer other origins | Call them from your server; use the browser SDK in the browser |
| `429` that doesn't clear after a minute | A monthly allowance is used up | Check Billing; raise the plan, or evaluate flags locally |
