Skip to main content

Complete reference for all Flaggr REST API endpoints — flags, evaluation, projects, services, tokens, audit, and webhooks

Last updated November 21, 2026

REST API Reference

Base URL: https://flaggr.dev (or your self-hosted instance).

All endpoints accept and return application/json. State-changing requests (POST, PATCH, DELETE) require a CSRF token in the X-CSRF-Token header.

Hosts

https://flaggr.dev, the control plane, serves every endpoint on this page. https://api.flaggr.dev is an edge Worker in front of the Go data plane, which evaluates flags. On api.flaggr.dev:

PathServed by
POST /api/flags/evaluate, POST /api/flags/evaluate/batch, GET /api/flags/export, POST /api/ofrep/v1/evaluate/flags/{key}The data plane. Successful answers are cached at the edge for 5 seconds, keyed by the URL, the body and the full Authorization header (for OFREP, also the service and environment headers)
GET /api/flags/stream (SSE), Connect and gRPC-Web (/flaggr.v1.*), GET /health and GET /healthzThe data plane, never cached
POST /api/ofrep/v1/evaluate/flags (bulk OFREP), GET /api/ofrep/v1/metadata, POST /api/playground/evaluateflaggr.dev, cached at the edge
GET /api/sdk-config, POST /api/analytics/sdk-telemetry, POST /api/events/outcomes, POST /api/events/exposures/batch, and their OPTIONS preflightsflaggr.dev, never cached
Any other pathThe data plane, which answers 404 for paths it doesn't serve

When the edge sends a request to flaggr.dev (bulk OFREP, the playground and the four SDK routes), it passes the caller's IP along with a shared secret, so flaggr.dev rate-limits the caller's own address rather than the edge's. A POST to a cached route with a body over 128 KiB (the data plane's limit) gets 413 at the edge before credentials are checked, and so does POST /api/events/outcomes. Telemetry and exposure batches go to flaggr.dev as they are sent, under its own size limits.

Authentication

Bearer Token

Authorization: Bearer fgr_your_token     # project API token (one project)
Authorization: Bearer fgp_your_token     # personal access token (your account, capped by its tier)

See API Tokens and Personal Access Tokens for what each credential can reach. A credential that is recognised but refused (for example an SDK key on a management endpoint) gets 403 with an explanatory error rather than 401.

Firebase session cookies are sent automatically by the dashboard.

Get CSRF Token

GET /api/csrf-token
{ "token": "abc123", "headerName": "x-csrf-token" }

Current User

GET /api/users/me

Who the request's credential acts as and what it can reach: { user, credential, projects, server }. Sessions and personal access tokens list every project you belong to; connectors and project API tokens list only the projects they are bound to. credential is one of:

{ "type": "session", "tier": "role" }
{ "type": "connector", "clientId": "…", "clientName": "Claude", "scope": "read write", "tier": "write", "projectTiers": { "proj-1": "write", "proj-2": "read" }, "expiresAt": "…" }
{ "type": "api_token", "tier": "read" | "write" | "admin" | "none", "tokenId": "…", "name": "checkout-ci", "projectId": "…", "scopes": ["service:service-1712345:read"], "expiresAt": "…" }
{ "type": "personal_token", "tier": "admin", "tokenId": "…", "name": "ci", "clientName": "personal access token “ci”", "expiresAt": "…", "allowOwnerActions": false }

tier: "role" means the session isn't capped; your project roles decide. For a connector, scope is the connection's tier as tier words (read, read write or read write admin), never the stored grant; each selected project's effective tier, which can be lower, is in projectTiers. Read tier (the connection's tier) and projectTiers (each selected project's effective tier) rather than parsing scope. An API token whose scopes name only services, environments or flags has tier: "none": those scopes count only on requests that name them, and scopes lists them.


Flag Evaluation

Evaluate a Single Flag

POST /api/flags/evaluate

Evaluates a flag against the provided context. This is the primary evaluation endpoint. Name the environment in every request: without it, flaggr.dev evaluates development and the data plane at api.flaggr.dev evaluates production (see Default Environment).

Request:

{
  "flagKey": "checkout-v2",
  "serviceId": "web-app",
  "environment": "production",
  "defaultValue": false,
  "context": {
    "targetingKey": "user-123",
    "email": "alice@example.com",
    "plan": "enterprise"
  }
}

Response:

{
  "flagKey": "checkout-v2",
  "value": true,
  "reason": "TARGETING_MATCH",
  "variant": "enabled",
  "_debug": {
    "timings": {
      "rateLimit": 2,
      "validation": 1,
      "cacheGet": 0.5,
      "evaluate": 3
    },
    "cacheHit": false,
    "totalMs": 12
  }
}

Auth: API token (read) OR session. Public flags can be evaluated without auth. When a request authenticates with a dashboard session or connector instead of an SDK key, the member's access overrides for the service and environment the request names apply; an override of none answers 403. The same holds for batch evaluation, OFREP, Connect and gRPC-Web.

Rate limits: 1,000/min (IP; an IPv6 address counts by its /64) · 5,000/min (token) · 10,000/min (service)

On api.flaggr.dev, a request body over 128 KiB gets 413 {"error":"REQUEST_TOO_LARGE"} from the edge (the data plane's limit), before credentials are checked.

Multi-Language Examples

curl -s -X POST https://flaggr.dev/api/flags/evaluate \
  -H "Authorization: Bearer fgr_abc123xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "flagKey": "checkout-v2",
    "serviceId": "web-app",
    "environment": "production",
    "defaultValue": false,
    "context": {
      "targetingKey": "user-123",
      "email": "alice@example.com",
      "plan": "enterprise"
    }
  }' | jq

Bulk Evaluate

POST /api/flags/evaluate/batch

Evaluates multiple flags in a single request. Use this to reduce round-trips when your application needs several flags at once.

Request:

{
  "serviceId": "web-app",
  "environment": "production",
  "flags": [
    { "key": "checkout-v2", "defaultValue": false },
    { "key": "dark-mode", "defaultValue": false },
    { "key": "new-pricing", "defaultValue": "off" }
  ],
  "context": {
    "targetingKey": "user-123",
    "plan": "enterprise"
  }
}

Response:

{
  "flags": [
    { "key": "checkout-v2", "value": true, "reason": "TARGETING_MATCH", "variant": "enabled" },
    { "key": "dark-mode", "value": false, "reason": "DEFAULT" },
    { "key": "new-pricing", "value": "tier-b", "reason": "VARIANT", "variant": "tier-b" }
  ],
  "_meta": {
    "evaluationTimeMs": 9,
    "flagCount": 3,
    "cacheHits": 2,
    "cacheMisses": 1,
    "timings": { "auth": 2, "storage": 5, "evaluate": 1 }
  }
}

_meta holds the request's timings in milliseconds and its cache hits and misses. A batch takes up to 100 entries; more, or an entry that isn't an object with a non-empty string key, gets 400. A flag that doesn't exist comes back with reason: "NOT_FOUND" and your defaultValue. Without environment, flaggr.dev evaluates development.

On api.flaggr.dev, the data plane's batch takes flagKeys (a list of up to 100 distinct keys, without defaults; more get 413) instead of flags, and evaluates every flag of the service when the list is empty or missing. It answers flags as an object keyed by flag key ({ flagKey, value, variant, reason }), with total and evaluatedAt. A missing key there has reason and errorCode FLAG_NOT_FOUND, and without environment it evaluates production. @flaggr/sdk 0.5.0 and later send both fields, so their batches work on either host. On api.flaggr.dev, a request body over 128 KiB gets 413 {"error":"REQUEST_TOO_LARGE"} from the edge, before credentials are checked.

Multi-Language Examples

curl -s -X POST https://flaggr.dev/api/flags/evaluate/batch \
  -H "Authorization: Bearer fgr_abc123xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "serviceId": "web-app",
    "environment": "production",
    "flags": [
      { "key": "checkout-v2", "defaultValue": false },
      { "key": "dark-mode", "defaultValue": false },
      { "key": "new-pricing", "defaultValue": "off" }
    ],
    "context": {
      "targetingKey": "user-123",
      "plan": "enterprise"
    }
  }' | jq

Evaluation Logs

GET /api/evaluations?flagKey=checkout-v2&serviceId=web-app&limit=100&since=2025-01-01

Returns this instance's recent evaluation events (newest first, evaluation contexts included) as a JSON array. Requires authentication.

  • serviceId: that service's events (needs read access to the service; access overrides and narrow token scopes apply).
  • projectId: the events of that project's services you can read.
  • Neither: the events of every service you can read; Flaggr platform admins (verified dashboard session) see every project.
  • Project API tokens and MCP connectors must pass serviceId or projectId (400 otherwise).
DELETE /api/evaluations?flagKey=checkout-v2

Clears the evaluation log: every entry, or one flag key's across all projects. The log is shared by every project on the instance, so only Flaggr platform admins can clear it, from a signed-in dashboard session (403 for everyone else, and for any API token, personal access token or connector). Entries age out of the bounded log on their own.

POST /api/evaluations
Authorization: Bearer <SDK key or project API token>
{
  "serviceId": "web-app",
  "events": [
    { "flagKey": "checkout-v2", "value": true, "defaultValue": false, "context": { "targetingKey": "user-123" }, "timestamp": 1767225600000 }
  ]
}

Legacy exposure ingestion used by the analytics clients; new integrations should use POST /api/events/exposures/batch. The events feed the evaluation log, flag metrics, the circuit breaker and rollout guardrails, so every project the batch writes to must accept the caller, as for flag evaluation: an SDK key or project API token for that project, or a dashboard session or connector with read access. A batch without an Authorization header gets 401; a batch that names another project's service is refused whole (403). Events for unknown services are skipped ({ "success": true, "logged": 0 }). Browsers on other origins can POST here (CORS preflight allowed for Authorization, Content-Type and X-API-Key); GET and DELETE /api/evaluations stay same-origin. Service-, environment- and flag-scoped keys must cover each event's service, environment and flag.

POST /api/events/exposures/batch answers 401 without an Authorization header (before the body is read) and is rate limited per IP and per token. Refused batches are logged server-side; they are not written to the project's audit log. Cross-origin POST is allowed.

Evaluation Stats

GET /api/evaluations/stats?serviceId=web-app&flagKey=checkout-v2
GET /api/evaluations/stats?projectId=proj_123

Returns counts from the evaluation log of the instance that serves the request: { totalEvaluations, uniqueFlags, evaluationsByFlag, recentEvaluations }.

  • serviceId needs read access to that service.
  • projectId counts the services in that project you can read.
  • With neither, you get the services you can read across your projects. Platform admins in a signed-in dashboard session see every project.
  • API tokens and connectors must pass serviceId or projectId (400 otherwise).

GET /api/roadmap/kpis scopes its exposure counts the same way, with or without projectId.

GET /api/traces without serviceId lists traces of the services and environments you can read, plus public playground traces. GET /api/traces/{traceId} needs read access to the trace's service, except for playground traces.


Public Demo Service

The pixel-grid service (4,096 boolean flags — a 64×64 grid where flag px-N is cell N) is a designated public demo service. The standard core endpoints below work unauthenticated against it — no token required. No special transport is involved.

List the grid

GET /api/flags?serviceId=pixel-grid&environment=development&limit=4096

When serviceId is a public demo service, projectId may be omitted and the page-size cap relaxes to 4,096 (the whole grid in one call). For every other service, projectId and a read-scoped token are still required.

Sparse fieldsets — pass ?fields=key,enabled to project each flag to just the named fields (whitelist: key, name, description, type, enabled, defaultValue, serviceId, environment, tags, variants, targeting, isPublic, createdAt, updatedAt). For the full grid this cuts the response from ~2.3MB of flag documents to ~140KB. Works on authenticated lists too.

Conditional requests — public demo list responses carry a weak ETag over the result set. Send it back as If-None-Match; when nothing changed the response is 304 Not Modified with an empty body, so a client that polls the grid pays for a round trip, not a download.

Evaluate the grid

POST /api/flags/evaluate/batch
{
  "serviceId": "pixel-grid",
  "environment": "development",
  "flags": [{ "key": "px-0", "defaultValue": false }, "..."]
}

Public demo services may batch up to 4,096 flags per request (the normal cap is 100) and skip token auth. All flags in the service are also isPublic, so POST /api/flags/evaluate works flag-by-flag too.

Stream updates

GET /api/flags/stream?serviceId=pixel-grid&environment=development

The standard SSE stream, open without a token for demo services. Each message is a data: JSON payload — type: "connected" on open, then type: "flag-update" per mutated flag with the full flag object included (flag.enabled, flag.updatedAt, …).

Write to the grid

PATCH /api/flags/bulk
{
  "flags": [
    {
      "key": "px-0",
      "serviceId": "pixel-grid",
      "environment": "development",
      "updates": { "enabled": true }
    }
  ]
}

When every serviceId in the request is a public demo service, bulk updates run unauthenticated — the demo grid is intentionally shared and mutable. Public writes are constrained:

  • Only updates.enabled is applied; all other fields are ignored.
  • Up to 4,096 flag updates per request (normal cap is 100).
  • One write per IP per 2 seconds.
  • Writes are attributed to a public-demo actor in the audit log.

Summary responses — PATCH /api/flags/bulk?summary=true returns only {success,total,succeeded,failed} instead of the per-flag result array (~50B vs ~2.6MB for a full-grid write). Works on authenticated calls too.

Any non-demo service in the same request reverts to the normal CSRF + write-token requirements — public access never crosses service boundaries.


Flag Management

List Flags

GET /api/flags?projectId=proj-1&serviceId=web-app&environment=production

Query parameters:

ParameterTypeDescription
projectIdstringRequired. Project ID
serviceIdstringFilter by service
environmentstringdevelopment, staging, or production
limitnumberMax 100, default 50
offsetnumberOffset-based pagination
cursorstringCursor-based pagination
cursor_directionstringnext or prev
searchstringSearch flag keys and names
tagsstringComma-separated tag filter
enabledbooleanFilter by enabled state
typestringboolean, string, number, or object

With serviceId, the list needs read on that service (and on environment when given), so access overrides and service- or environment-scoped tokens apply. Listings leave out flags in services or environments the caller's access overrides set to none, or that a scoped token doesn't cover.

Callers who reach the project only through a public floor (the shared demo or showcase, with no membership) see createdBy and updatedBy only when they are themselves or system; anyone else's id is "redacted". The same applies to the flags returned by GET and PATCH /api/flags/{key}, POST /api/flags/{key}/toggle, POST/PATCH /api/flags/bulk, rollback to a version, and the snapshots in GET /api/flags/{key}/history. Anonymous reads of the public demo service see no user id except the demo actor's (public-demo). Exports never include these fields.

Response:

{
  "flags": [...],
  "total": 42,
  "limit": 50,
  "offset": 0,
  "hasMore": false,
  "nextCursor": null,
  "prevCursor": null
}

Multi-Language Examples

curl -s "https://flaggr.dev/api/flags?projectId=proj-1&serviceId=web-app&environment=production&limit=10" \
  -H "Authorization: Bearer fgr_abc123xxxxxxxxxxxx" | jq

Create Flag

POST /api/flags
{
  "key": "checkout-v2",
  "name": "Checkout V2",
  "description": "New checkout flow",
  "type": "boolean",
  "enabled": false,
  "defaultValue": false,
  "serviceId": "web-app",
  "environment": "production",
  "tags": ["checkout", "experiment"],
  "variants": [
    { "name": "control", "value": false, "weight": 50 },
    { "name": "treatment", "value": true, "weight": 50 }
  ],
  "targeting": [],
  "isPublic": false
}

Returns 201 with the created flag. Triggers flag.created event (Pub/Sub + webhooks), saves version snapshot, and writes audit log.

overrides in the request are stored as the flag's own overrides, as PATCH /api/flags/{key} stores them (and as each item of POST /api/flags/bulk does), and serve from the first evaluation. Like every flag write they are held to the data plane's per-flag limits: a flag they push past (for example 50 overrides with 250-element values) gets 422 with "code": "FLAG_NOT_SERVABLE" and nothing is created.

Needs write on the service and environment (access overrides and narrow token scopes apply). In an environment that requires approval: 409 APPROVAL_REQUIRED — create the flag elsewhere and promote it.

A defaultValue that isn't a value of the flag's type gets 400 (Default value must be a boolean, and so on), and a flag the evaluation API couldn't load gets 422 with "code": "FLAG_NOT_SERVABLE"; nothing is created. See Refused Flag Writes.

Multi-Language Examples

curl -s -X POST https://flaggr.dev/api/flags \
  -H "Authorization: Bearer fgr_abc123xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "X-CSRF-Token: $CSRF_TOKEN" \
  -d '{
    "key": "checkout-v2",
    "name": "Checkout V2",
    "description": "New checkout flow",
    "type": "boolean",
    "enabled": false,
    "defaultValue": false,
    "serviceId": "web-app",
    "environment": "production",
    "tags": ["checkout", "experiment"],
    "variants": [
      { "name": "control", "value": false, "weight": 50 },
      { "name": "treatment", "value": true, "weight": 50 }
    ],
    "targeting": [],
    "isPublic": false
  }' | jq

Get Flag

GET /api/flags/{key}?serviceId=web-app&environment=production

Public-floor callers see createdBy/updatedBy redacted as in List Flags.

Update Flag

PATCH /api/flags/{key}?serviceId=web-app&environment=production

Send a partial update — only include fields you want to change:

{
  "enabled": true,
  "targeting": [
    {
      "id": "beta-users",
      "conditions": [
        { "property": "betaUser", "operator": "equals", "value": true }
      ],
      "value": true
    }
  ]
}

In an environment that requires approval: 202 with { message, changeRequest } instead of the change; 503 APPROVAL_CHECK_UNAVAILABLE when the environment can't be checked; 403 (code: "APPROVAL_REQUIRED") for public-floor callers of the shared demo/showcase, who can't open change requests.

A targeting list is merged onto the flag as it is now, under the flag's rollout lock:

  • rollout-engine rules (rollout-<planId>) never come from the request: one the flag doesn't carry is dropped, and one it carries keeps the engine's share and conditions;
  • a live (active or paused) plan's rule stays even if the list leaves it out (cancel the plan or abort the canary to remove it);
  • a rule left by a plan that is no longer live (completed, failed, rolled back, cancelled or deleted) is removed when the list leaves it out.

Every other rule is yours as sent. 409 BUSY when another change holds the flag's lock; nothing is written.

A rule's rolloutPercentage and a variant's weight are whole numbers from 0 to 100, a schedule's recurrence.daysOfWeek are whole numbers from 0 (Sunday) to 6 (at most 7 of them), and a condition group needs at least one condition (here and in POST /api/flags); others get 400 ("error": "Validation Error", with the field in details). A rule with no conditions and no condition groups matches everyone (a data plane from before Flaggr 0.5.0 matches it to nobody; see Targeting Rules).

A defaultValue that isn't a value of the flag's type gets 400 (Default value must be a boolean (the flag's type is boolean)), and an update that would leave a flag the evaluation API couldn't load gets 422 FLAG_NOT_SERVABLE. Both are checked before an environment that requires approval opens a change request, so none is opened for a change that can't apply, and nothing is written. See Refused Flag Writes.

Delete Flag

DELETE /api/flags/{key}?serviceId=web-app&environment=production

409 APPROVAL_REQUIRED in an environment that requires approval. While a live (active or paused) rollout plan manages the flag in that environment, the delete is refused with 409 { "code": "ROLLOUT_IN_PROGRESS", "rolloutPlan": { "id", "status", "name" } } — cancel the plan (or abort the canary) or let it finish first. 409 BUSY means another change held the flag's rollout lock; retry. Nothing is deleted in either case.

Toggle Flag

POST /api/flags/{key}/toggle?serviceId=web-app&environment=production

Flips the enabled state (or explicitly sets it when passing {"enabled": boolean} in the JSON body). Broadcasts real-time updates over SSE, records a version snapshot and audit log entry, and purges Redis cache keys asynchronously via serverless durability lifecycles. The flag's updatedBy is set to the caller (before, it kept naming the previous editor).

In an environment that requires approval: 202 with { message, changeRequest }; 503 APPROVAL_CHECK_UNAVAILABLE when the environment can't be checked; 403 for public-floor callers of the shared demo/showcase.

Refused Flag Writes

https://api.flaggr.dev loads a service's flags in one environment as a single snapshot, so one flag it can't load makes it answer 503 for every flag of that service and environment. Flaggr refuses a write that would leave such a flag, whichever route makes it, and writes nothing.

A default of the flag's type. A boolean flag's default is a boolean, a string flag's a string, a number flag's a finite number, and an object flag's a JSON object (an array or null isn't one).

  • POST /api/flags and POST /api/flags/bulk answer 400 ("error": "Validation Error", with the problem in details and, when it's the only one, in message): Default value must be a boolean, Default value must be a string, Default value must be a number or Default value must be a JSON object (not an array or null).
  • PATCH /api/flags/{key} answers 400 the same way, with the flag's type added (Default value must be a boolean (the flag's type is boolean)), before it opens a change request in an environment that requires approval.
  • A flag_update change request is refused with 400 (Invalid flag update: Default value must be a boolean (the flag's type is boolean)) when it's opened and again when it's applied; an approved request stays approved.
  • PATCH /api/flags/bulk refuses only that item, with FLAG_NOT_SERVABLE.

The data plane's per-flag limits. A flag must also be one the data plane can decode.

  • The request schemas stop most of its limits first, with a 400 ("error": "Validation Error"): POST and PATCH /api/flags and the bulk routes refuse more than 100 rules, 50 variants, 50 overrides or 20 tags, a key of more than 100 characters, and a rollout percentage, variant weight, override priority or schedule day that isn't a whole number. The imports check an item's key, rules, variants and tags the same way, and list one that fails in errors with the first problem (and, for rules, variants and tags, the field's path) and no code.
  • What the schemas don't express is checked on the flag as it would be stored: at most 10,000 conditions, 1,000 condition groups and 10,000 override identifiers, 100 prerequisites, at most 10,000 JSON values across the flag's values, nested at most 64 deep, and a key of at most 512 bytes without control characters (the imports hold a key to 100 characters first, so they never answer for it). A write that leaves a flag outside those limits answers 422:
{
  "error": "Flag \"allow\" can't be saved: the evaluation API couldn't load it (targeting[0].conditions[0].value exceeds dynamic JSON nodes). One flag it can't load stops every flag of its service in production from evaluating there.",
  "code": "FLAG_NOT_SERVABLE"
}

The parenthesis names the field path and the limit, never a value. A writer that doesn't go through the request schemas (a version rollback, applying a change request opened earlier, the RUM optimizer, bandit reallocation, the LaunchDarkly migration, environment promotion) is held to every limit, the schemas' too: 100 rules, 50 variants and overrides, 100 tags, and whole numbers. 422 FLAG_NOT_SERVABLE comes from:

  • POST /api/flags, and PATCH /api/flags/{key} (before it opens a change request);
  • POST /api/flags/{key}/rollback/{version}, when the version's snapshot would leave a flag the data plane can't load;
  • opening a flag_update change request (POST /api/projects/{id}/change-requests) and applying one (POST /api/projects/{id}/change-requests/{requestId}/apply; the request stays approved);
  • POST /api/flags/{key}/optimize-rum and POST /api/experiments/{id}/reallocate.

These refuse the one flag with "code": "FLAG_NOT_SERVABLE" in its own entry and go on with the rest: POST /api/flags/bulk and PATCH /api/flags/bulk (results[]), POST /api/flags/import and POST /api/projects/{id}/import (errors[]), POST /api/migrate/launchdarkly (refusals[] in the preview, failures[] on apply) and environment promotion (refused[]).

Promotion (POST /api/projects/{id}/environments/{source}/promote, and an approved promotion change request) never copies a default, variants or rules onto a target flag of another type: that flag is listed in refused with "code": "FLAG_TYPE_MISMATCH" (promote only enabled, which still copies across types, or give the flag one type in both environments), and the others are promoted. It answers 409 with the first refusal's code when nothing was promoted; an approved change request that was only partly applied answers 409 too, with promoted and refused, and stays approved.

A write that changes only enabled, name, description, up to 100 tags or a boolean, string or number default of the flag's type isn't checked against the whole flag, and a flag that is already one the data plane can't load (stored before this check) can still be updated, so a kill switch or a fix always lands. The data plane's limits on a whole snapshot (4 MiB encoded and 10,000 flags per service and environment) can't be checked one flag at a time, so they aren't checked when a flag is written.

Post-Toggle Safety & Drift Analysis

GET /api/flags/{key}/toggle-impact?serviceId=web-app&environment=production&range=24h&windowMinutes=30

Evaluates post-toggle safety, health, and performance drift by comparing metrics before and after the latest toggle event.

Query parameters:

ParameterRequiredDescription
serviceIdYesService identifier
environmentNoEnvironment filter (e.g. production, staging, development)
rangeNoTime range for evaluation discovery: 1h, 24h, 7d, 30d (default 24h)
windowMinutesNoComparison window duration before/after toggle (e.g. 15, 30, 60)

Response:

{
  "flagKey": "checkout-v2",
  "serviceId": "web-app",
  "environment": "production",
  "range": "24h",
  "impact": {
    "hasRecentToggle": true,
    "latestToggle": {
      "id": "audit-f9e4a8b2",
      "timestamp": "2026-09-12T08:00:00.000Z",
      "timestampMs": 1789200000000,
      "actor": "release-engineer@flaggr.dev",
      "actorId": "user_8f3c2a",
      "transition": { "from": false, "to": true },
      "environment": "production",
      "durationMs": 42
    },
    "healthStatus": "healthy",
    "windowMinutes": 30,
    "before": {
      "evaluations": 1200,
      "errors": 2,
      "errorRate": 0.0017,
      "avgLatencyMs": 1.5,
      "p99LatencyMs": 4.2
    },
    "after": {
      "evaluations": 1250,
      "errors": 1,
      "errorRate": 0.0008,
      "avgLatencyMs": 1.48,
      "p99LatencyMs": 4.15
    },
    "delta": {
      "errorRateDelta": -0.0009,
      "latencyP99DeltaMs": -0.05,
      "evaluationsRatio": 1.04
    },
    "recommendation": "Healthy: Post-toggle metrics are stable with no significant error or latency regression."
  },
  "recentToggles": [
    {
      "id": "audit-f9e4a8b2",
      "timestamp": "2026-09-12T08:00:00.000Z",
      "timestampMs": 1789200000000,
      "actor": "release-engineer@flaggr.dev",
      "transition": { "from": false, "to": true },
      "environment": "production",
      "durationMs": 42
    }
  ]
}

Every toggle entry (impact.latestToggle, recentToggles[]; the same data appears in GET /api/flags/{key}/metrics and GET|POST /api/flags/{key}/auto-rollback) carries actorId, the user id behind actor. Callers who reach the project only through the shared demo's or showcase's public access see actor: "Another member" and actorId: "redacted" on other people's toggles. Their own toggles and the system's are shown as they are. In the auto-rollback response, the restored flag shows createdBy/updatedBy only when that is them or system.

Flag Evaluation Metrics & Time Series

GET /api/flags/{key}/metrics?serviceId=web-app&environment=production&range=24h

Returns comprehensive evaluation metrics, real-time rates, value and reason breakdowns, time-series data, and correlated toggle impact analysis.

Query parameters:

ParameterRequiredDescription
serviceIdYesService identifier
environmentNoEnvironment filter
rangeNoTime range: 1h, 24h, 7d, 30d (default 24h)

Response:

{
  "flagKey": "checkout-v2",
  "serviceId": "web-app",
  "environment": "production",
  "source": "memory",
  "range": {
    "start": 1789113600000,
    "end": 1789200000000,
    "rangeLabel": "24h",
    "minutes": 1440
  },
  "summary": {
    "totalEvaluations": 48500,
    "totalErrors": 24,
    "errorRate": 0.0005,
    "avgLatencyMs": 1.42,
    "p50LatencyMs": 1.1,
    "p95LatencyMs": 3.8,
    "p99LatencyMs": 6.2,
    "evaluationsPerMinute": 33.68,
    "evaluationsPerSecond": 0.56
  },
  "realtime": {
    "evaluationsPerSecond": 1.2,
    "evaluationsPerMinute": 72,
    "evaluationsLastMinute": 72,
    "evaluationsLast5Min": 340,
    "errorRateLastMinute": 0,
    "trend": "stable",
    "lastEvaluatedAt": "2026-09-12T08:15:00.000Z",
    "topReason": "TARGETING_MATCH"
  },
  "toggleImpact": { ... },
  "recentToggles": [ ... ],
  "reasonBreakdown": {
    "TARGETING_MATCH": 38200,
    "DEFAULT_VALUE": 10276,
    "ERROR": 24
  },
  "valueBreakdown": {
    "true": 38200,
    "false": 10300
  },
  "timeSeries": [
    {
      "timestamp": 1789113600000,
      "evaluations": 2040,
      "errors": 1,
      "avgLatencyMs": 1.38,
      "p50LatencyMs": 1.05,
      "p95LatencyMs": 3.5,
      "p99LatencyMs": 5.9
    }
  ]
}

Flag Audience

GET /api/flags/{key}/audience?serviceId=web-app&environment=production&range=7d&pages=1

Who received the flag: browser sessions on the service's Sites whose flag stamp contains the key, split by served value (variants), country, browser, device and OS. Repeat filter to narrow the audience (filter=country:in:AU,NZ, filter=browser:not_in:Safari); exposed is always the unfiltered session count and matched the filtered one. Needs read access to the service and environment.

pages=1 adds the top pages, counted from pageview events: they leave out pageviews the ingest marked untrusted unless a member adds includeUntrusted=1 (callers on a public project's floor can't). The session counts come from session rows, which carry no trust marks, so they include every session.

Automated Guardrail Circuit Breaking & Rollback

POST /api/flags/{key}/auto-rollback
GET /api/flags/{key}/auto-rollback?serviceId=web-app&environment=production

Evaluates post-toggle safety drift and automatically reverts the feature flag to its previous version snapshot if health metrics are degraded. Also supports dry-run preview mode.

Rollout plans: when a live (active or paused) rollout plan manages the flag in that environment, the rollback cancels the plan instead, removing only its rollout-<planId> rule and keeping every other edit. The response carries rolloutPlan: { id, name, status, ruleId }; in a dry run it shows what would be cancelled. Otherwise the previous version is restored without rollout-engine rules: a snapshot's are never re-added, and the flag's leftover ones — rules of completed, failed, rolled-back, cancelled or deleted plans — are removed and listed in removedRolloutRuleIds (a dry run lists what it would remove). Hand-named rules such as rollout-eu are restored like any other rule. In an environment that requires approval nothing is restored: the response has actionTaken: "none", approvalRequired: true and a reason pointing at rollback to a version, which opens a change request. 409 with ROLLOUT_IN_PROGRESS or BUSY means a plan went live, or another rollout change held the flag, while the breaker ran; run it again.

Request body (or query parameters):

FieldTypeDescription
serviceIdstringService identifier (required)
environmentstringTarget environment (default: production)
dryRunbooleanIf true, returns what action would be taken without mutating flag state
maxErrorRateDeltanumberMaximum allowed error rate increase before tripping, above 0 and at most 1 (default: 0.02 for +2%)
maxLatencyDeltaMsnumberMaximum allowed P99 latency increase in ms, above 0 (default: 200)
windowMinutesnumberPre/post toggle evaluation window in minutes, above 0 and at most 1440

Values outside those ranges return 400; omitted or null values use the defaults.

Response:

{
  "flagKey": "checkout-v2",
  "serviceId": "web-app",
  "environment": "production",
  "actionTaken": "rolled_back",
  "reason": "Rollback completed: Guardrails tripped due to error rate surge +5.00%. Flag reverted to version 2.",
  "tripped": true,
  "targetVersionNumber": 2,
  "alertNotifiedChannels": ["ch-slack-prod", "ch-pagerduty"]
}

When a live rollout plan was cancelled instead, the response also carries "rolloutPlan": { "id": "plan_123", "name": "Checkout ramp", "status": "active", "ruleId": "rollout-plan_123" }.

RUM Optimization & Site Guardrails

POST /api/flags/{key}/optimize-rum
GET  /api/sites/{id}/guardrails
POST /api/sites/{id}/guardrails

Both need write on the flag's (site's) service and environment; a dry run needs read. A real run is refused in an environment that requires approval (optimize-rum 409 APPROVAL_REQUIRED; guardrails report the flag with action: "blocked" and a code) and while a live rollout plan manages the flag (409 ROLLOUT_IN_PROGRESS / blocked). 422 FLAG_NOT_SERVABLE when the optimization would leave a flag the evaluation API couldn't load (Refused Flag Writes). Guardrail mitigations are blocked with APPROVAL_REQUIRED, ROLLOUT_IN_PROGRESS, FORBIDDEN (no write on that flag) or BUSY, dry runs included. Guardrails only touch flags of the site's own project and refuse a site whose service is in another project (409 SITE_SERVICE_MISMATCH), or a site created before site ids were server-generated whose id belongs to other data (409 SITE_ID_NOT_OWNED); delete such a site and create it again.

Sites

GET    /api/sites?projectId=proj-1
POST   /api/sites
GET    /api/sites/{id}
PATCH  /api/sites/{id}
DELETE /api/sites/{id}
GET    /api/sites/{id}/health
POST   /api/sites/{id}/flags
GET    /api/flags/{key}/sites?serviceId=web-app
POST   /api/flags/{key}/sites

POST /api/sites generates the site id (site_…), which goes in the browser analytics tag (<script src="https://cdn.flaggr.dev/a.js" data-site-id="site_…" defer></script>); the optional slug is a label. GET /api/sites/{id}/health, GET and POST /api/sites/{id}/guardrails, POST /api/sites/{id}/flags (link) and POST /api/flags/{key}/sites (link) answer 503 SITE_CHECK_UNAVAILABLE (it was 409) when the site's integrity check can't run; retry. 409 stays for SITE_ID_NOT_OWNED and SITE_SERVICE_NOT_IN_PROJECT. Public-floor callers see a site's createdBy only when it is themselves or system, otherwise "redacted". This includes the site lists of GET /api/flags/{key}/sites.

Project Stale Flags & Technical Debt Analysis

GET /api/projects/{id}/stale-flags

Scans all flags in a project to discover candidates for codebase cleanup, archiving, or deletion based on evaluation inactivity and 100% rollout duration.

Response:

{
  "total": 5,
  "staleCount": 2,
  "inactiveCount": 1,
  "launchedCount": 1,
  "potentialTechDebtFlags": 3,
  "reports": [
    {
      "flagKey": "legacy-auth",
      "serviceId": "svc-auth",
      "environment": "production",
      "status": "stale",
      "category": "stale_rolled_out",
      "daysInactive": 0,
      "daysSinceLastMutation": 45,
      "rolloutPercentage": 100,
      "stalenessScore": 90,
      "recommendation": "100% rolled out for 45 days. Candidate for permanent code migration.",
      "codeRemovalAdvice": "Replace flag('legacy-auth') check with true branch; delete fallback code."
    }
  ]
}

Organization Alert Channels

GET /api/orgs/{orgId}/alert-channels
POST /api/orgs/{orgId}/alert-channels
DELETE /api/orgs/{orgId}/alert-channels/{channelId}
POST /api/orgs/{orgId}/alert-channels/{channelId}/test
PATCH /api/orgs/{orgId}/alert-channels/{channelId}

Manage organization-wide alert destinations (Slack, Discord, PagerDuty, Email, Webhook) automatically inherited by all projects in the organization.

Project Alert Channels & Metric Sources

GET    /api/projects/{id}/alert-channels
POST   /api/projects/{id}/alert-channels
PATCH  /api/projects/{id}/alert-channels/{channelId}
DELETE /api/projects/{id}/alert-channels/{channelId}
POST   /api/projects/{id}/alert-channels/{channelId}/test
GET    /api/projects/{id}/metric-sources
POST   /api/projects/{id}/metric-sources
GET    /api/projects/{id}/metric-sources/{sourceId}
PATCH  /api/projects/{id}/metric-sources/{sourceId}
DELETE /api/projects/{id}/metric-sources/{sourceId}
POST   /api/projects/{id}/metric-sources/{sourceId}/test

Reads need project read access; creating, changing, deleting and testing need write. The channel list includes the channels the project inherits from its organization. A metric-source test body's serviceId must be a service of this project (404 otherwise) that you can read, and flagKey must be a flag of that service. Testing an internal source needs a serviceId (400).

Secrets in config. Credentials in config — webhook URLs, signing secrets, PagerDuty routing keys, API keys and tokens, auth header values — are returned only to callers who can manage the owner's settings: project admins/owners, or org owners/admins for org channels, using a session or an admin-tier credential. Everyone else sees "[redacted]". Send "[redacted]" back unchanged on update to keep the stored value; creating a source or channel with a placeholder returns 400.

An update that keeps a "[redacted]" placeholder while changing where the config sends that secret needs the same manage-settings access as reading the secret; otherwise it gets 403. "Where it sends it" means a URL, endpoint or host, the Datadog site, the CloudWatch or New Relic region, the SignalFx realm, the Grafana Cloud stackSlug, email recipients, or the channel type. To change the destination without that access, retype the secrets.

Visitors of the shared demo (no membership) can read the demo project's metric sources and alert channels but can't create, change, delete or test them (403). They don't see who a channel delivers to: an email channel's recipients, to, cc and bcc, and any email address or direct @-mention elsewhere in a channel's or metric source's config, read "[redacted]". This covers the project's own channels and the organization channels it inherits (the showcase inherits org-flaggr's). A metric source's createdBy shows as "redacted" unless it is the visitor's own id or system. Project members see recipients; credentials still need manage-settings access.

SDK Ingest & Telemetry Analytics

POST /api/analytics/sdk-telemetry
GET /api/analytics/sdk-telemetry?siteId=site_3f9c…&range=24h
Authorization: Bearer <token>

Ingests batched client-side telemetry (flag evaluation summaries, Core Web Vitals, errors, page views, sessions and conversions) and serves aggregated reports correlated with active feature flags. Browser analytics from the https://cdn.flaggr.dev/a.js script goes to a separate ingest; see Analytics API.

Reads need authentication and read access to the project that owns the data. siteId resolves to the site's owning project (a projectId that names a different project is ignored), serviceId resolves to the service's project, and projectId alone reads that project's events. Without any of them the request uses the credential's single bound project, otherwise 400. siteId=default (beacons that named no project or site) returns 404. Without credentials, only the public showcase site ids flaggr-marketing and flaggr-showcase can be read, as aggregates (recentErrors and frustrations are empty).

Analytics routes and the public showcase. siteId=default (the shared bucket) answers 404 on every analytics route that takes a siteId; events, overview, vitals, issues, flag-impact, drilldown and mobile-summary used to answer 403. Raw landing-page data of the public showcase (flaggr-marketing, flaggr-showcase, or a showcase project id) is for showcase members. GET /api/analytics/events, GET /api/analytics/flight-recorder, GET /api/analytics/drilldown?kind=render and POST /api/analytics/export answer 403 SHOWCASE_MEMBERS_ONLY to callers who reach the showcase only through its public floor (the export answers 403 MEMBERS_ONLY on the shared demo). The aggregate routes give those callers pages cut at the query string with the console and share links collapsed (/console/*, /f/*), referrers by host, no render traces in GET /api/analytics/vitals, and issues labelled by kind and fingerprint (aggregatesOnly: true on vitals and issues). GET /api/analytics/sdk-telemetry gives them the public report (recentErrors and frustrations empty), as for anonymous callers. Anonymous showcase reads are limited to 60 per minute per IP (429, Retry-After) and served from a 30-second shared cache. POST /api/analytics/export only sends to an https webhook on a public address. See Analytics API — Public showcase data.

Ingest SDK Telemetry (POST)

Ingest needs the project's SDK key or a project API token. Send it as Authorization: Bearer <key>, or, from navigator.sendBeacon (which can't set headers), as apiKey in the JSON body (a text/plain body works). The flaggrTelemetry() plugin of @flaggr/sdk 0.5.0 and later does both; 0.4.0 sends its page-hide batch without the key, and the ingest refuses it with 401.

  • The key decides the project. projectId must be that project, serviceId one of its services, and siteId one of its Sites (or the project id). With a Site, the rows are that Site's service's telemetry: a service-scoped key must cover the Site's service, and a serviceId you send must be it. Otherwise the answer is 403 TELEMETRY_SCOPE_MISMATCH. A batch with only a serviceId is filed under the key's project.
  • Refused credentials. Keys scoped to an environment or to flags can't send telemetry (403 TELEMETRY_FORBIDDEN), and neither can expired keys (an expired fgr_ key gets the same 403, an expired JWT 401 TELEMETRY_AUTH_INVALID). Sessions, connector tokens and unknown keys get 401 TELEMETRY_AUTH_INVALID; personal access tokens get 403 TELEMETRY_CREDENTIAL_NOT_ALLOWED.
  • Without a credential, only Flaggr's own landing-page beacon is accepted (flaggr-marketing or flaggr-showcase, sent from the app's own origin). Everything else gets 401 TELEMETRY_AUTH_REQUIRED and nothing is stored.
  • When a check can't run, the answer is 503 TELEMETRY_CHECK_UNAVAILABLE; retry.
  • Trust marks. Stored rows carry data._src (sdk or beacon), data._c (a daily keyed hash of the client, when the deployment sets ANALYTICS_CLIENT_HASH_SECRET) and data._untrusted: true unless the request's Origin (or Referer without one) is the Site's domain or a subdomain. For telemetry without a Site, it must be the domain of one of the project's Sites. Requests with no Origin, or Origin: null, are untrusted. Rollout RUM checks ignore untrusted rows, and so do the analytics reads: most /api/analytics/* routes report how many rows they left out (excluded), the telemetry report doesn't, and project members can count them with ?includeUntrusted=1 (see Analytics API). Batches from servers send no Origin, so they are always untrusted, but their evaluation summaries still count in evaluation totals, never as visitors or sessions.
  • Scrubbing. URLs and free-text fields are scrubbed before storage as the browser ingest scrubs them: fragments dropped, credential-like values, emails and JWTs redacted (see Analytics API).
  • Bounds per event. A timestamp more than a minute ahead, missing or unparseable is stored as the receive time; events older than 2 hours aren't stored; session ids are at most 128 characters (else the batch's sessionId); URLs and referrers are cut to 4,096 characters; typed fields that don't fit their type (for example a non-numeric value) are dropped; a vital needs a numeric value; flags must be an object (50 entries, keys up to 200 characters, values up to 256).

Request Body:

{
  "serviceId": "web-app",
  "sessionId": "8f6c2a1e-4b7d-4c1a-9e3f-2d5b7a9c0e11",
  "summaries": [
    {
      "flagKey": "checkout-v2",
      "variant": "enabled",
      "evaluations": 1420,
      "cacheHits": 1395,
      "cacheMisses": 25,
      "totalDurationMs": 170.4,
      "minDurationMs": 0.05,
      "maxDurationMs": 2.1
    }
  ],
  "vitals": [
    {
      "metric": "lcp",
      "value": 1420.5,
      "rating": "good",
      "flags": { "checkout-v2": "enabled" },
      "pageUrl": "https://shop.example.com/checkout"
    }
  ],
  "errors": [
    {
      "message": "Payment gateway timeout",
      "stack": "Error: Payment gateway timeout\n    at submitPayment (checkout.js:142)",
      "flags": { "checkout-v2": "enabled" },
      "pageUrl": "https://shop.example.com/checkout"
    }
  ]
}

Each event may carry a timestamp (epoch milliseconds or a date string). A batch may also name siteId and projectId, and carry components, frustrations, pageviews, sessions and conversions lists. metric is one of lcp, cls, inp, fid, fcp, ttfb, tbt or longtask.

Response (200 OK):

{
  "success": true,
  "processed": {
    "summaries": 1,
    "vitals": 1,
    "errors": 1,
    "components": 0,
    "frustrations": 0,
    "pageviews": 0,
    "sessions": 0,
    "conversions": 0
  }
}

The answer comes before the rows are written to Postgres, so processed counts what the batch held, not what was stored.

Query Aggregated Telemetry Report (GET)

Query Parameters:

  • siteId or projectId: whose telemetry to read (see above).
  • serviceId (optional): a service's telemetry; without a siteId it resolves to the service's project.
  • flagKey (optional): only events tagged with that flag.
  • range (optional): 1h, 24h (default), 7d or 30d; any other value reads the last 24 hours.
  • includeUntrusted (optional): 1 or true counts untrusted rows too. Only project members can; callers who reach the project through a public project's floor, and anonymous showcase reads, can't.

The report leaves out the web vitals, errors, flag × vital correlation and rage and dead clicks of untrusted batches, and has no field that counts them. Evaluation summaries count whatever their mark. The rows this server instance still holds in memory are filtered the same way, as are the in-memory reads behind GET /api/flags/{key}/frustrations and GET /api/flags/{key}/component-hotspots. A batch without a Site is checked against the project's Site domains after the response, and reaches the in-memory reads only then.

Response (200 OK):

{
  "projectId": "proj-1",
  "range": "24h",
  "evaluationStats": {
    "totalEvaluations": 45200,
    "cacheHits": 44522,
    "cacheMisses": 678,
    "cacheHitRatio": 0.985,
    "avgLatencyMs": 0.14,
    "p95LatencyMs": 0.4
  },
  "flags": [
    {
      "flagKey": "checkout-v2",
      "evaluations": 25400,
      "cacheHits": 25100,
      "cacheMisses": 300,
      "cacheHitRatio": 0.988,
      "avgResolutionMs": 0.14,
      "variants": { "enabled": 12700, "disabled": 12700 }
    }
  ],
  "webVitals": {
    "lcp": { "p75": 1640.2, "rating": "good", "count": 3120 },
    "cls": { "p75": 0.04, "rating": "good", "count": 3050 },
    "inp": { "p75": 180, "rating": "good", "count": 2980 },
    "fcp": { "p75": 1100, "rating": "good", "count": 3120 },
    "ttfb": { "p75": 420, "rating": "good", "count": 3120 }
  },
  "flagVitalsCorrelation": [
    { "flagKey": "checkout-v2", "variant": "enabled", "lcpP75": 1580.4, "clsP75": 0.03, "inpP75": 170, "count": 1560 }
  ],
  "recentErrors": [
    {
      "message": "Payment gateway timeout",
      "stack": "Error: Payment gateway timeout\n    at submitPayment (checkout.js:142)",
      "flags": { "checkout-v2": "enabled" },
      "pageUrl": "https://shop.example.com/checkout",
      "timestamp": "2026-09-12T11:45:00.000Z"
    }
  ],
  "frustrations": [],
  "frustrationStats": { "totalRageClicks": 0, "totalDeadClicks": 0, "frictionScore": 0, "topTargets": [] }
}

Server Telemetry

POST /api/ingest/server-events
GET  /api/analytics/server-events?projectId=proj-1&kind=error&hours=24&limit=50
GET  /api/analytics/server-events?projectId=proj-1&summary=1&hours=48
Authorization: Bearer <token>

Backend services (the psymatch Go GraphQL API is the first) report errors and request spans with the project's API token; project readers read them back, or the window summary (error/span counts, top error fingerprints, span p50/p95). See Analytics API — Server Telemetry Ingestion: the ingest refuses SDK keys, demo tokens, sessions, connectors and personal access tokens (403/401 codes of its own), an event's serviceId must be one of the token's project's services, and the batch is { "events": [...] } of at most 100 events and 256 KB, answered 202 before the rows are written. Spans are downsampled by trace (failed spans kept), events over a per-project quota are dropped as throttled, and over 120 batches a minute a token gets 429.

Error Issues

GET   /api/projects/{id}/issues?range=24h&source=all&status=unresolved&sort=last_seen&limit=25
PATCH /api/projects/{id}/issues
GET   /api/projects/{id}/issues/{fingerprint}?source=server&range=30d&eventsLimit=25
PATCH /api/projects/{id}/issues/{fingerprint}

The project's browser and server errors grouped by fingerprint, with the status members set (unresolved, resolved, ignored, and regressed for a resolved issue that got a later event). The list returns { issues, total, counts }, where counts gives the window's issues by status. The detail returns the issue's trend, its release, environment, browser, location and service breakdowns, the flag variants its events carried, a page of events (nextCursor), and one event in full (eventId, else the newest), with its stack parsed into frames.

// PATCH /api/projects/{id}/issues — up to 100 issues
{ "issues": [{ "source": "server", "fingerprint": "srv_3f3e97c0ea6a58feebc2" }], "status": "resolved", "resolvedInRelease": "checkout-api@2.8.2" }
// → { "updated": 1, "status": "resolved" }

Reading needs read access, and a status change needs write access. GET /api/projects/{id}/issues/releases?range= returns release health: { releases: [{ release, sessions, crashedSessions, crashFreeRate, events, unhandled, issues, introducedIssues, affected, firstSeen, lastSeen }] }, newest activity first. See the Error Tracking guide.

Source Maps

PUT    /api/projects/{id}/sourcemaps?release=web@1.4.2&file=/_next/static/chunks/app/page-3f9a1c2b.js
GET    /api/projects/{id}/sourcemaps[?release=web@1.4.2]
DELETE /api/projects/{id}/sourcemaps?release=web@1.4.2[&file=...]

Source maps for a release, so the issue detail shows minified frames as the original source. PUT takes one version 3 map as the body, plain or gzipped (Content-Encoding: gzip), up to 4 MiB as sent and 64 MiB decompressed. It answers 201 { release, file, bytes, replaced: false }, or 200 with replaced: true when the file was uploaded before. Errors: 400 SOURCEMAP_INVALID / SOURCEMAP_INVALID_TARGET, 413 SOURCEMAP_TOO_LARGE, 409 SOURCEMAP_RELEASE_FULL (2,000 files). The project keeps its last 20 releases' maps. PUT and DELETE need write access, GET read. See Source maps.

Flag Version History

GET /api/flags/{key}/history?serviceId=web-app&limit=20&offset=0
{
  "versions": [...],
  "total": 15,
  "hasMore": false
}

Public-floor callers (the shared demo or showcase, with no membership) see changedBy, changedByEmail and changedByName only on their own changes; other changes show changedBy: "redacted" and changedByName: "Another member". Each version's snapshot shows createdBy and updatedBy the same way — "redacted" unless it is the caller's own id or system — and diffs are computed between those redacted snapshots.

Rollback to Version

POST /api/flags/{key}/rollback/{version}

Restores the flag's fields from the version snapshot under the flag's rollout lock. Rollout-engine rules (rollout-<planId> of a plan on the flag, or rollout-<uuid>) are never restored from the snapshot, and the flag's leftover ones are removed and listed in removedRolloutRuleIds. 409 ROLLOUT_IN_PROGRESS (with rolloutPlan) while a live rollout plan manages the flag in that environment — cancel it or let it finish; 409 BUSY while another rollout change holds the flag. In an environment that requires approval it returns 202 with a flag_update change request carrying the restored fields. 422 FLAG_NOT_SERVABLE when the snapshot would leave a flag the evaluation API couldn't load (a version saved while the stored flag was one it couldn't load, say); nothing is restored. See Refused Flag Writes.

Flag Code References

GET  /api/flags/{key}/code-refs?serviceId=svc-1&environment=production&repo=acme/web
POST /api/flags/{key}/code-refs

Searches the project's connected GitHub repository for the flag key and lists matching files. Search results are not stored. Requires read access to the service and environment, and actual project membership rather than public demo access.

  • GET supports read-only connectors. No GitHub credential is accepted in the URL or headers.
  • POST takes { "serviceId": "svc-1", "environment": "production", "repo": "acme/web" } and uses the same saved connection. Credentials in a search body are rejected.

A project administrator first configures the repository in Settings → GitHub. The write-only GitHub read credential is verified against that repository, encrypted at rest and never returned to clients. This grants project members and their authorized read connectors code-search access to that repository. Changing or removing the connection requires a dashboard session with project settings permission; API tokens and MCP connectors cannot do it.

repo is owner/name and must match the configured repository (case-insensitive). environment defaults to development in the REST API and production in the MCP tool. Missing setup returns 409 REPOSITORY_NOT_CONFIGURED; a revoked credential returns 424 GITHUB_CONNECTION_INVALID; unavailable repository access returns 403 REPOSITORY_NOT_ACCESSIBLE; GitHub rate limits return 429 GITHUB_RATE_LIMITED; transient upstream failures return 502 GITHUB_UNAVAILABLE. An inaccessible repository is never reported as a successful search with zero matches.

Repository configuration endpoints (credentials never returned):

GET    /api/projects/{id}/github-connection
PUT    /api/projects/{id}/github-connection  { "repo": "acme/web", "token": "…" }
DELETE /api/projects/{id}/github-connection

For self-hosted deployments provided on request, administrators must set GITHUB_CONNECTION_ENCRYPTION_KEY to a persistent random 32-byte key encoded as 64 hex characters. Keep it in the deployment's secret store. Replacing the key requires administrators to reconnect saved repositories; do not rotate it on each deploy.

{
  "flagKey": "checkout-v2",
  "repo": "acme/web",
  "totalCount": 1,
  "refs": [{ "path": "src/checkout.ts", "url": "https://github.com/acme/web/blob/main/src/checkout.ts" }],
  "scannedAt": "2026-10-07T03:00:00.000Z"
}

Bulk Operations

All bulk endpoints accept arrays of flag operations and return per-item results.

Bulk Create

POST /api/flags/bulk
{
  "flags": [
    { "key": "flag-a", "name": "Flag A", "type": "boolean", "serviceId": "web-app", "defaultValue": false },
    { "key": "flag-b", "name": "Flag B", "type": "string", "serviceId": "web-app", "defaultValue": "off" }
  ]
}

A defaultValue that isn't a value of its flag's type fails the whole request with 400 (Validation Error), as in POST /api/flags. A flag the evaluation API couldn't load fails on its own with code: "FLAG_NOT_SERVABLE", and the rest of the batch goes ahead (207).

Bulk Update

PATCH /api/flags/bulk
{
  "flags": [
    { "key": "flag-a", "serviceId": "web-app", "environment": "production", "updates": { "enabled": true } },
    { "key": "flag-b", "serviceId": "web-app", "environment": "production", "updates": { "enabled": false } }
  ]
}

An item whose updates carry targeting is merged onto the flag under its rollout lock, exactly as in Update Flag: rollout-engine rules (rollout-<planId>) stay server-owned, and a live plan's rule always stays. When another change holds the flag's lock, that item fails with code: "BUSY" and the rest of the batch goes ahead. An item whose update would leave a flag the evaluation API couldn't load, a defaultValue that isn't a value of the flag's type included, fails with code: "FLAG_NOT_SERVABLE" (error names the problem, such as defaultValue: Default value must be a boolean), and the rest of the batch goes ahead too. See Refused Flag Writes.

Bulk Delete

DELETE /api/flags/bulk
{
  "flags": [
    { "key": "flag-a", "serviceId": "web-app", "environment": "production" },
    { "key": "flag-b", "serviceId": "web-app", "environment": "production" }
  ]
}

An item a live rollout plan manages fails with code: "ROLLOUT_IN_PROGRESS" and rolloutPlan: { id, status, name } (or code: "BUSY"); the rest of the batch goes ahead (207).

Response (all bulk):

{
  "success": true,
  "total": 2,
  "succeeded": 2,
  "failed": 0,
  "results": [
    { "key": "flag-a", "status": "success", "flag": {...} },
    { "key": "flag-b", "status": "success", "flag": {...} }
  ]
}

Status codes: 201 (all succeed on create), 200 (all succeed on update/delete), 207 (mixed results).

Items in an environment that requires approval are refused per item (status: "error", code: "APPROVAL_REQUIRED"; the batch returns 207) — a batch never opens change requests. A failed environment lookup refuses the whole batch with 503 APPROVAL_CHECK_UNAVAILABLE before anything is written. Access is checked per (service, environment), so service- and environment-scoped tokens work within their scope. Public-floor callers see the returned flags' createdBy/updatedBy redacted as in List Flags.


Export & Import

Export Flags

GET /api/flags/export?projectId=proj-1&serviceId=web-app&format=json&includeDisabled=true

Returns a downloadable JSON file:

{
  "version": "1.0",
  "exportedAt": "2025-07-20T10:00:00Z",
  "projectId": "proj-1",
  "flagCount": 42,
  "flags": [...]
}

Needs read on the project, or on the service when serviceId is given (a service outside the project is 404). Flags whose service or environment the caller's access overrides set to none are left out. Responses are Cache-Control: private, no-store.

Import Flags

POST /api/flags/import

Upload an exported JSON file to restore flags.

Items in an environment that requires approval are reported in errors with code: "APPROVAL_REQUIRED" (dry runs report them too). Overwrites are refused per item while a live rollout plan manages the flag (code: "ROLLOUT_IN_PROGRESS"), and rollout-engine rules (rollout-<uuid>) in the file aren't imported. Service- and environment-scoped tokens can import into their own scope.

Each item's targeting and variants are checked as POST /api/flags checks them: rules and variants of the documented shape, whole-number percentages and weights from 0 to 100, and condition groups with at least one condition. An item that fails is listed in errors with the first problem and its path (targeting[0].rolloutPercentage: Rollout percentage must be a whole number (0-100)), dry runs included, and isn't written. The project import (POST /api/projects/{id}/import) checks its flags the same way.

Each item is also held to what POST /api/flags takes, dry runs included, and one that fails is listed in errors and isn't written:

  • A default must be a value of the item's type; an object flag's default is a JSON object, never an array or null.
  • tags are at most 20 strings of 1 to 50 characters (an import used to store them as sent), and a schedule's recurrence.daysOfWeek are whole numbers from 0 (Sunday) to 6, at most 7 of them.
  • A null in an optional field counts as not set (exports of flags stored by older builds carry them): in the variants, targeting and tags lists themselves; in a rule's conditions, conditionOperator, groups, groupOperator, rolloutPercentage, variant and schedule (and the schedule's own fields); and in a condition's cohortId and a variant's weight. A value is never touched.
  • Both imports keep an existing flag's type: an overwrite of an item whose type differs from the stored flag's is refused with code: "FLAG_TYPE_MISMATCH" and the message Flag "x" has type string in production, and the file gives it type boolean: an import can't change a flag's type. Import it with type string, or delete the flag first. (dry runs included; POST /api/projects/{id}/import lists it in errors with type: "flag", name, environment and code).
  • conflictResolution: "overwrite" replaces the stored flag with the item: its name, description, enabled, default, tags, variants and rules become what the item says, and what the item leaves out is cleared (enabled becomes false, and this import also resets isPublic to private; the project import keeps the flag's own isPublic). The flag's type, overrides and prerequisites stay as they are.
  • A flag key is held to the rule of POST /api/flags: 1 to 100 characters, a letter first, then letters, digits, hyphens and underscores. A longer key is refused with Flag key must be 100 characters or less (the imports took a key of any length that matched the pattern before 0.5.0).
  • name is a string of 1 to 200 characters and description a string of at most 1,000; enabled is true or false; POST /api/flags/import also takes isPublic as true or false only. An import reads a null as left out (POST /api/flags refuses one), and enabled is then false, as it is when left out in POST /api/flags. Anything else is refused with the message of the rule (Flag name must be 200 characters or less, Description must be 1000 characters or less, Enabled must be true or false, isPublic must be true or false) as an errors entry without a code.
  • An item's overrides, prerequisites and projectId are ignored: an import never writes them (a new flag has none, an overwrite keeps the flag's own), so they are not checked and can't refuse an item.
  • A file that lists one flag (the same key and environment) twice is settled by conflictResolution as a stored flag would be: the repeat is skipped, listed in errors (Flag already exists: <key> (<environment>)), or overwrites the first item.
  • A flag the evaluation API couldn't load is listed with code: "FLAG_NOT_SERVABLE" (see Refused Flag Writes); an overwrite is checked as the row it leaves too, the item's content over the flag's own overrides and prerequisites, which stay (dry runs included). The project import (POST /api/projects/{id}/import) checks its flags the same way, and POST /api/migrate/launchdarkly refuses a mapped flag whose default isn't a value of its type, or whose key, environment, name, description or on the flag API wouldn't take, with code: "VALIDATION_ERROR" (a name or description that is too long is trimmed, with a warning, instead; see Migrate from LaunchDarkly). Details: Import & Export.

A new flag can't take a reserved key (bulk, create-from-nl, evaluate, evaluate-debug, export, import, stream). POST /api/flags and POST /api/flags/bulk answer 400 for one; the other paths that create flags refuse it per item: this import, the project import (POST /api/projects/{id}/import), the LaunchDarkly migration (POST /api/migrate/launchdarkly) and environment promotion (POST /api/projects/{id}/environments/{source}/promote). Such items are refused one by one with code: "FLAG_KEY_RESERVED" and the rest go ahead: import errors[] (dry runs included), migration refusals[] (dry run) and failures[] (apply), promotion refused[] (409 when nothing was promoted). An existing flag with such a key can still be overwritten by an import or promoted onto.


Projects

List Projects

GET /api/projects

Returns all projects the authenticated user has access to, including their role. Sessions and personal access tokens also see the shared demo (flaggr-demo-project, role member) and the showcase (flaggr-showcase, role viewer). Bound credentials (project API tokens, connectors) only see the projects they are bound to. Each project has an accessVia: membership (a direct membership), organization (through an organization role), or public (the shared demo or showcase, which every signed-in user can view).

Create Project

POST /api/projects
{
  "name": "My Project",
  "description": "Feature flags for the platform",
  "slug": "my-project",
  "tags": ["platform"],
  "orgId": "org-flaggr"
}

The creator is automatically assigned the owner role.

orgId is optional: any organization you belong to (API-created orgs have UUID ids; seeded ones use readable ids such as org-flaggr). It is required when you belong to more than one organization (400 otherwise). Project API tokens can't create projects (403) — use a personal access token with the admin tier, or the dashboard. Connectors need the admin tier and can create a project only in an organization that already contains one of their consented projects, or in a brand-new organization you created that has no projects yet. Billing members of an organization can't create projects in it (403), including when orgId defaults to your only organization.

Get Project

GET /api/projects/{id}

Responses never include settings.demoApiToken (server-managed).

Get Project by Slug

GET /api/projects/by-slug/{slug}

Responses never include settings.demoApiToken (server-managed). The project includes viaFloor: true when the caller has no membership and reaches the project only through a public floor (the shared demo or showcase), false otherwise. The console uses it to hide actions floor callers can't take (change requests, alert rules, incident notes and assignments, capability links).

Public-floor callers of GET /api/projects/{id}, GET /api/projects/by-slug/{slug} and the floor entries of GET /api/projects see createdBy, settings.rolloutGovernance.guardrailDefaults.updatedBy (and its copy in settings.configuration.core) and settings.ai.judgeProfiles[].createdBy only when they are themselves or system; anyone else's id reads "redacted".

Project Overview

GET /api/projects/{id}/overview?hours=720&environment=production

The console Overview's data: KPIs for the window and the window before it (active flags, evaluations, errors, active rollouts, exposed sessions, policy violations), the exposure chart and browser vitals. Optional teamId limits the KPIs to one team's flags and exposureFlag picks the flag the exposure chart shows. Needs read access to the project.

vitals comes from the web vitals of the project's Sites and leaves out the ones the ingest marked untrusted. vitalsExcluded ({ untrustedEvents, untrustedSessions }) counts what it left out in the current window: zeros when the project has no analytics, null when a member counted them with ?includeUntrusted=1 (callers on a public project's floor can't). The exposure numbers come from session rows, which carry no trust marks, so they count every session.

Update Project

PATCH /api/projects/{id}

Requires manage_settings permission. Only owners can change a slug, and project API tokens never can. Resending the current slug unchanged (as the Terraform provider does) is not a slug change. settings.demoApiToken is server-managed and ignored if sent. Setting settings.demoEnabled: false revokes the demo's SDK key.

Delete Project

DELETE /api/projects/{id}

Requires delete_project permission. Cascade-deletes all resources and revokes the project's API tokens. Only dashboard sessions and admin personal access tokens created with owner actions can delete a project; API tokens and connectors get 403.

Demo SDK Key

GET /api/projects/{id}/demo/token

Returns { "token": "fgr_…", "serviceId": "…" } for a project with the demo enabled — the demo page's evaluation-only SDK key. It evaluates flags; every management route refuses it. Only a signed-in dashboard session can fetch it: API tokens, personal access tokens and connectors get 403. Sent with Cache-Control: private, no-store. 404 when the demo isn't enabled. The key is minted on first use and attributed to the platform, not to the caller. POST /api/projects/{id}/demo/setup no longer returns it.

Demo Setup

POST /api/projects/{id}/demo/setup

Creates the project's demo service (<projectId>-demo-service) and sample flags, only in environments that don't require approval (the others are listed in data.skippedEnvironments; 409 APPROVAL_REQUIRED when every environment requires approval, 503 APPROVAL_CHECK_UNAVAILABLE when that can't be checked). Repeating it on a demo that is already set up (alreadySetup: true) refreshes synthetic metrics and support data only for the project's own demo service (<projectId>-demo-service or a service of the project tagged demo), never for a real service the demo points at.


Services

List Services

GET /api/services?projectId=proj-1&limit=50&search=web

Create Service

POST /api/services
{
  "projectId": "proj-1",
  "name": "Web App",
  "description": "Frontend web application",
  "tags": ["frontend"]
}

Get / Update / Delete Service

GET    /api/services/{id}
PATCH  /api/services/{id}
DELETE /api/services/{id}
GET    /api/services/by-slug/{slug}?projectId=proj-1

These routes check access on the service itself. A member's access override for the service applies (none → 403), and a service-scoped token works on its own service: service:<id>:read for GET /api/services/{id} and its /history, /metrics (with ?flagKey=, flag scopes count too), /health, /lifecycle, /stale-flags and GET /code-refs; :write for PATCH and POST /code-refs; :admin for DELETE. GET /api/services/by-slug/{slug}?projectId= answers 401 before any lookup and checks the found service's scope; a slug that doesn't exist is 404 only for callers who can read the project. Listing (GET /api/services?projectId=) and creating services still need project-wide access. The list leaves out services you can't read: a service access override of none, or a key scoped to other services (organization owners and admins aren't held to overrides). total counts only the listed services. Environment overrides don't hide a service. Public-floor callers see a service's createdBy only when it is their own id or system ("redacted" otherwise) — in the list, by id and by slug. The same applies to environments, AI judges and cohorts (in responses to cohort changes too). A cohort's createdBy can't be changed through PATCH.

DELETE /api/services/{id} also deletes the service's flags in every environment. So it needs delete in each environment the service has flags in (environment overrides outrank the service's). It is refused with 409 APPROVAL_REQUIRED (environments) if any of them requires approval (503 APPROVAL_CHECK_UNAVAILABLE when that can't be checked), and with 409 ROLLOUT_IN_PROGRESS (rolloutPlan) or 409 BUSY while a rollout plan is live on any of its flags. The delete (and DELETE /api/cleanup when it removes services) also deletes the service's non-live rollout plans in its project (draft, completed, failed, rolled back, cancelled), each audited as rollout.deleted. A deleted draft's open rollout_start change requests (pending, or approved but not applied) are retired with it: expired, with the reason as a comment, and listed on the plan's rollout.deleted entry (retiredChangeRequests).

Update Service Settings

PATCH /api/services/{id}
{
  "settings": {
    "sdk": { "updateMode": "stream", "telemetry": true },
    "ignoredUnknownKeys": ["legacy_header"]
  }
}

Merge rules: top-level settings keys replace. ui, sdk and extensions merge one level, so send only the fields that change. Lists (tags, ignoredUnknownKeys) replace the whole list, so send the complete next list to remove entries.

settings.sdk is what GET /api/sdk-config serves to SDKs:

FieldValues
updateModestream, batch or poll
telemetrytrue or false
cacheTtlMs0–86,400,000 (0 = SDK default)
batchIntervalMs500–3,600,000

Out-of-range values return 400. Updating or deleting a service clears the server-side SDK config cache. /api/sdk-config responses still carry Cache-Control: public, max-age=60, so CDN and browser copies can serve the old values for up to 60 seconds.


Team Members

List Members

GET /api/projects/{id}/members?limit=50&offset=0

limit is 1–100 (default 50). Response: { members, total, limit, offset }. Members whose user record was deleted are listed with a placeholder user.

Add Member

POST /api/projects/{id}/members

Two bodies:

{ "userId": "user-456", "role": "member" }
{ "email": "bob@example.com", "role": "member" }
  • { userId, role } adds the person directly: 201 { membership }. Direct adds work only for someone who already shares an organization or project with you; otherwise 404, the same as for an unknown ID.
  • { email, role } always sends an emailed invitation: 202 { invited: true, invitation }, the same whatever the address (Flaggr never looks the address up). Owner can't be invited. Same rules as Create Invitation.
  • Sending both userId and email is 400.
  • 402 when the plan has no free seat: direct members, org members whose role reaches the project, and pending project and organization invitations all hold seats.
  • 403 EMAIL_NOT_VERIFIED ("Verify your email address first") for a dashboard session whose email isn't verified, with either body.

Roles: owner, admin, member, viewer. Only owners can add an owner; admins add up to admin and can't add themselves (403). Ownership changes are refused for connectors and project API tokens (403).

Add Organization Member

POST /api/organizations/{orgId}/members

Takes the same two bodies with organization roles (owner, admin, member, billing). { email, role } always sends an invitation (202 { invited: true, invitation }). { userId, role } adds directly (201 { member }: the membership, with the user as { id, email, name } only) for someone who already shares an organization or project with you (404 otherwise). An owner can be added only by userId and only by an organization owner. Members other than billing hold a seat on every project in the organization, so 402 names the project (projectId) without a free seat, measured against the organization's most generous project plan. A dashboard session needs a verified email (403 EMAIL_NOT_VERIFIED).

Update / Remove Member

PATCH  /api/projects/{id}/members/{memberId}
DELETE /api/projects/{id}/members/{memberId}

Only owners grant, change or remove the owner role, and nobody raises their own role (403). The last owner can't be demoted or removed (400). A concurrent change returns 409. DELETE on your own membership leaves the project.

PATCH (role or access overrides) needs a verified email for dashboard sessions (403 EMAIL_NOT_VERIFIED). DELETE /api/organizations/{orgId}/members/{memberId} answers 500 { success: false, error: "Couldn't stop SSO from re-adding this member — try again", removedFromProjects, failedProjects: [] } when the SSO just-in-time block can't be recorded, and 409 if the person became an owner of one of the organization's projects during the removal. In both cases the organization membership is kept, so retry.

Teams & Flag Owners

GET    /api/projects/{id}/teams
POST   /api/projects/{id}/teams
PATCH  /api/projects/{id}/teams/{teamId}
DELETE /api/projects/{id}/teams/{teamId}
GET    /api/projects/{id}/teams/flag-owners?serviceId=web&flagKey=checkout-v2
PUT    /api/projects/{id}/teams/flag-owners

Reading teams and flag owners needs read access; team changes need manage_members, and setting a flag's owner needs write and a membership. Public-floor callers get 403 from PUT /api/projects/{id}/teams/flag-owners before the body is read, so the answer never says whether a user id is a member. Team members must be project members. Public-floor callers see which team owns a flag, but not other people's user ids: ownerUserId, updatedBy and a team's createdBy show as "redacted", and team member lists keep only the caller.


Invitations

List Invitations

GET /api/projects/{id}/invitations

Accept tokens are never included.

Create Invitation

POST /api/projects/{id}/invitations
{ "email": "bob@example.com", "role": "member" }

Invitations are emailed and expire after 7 days. Owner can't be invited. Responses:

  • 201 { invitation } (the token is included only for dashboard sessions);
  • 409 for a pending invitation to the same address or an existing member;
  • 402 when the plan's member limit is reached (pending project and organization invitations and organization members count);
  • 429 after 20 invitations in an hour (attempts refused with 409 or 402 count too);
  • 403 EMAIL_NOT_VERIFIED for a dashboard session whose email isn't verified;
  • 403 for API tokens, personal access tokens and self-invites.

Revoke Invitation

DELETE /api/projects/{id}/invitations/{invitationId}

Returns { "success": true }; 404 for an unknown invitation, 409 if it was already accepted.

Accept Invitation

POST /api/invitations/accept
{ "token": "..." }

Works for project and organization invitations, from a signed-in browser session with a verified email that matches the invitation. Responses:

  • 200 { "kind": "project", "membership": { "id", "projectId", "role" }, "project": { "id", "slug", "name" } } or { "kind": "organization", "membership": { "id", "orgId", "role" }, "organization": { ... } };
  • 403 wrong address, unverified email ("Verify your email address first"), delegated credential, own invitation, owner invitation, or withdrawn because the inviter lost access;
  • 404 unknown token (including an invitation withdrawn because its addressee was removed) or deleted target;
  • 409 already accepted, or already a member (body includes the project or organization);
  • 410 expired;
  • 402 plan limit (organization invitations: any project in the organization without a free seat).

Organization SSO Domains

GET    /api/organizations/{orgId}/sso/domains
POST   /api/organizations/{orgId}/sso/domains                     { "domain": "acme.com" }
POST   /api/organizations/{orgId}/sso/domains/{domain}/verify
DELETE /api/organizations/{orgId}/sso/domains/{domain}

An SSO connection's domain counts only once its organization proves it owns it with a DNS TXT record (_flaggr-sso.<domain> = flaggr-sso-verification=<token>). GET lists each domain's status (verified, pending, unverified) and the record to publish (organization read access). The other three need an organization admin's dashboard session: POST issues the challenge (201; 400 PUBLIC_EMAIL_DOMAIN, 409 DOMAIN_VERIFIED_BY_ANOTHER_ORG, 402 plan), verify answers 200, 422 DOMAIN_NOT_VERIFIED (record missing or wrong) or 404 (no challenge yet), and DELETE releases the domain (409 DOMAIN_IN_USE while an active connection uses it). See Organization SSO.


API Tokens

Project tokens are managed on https://flaggr.dev. The list, the scoped-token create, rename, opaque rotation and GET /api/users/me/tokens return the token object below (GET /api/users/me/tokens adds projectId and leaves out the creator's name and email). The legacy permissions create and the JWT create and rotation return a shorter one (id, name, tokenType, kind, permissions, expiresAt, createdAt, plus scopes for a JWT). None includes the secret's hash.

FieldMeaning
id, projectId, nameThe token and its project. A name is 1 to 100 characters.
tokenTypeopaque (fgr_…) or jwt (legacy)
kindapi_token, sdk_key (evaluation-only) or jwt
permissionsThe legacy read, write and delete bits, and evaluationOnly: true on an SDK key. A scoped token's bits come from its project-level scopes, and are all false when it has none.
scopesThe stored scope strings, when the token has any
expiresAtWhen the token expires. For a legacy JWT row, when its current access token expires (5 minutes after the last refresh). Absent for a token that never expires.
lastUsedAt, lastUsedUserAgentWhen the token was last used, and by which client
tokenHintThe last four characters of the secret
createdBy, createdAt, updatedAtThe creator's user ID and the timestamps
createdByName, createdByEmailThe creator's name and email. The list returns them.

List Project Tokens

GET /api/projects/{id}/tokens

Needs manage_settings, which means the admin tier for API tokens and connectors. Returns { "tokens": [...] }, one token object for each token in the project.

Create a Token

POST /api/projects/{id}/tokens

Creating a token is credential issuance. It needs a signed-in dashboard session with a verified email, or an MCP connector with the admin tier (a connector whose consent narrowed the project needs admin on that project). API tokens and personal access tokens get 403. It also needs manage_settings on the project (the owner and admin roles have it), so a member or viewer gets 403. The body picks the kind of token:

BodyCreates
"tokenType": "opaque" and scopesA scoped, long-lived token. Its scopes decide its access, and expiresAt is optional. "evaluationOnly": true makes it an SDK key.
permissions (no scopes)A whole-project token from the legacy body
scopes and no tokenType (or "tokenType": "jwt")A legacy JWT pair (see Create a Legacy JWT Pair)

A scoped token:

{
  "name": "CI Read Token",
  "tokenType": "opaque",
  "scopes": ["service:service-1712345:read", "environment:production:read"],
  "expiresAt": "2026-12-31T00:00:00Z"
}

expiresAt is a future timestamp ending in Z. Leave it out for a token that never expires. Scopes are checked when the token is created: at most 50, each <level>:<identifier>:<permission>. A project scope must name this project, a service scope must name a service ID of the project (not its slug or name), and an environment scope must name one of the project's environment slugs. An SDK key ("evaluationOnly": true) may hold only read scopes. The full rules are in API Tokens.

curl -s -X POST https://flaggr.dev/api/projects/proj-1/tokens \
  -H "Authorization: Bearer $ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  --data-binary @- <<'JSON' | jq
{
  "name": "CI Read Token",
  "tokenType": "opaque",
  "scopes": ["service:service-1712345:read", "environment:production:read"],
  "expiresAt": "2026-12-31T00:00:00Z"
}
JSON
 
# Save the token value — it is only shown once
# .value => "fgr_abc123..."

$ADMIN_TOKEN stands for a signed-in session's ID token or an admin-tier connector token. A request with a Bearer header doesn't need the X-CSRF-Token header, which applies to cookie sessions.

The response is { "token": …, "value": "fgr_…" }. The value is shown once: on creation, and a new one on each rotation.

Answers that refuse the body:

  • 400 Validation Error: a body of the wrong shape (for example a missing or empty name), a name over 100 characters, a scope that doesn't match <level>:<identifier>:<permission>, more than 50 scopes, or an expiresAt that isn't a future timestamp.
  • 400 Invalid scopes, with an issues list of { scope, message }. The scopes don't fit this project. A slug or name where a service ID belongs gets a "did you mean" hint when one matches.
  • 400 for a name that is reserved (Demo Client Token), for a body with both scopes and permissions, for evaluationOnly on any other body (or inside permissions), for a tokenType other than opaque or jwt alongside scopes, and for a body that isn't a JSON object.
  • 403 EMAIL_NOT_VERIFIED for an unverified session.

A whole-project token uses the legacy body. Its read, write and delete bits give the tiers, and expiresAt is optional:

{
  "name": "CI Read Token",
  "permissions": { "read": true, "write": false, "delete": false },
  "expiresAt": "2026-12-31T00:00:00Z"
}

The response has the same shape, with value. For multi-language examples, see API Tokens.

Create a Legacy JWT Pair

POST /api/projects/{id}/tokens
{
  "name": "Service JWT",
  "scopes": ["project:proj-1:read"]
}

Returns token, an accessToken valid for 5 minutes, a refreshToken valid for 30 days, and accessTokenExpiresAt and refreshTokenExpiresAt. JWT scopes are checked for their form only, when the token is created.

Refresh a Legacy JWT Pair

POST /api/projects/{id}/tokens/refresh
Content-Type: application/json
{ "tokenId": "token-1767225600000-k3x9q", "refreshToken": "eyJhbGciOiJ..." }

There is no Authorization header: the refresh token is the credential. Returns accessToken, refreshToken, accessTokenExpiresAt and refreshTokenExpiresAt. A refresh token works once. A used, expired or wrong one gets 401 Invalid or expired refresh token.

Rename Token

PATCH /api/projects/{id}/tokens/{tokenId}
{ "name": "checkout-ci" }

Needs manage_settings. Returns { "token": … }. The secret, access and expiry stay the same, and no new secret is issued. A rename to the name the token already has changes nothing and writes no audit entry. Each rename is audited as token.update.

The name Demo Client Token is reserved for the demo SDK key. Renaming a token to it returns 400, and a token that already has it can't be renamed (409 RESERVED_NAME).

Rotate Token

POST /api/projects/{id}/tokens/{tokenId}/rotate

Rotating replaces the token: a new secret, returned once, with the same name and creator, and the old token is revoked at once. The replacement acts as the creator, so the rotator's role must be at least the creator's. Rotation is credential issuance, as creating a token is: API tokens and personal access tokens get 403, and an unverified session gets 403 EMAIL_NOT_VERIFIED. It also needs manage_settings (the owner and admin roles), so a member or viewer gets 403.

The body is optional. For an opaque token it can change the access and the expiry:

{ "scopes": ["service:service-1712345:read"], "expiresAt": null }
  • scopes: the new access, checked as on create. Left out, the stored scopes carry over unchanged. A legacy token keeps its permission bits.
  • expiresAt: a future timestamp ending in Z, or null for no expiry. Left out, the expiry carries over.
  • Only the creator can send either one. Anyone else gets 403 NOT_TOKEN_CREATOR.

An opaque token returns { "token": …, "value": "fgr_…", "rotatedFrom": "…" }. A legacy JWT keeps its scopes and takes no change. It gets a new pair (a 5-minute access token and a 30-day refresh token), and returns token, accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt and rotatedFrom. A JWT body that sets scopes or expiresAt gets 400 JWT_BODY_NOT_SUPPORTED.

StatuscodeWhen
400—error: "Invalid scopes" with issues: the new scopes don't fit the project. A body the schema refuses (invalid JSON, a malformed scope, more than 50 scopes, a past expiresAt) gets 400 with its first problem as error. An evaluationOnly key gets 400 "Rotation keeps the token's kind — create an SDK key instead".
400JWT_BODY_NOT_SUPPORTEDA JWT whose body sets scopes or expiresAt
403NOT_TOKEN_CREATORA body that sets scopes or expiresAt, sent by anyone but the creator
403noneThe rotator lacks manage_settings (a member or viewer), has a role below the creator's, or is an API token or personal access token
404noneNo token with that ID in the project
409TOKEN_EXPIREDThe token has expired and the body has no expiresAt, the creator's included. Anyone else who sends one gets 403 NOT_TOKEN_CREATOR instead.
409INVALID_SCOPESThe stored scopes don't parse, and the body has no scopes
409NO_ACCESSA token with neither stored scopes nor a permissions object, and the body has no scopes

Rotate secret and Change access in the console both call this endpoint.

Revoke Token

DELETE /api/projects/{id}/tokens/{tokenId}

A revoked opaque token (fgr_…) is refused at once by the flaggr.dev server that handled the revocation and by the data plane (api.flaggr.dev), which caches no credentials. For up to 5 seconds, though, the edge cache in front of api.flaggr.dev can still answer a request identical to one it has just answered (same URL, body and Authorization header). Every other flaggr.dev server stops accepting it within about 10 seconds (on deployments with a shared Redis or KV cache, such as flaggr.dev; without a shared cache, within about 30 seconds). JWT access tokens stay valid until they expire (at most 5 minutes). Open streams close within about a minute, on api.flaggr.dev too (see Real-Time Updates).

Returns { "success": true }, or 404 for a token that isn't in the project.

List My Tokens

GET /api/users/me/tokens

Needs the admin tier (a session always has it), so a credential below admin gets 403 for the whole list. Returns { "tokens": [...] }: the tokens the signed-in user created. A session or personal access token sees every project where the user is a direct member. A connector or project API token sees only its bound projects that the user still reaches, and only where it could list tokens: a connector narrowed below admin on a project gets none of that project's tokens. Each item is the token object plus projectId, without createdByName or createdByEmail. Hashes are never returned.

Personal Access Tokens

Signed-in dashboard session only — API tokens, personal access tokens and connectors get 403.

GET    /api/users/me/personal-tokens               # → { tokens, limit, available }
POST   /api/users/me/personal-tokens               # { name, tier, expiresInDays, allowOwnerActions } → 201 { token, value }
DELETE /api/users/me/personal-tokens/{id}          # revoke
POST   /api/users/me/personal-tokens/{id}/rotate   # { expiresInDays? } → { token, value, rotatedFrom }

See Personal Access Tokens.


Connector Access (MCP OAuth)

An MCP connector (Claude, Codex and other assistants) gets its mcp_… token through the consent screen at /oauth/authorize. The screen approves the connection with one tier, and then lowers the access to any selected project. Approving and managing connections is for a signed-in dashboard session only: connectors and tokens get 403 on these routes.

Approve a Connection

POST /api/oauth/authorize
{
  "client_id": "mcp_…",
  "redirect_uri": "https://assistant.example/callback",
  "state": "…",
  "scope": "read write",
  "project_ids": ["proj-1", "proj-2"],
  "project_tiers": { "proj-2": "read" },
  "code_challenge": "…",
  "code_challenge_method": "S256"
}

Returns { "redirect": "…?code=…&state=…" }. The client then exchanges the code at POST /api/oauth/token (form-encoded, with the PKCE code_verifier).

  • scope: the connection's tier, read (the default), write or admin. Each one includes the tiers below it.
  • project_ids: one to 100 projects. Only projects you're a direct member of count (projects you reach through an organization or the shared demo are dropped). If none is left, the answer is 403 No selected projects belong to your account.
  • project_tiers: optional. Maps selected projects to read, write or admin to give them less access than the connection. A tier above scope gets 400, and a project whose tier equals scope isn't narrowed. A narrowed project's ID must be letters, digits, _, . or -, or the answer is 400. Entries for projects that aren't kept are ignored.
  • Re-approving the same client (the same client_id) replaces its previous grant once the new code is exchanged for a token. The exchange revokes the client's other live tokens for your account, so an earlier, broader grant stops working. A token refresh doesn't do this. The exchange at POST /api/oauth/token runs in one transaction: if the new tokens can't be issued, it answers 500 server_error (Could not issue tokens; restart authorization) and rolls back, so the code stays unspent until it expires (5 minutes) and the earlier grant stays as it was. The client can retry the exchange or restart authorization. A refused code (wrong verifier, client or redirect URI) stays spent.

A delegated credential gets 403, and an unverified session gets 403 EMAIL_NOT_VERIFIED.

Connections

GET    /api/oauth/connections
DELETE /api/oauth/connections?clientId={clientId}

GET (session only) returns { "connections": [...] }, one entry per connected client, with clientId, clientName, logoUri, tier, projectIds, projectTiers, connectedAt, lastUsedAt and expiresAt. projectTiers maps each selected project to its effective tier: a narrowed project sits below tier, and every other project has tier.

DELETE (session only, CSRF protected) disconnects the client. It revokes the client's live tokens and voids its authorization codes that haven't been exchanged, so a code issued before the disconnect can't mint a grant. It returns { "revoked": n }, or 404 Connection not found when no live grant exists.

Narrowed Access

A narrowed project's tier applies to every request on that project. An organization-level change needs admin on every selected project that the organization owns. Minting tokens, flag triggers, share links and project invitations needs admin on that project.

A narrowed connector that the tier refuses gets 403 with one of these texts. The first two are for a project, the third for an organization:

  • Forbidden: connector token is read-only in this project — reconnect Flaggr and give this project more access
  • Forbidden: connector token lacks the admin scope in this project — reconnect Flaggr and allow administration for this project
  • Forbidden: connector token lacks the admin scope for every project of this organization — reconnect Flaggr and allow administration for them

GET /api/users/me returns a connector's scope and projectTiers (see Current User).


Audit Logs

Query Audit Logs

GET /api/audit?projectId=proj-1&action=flag.update&limit=50

Query parameters:

ParameterTypeDescription
projectIdstringRequired.
actionstringFilter by action type
resourceTypestringflag, service, project, member, invitation, token, experiment, organization, org_member, org_invitation, sso_connection, alert_firing, team
resourceIdstringSpecific resource ID
userIdstringFilter by actor
startDatestringISO date lower bound
endDatestringISO date upper bound
limitnumberDefault 30, max 100
cursornumbernextCursor of the previous page (the last entry's timestampMs)

Actions:

  • Flags: flag.create, flag.update, flag.delete, flag.toggle, flag.rollback, flag.auto_rollback, flag.rum_optimize, flag.canary_start, flag.canary_advance, flag.canary_abort, flag.canary_complete, flag.owner_change
  • Services and projects: service.create, service.update, service.delete, project.create, project.update, project.delete
  • Members and invitations: member.add, member.remove, member.role_change, member.access_change, invitation.create, invitation.accept, invitation.cancel
  • Credentials: token.create, token.update, token.revoke, token.rotate, trigger.create, trigger.revoke, share_link.create, share_link.revoke, personal_token.create, personal_token.revoke, personal_token.rotate
  • Rollouts: rollout.started, rollout.stage_advanced, rollout.stage_approved, rollout.guardrail_breached, rollout.paused, rollout.resumed, rollout.rolled_back, rollout.completed, rollout.cancelled, rollout.advance_blocked, rollout.risk_assessed, rollout.autopilot_decision, rollout.risk_detected, rollout.autopause_triggered, rollout.start_blocked, rollout.start_override, rollout.approval_requested, rollout.approval_applied, rollout.approval_blocked
  • Experiments, impact and AI: experiment.summary_published, experiment.adaptive_allocation_recommended, experiment.adaptive_allocation_applied, impact.forecast_generated, impact.forecast_feedback_recorded, ai.judge_evaluated
  • Organizations: org.create, org.update, org.delete, org.member_add, org.member_remove, org.member_role_change, org.invitation_create, org.invitation_accept, org.invitation_cancel, org.sso_created, org.sso_updated, org.sso_deleted, org.sso_tested, org.sso_domain_verified, org.sso_domain_released
  • Accounts: user.identity_relinked (a verified sign-in took over an account whose previous sign-in identity didn't verify its address; the account's personal access tokens and connector grants were revoked and its pending invitations withdrawn — each withdrawal is also logged in its organization or project as org.invitation_cancel / invitation.cancel with metadata.reason: "inviter_identity_relinked"; the entry lists the withdrawn invitations and the members to review; filed under user:<id>)
  • Incidents and teams: alert.state_change, alert.assign, alert.note_add, team.create, team.update, team.delete

GET /api/projects/{id}/audit-log takes the same filters and validates them: every audit action above is a valid action and every resource type is a valid resourceType. Filters such as flag.rollback, flag.auto_rollback, flag.canary_*, member.access_change, personal_token.*, alert.*, team.*, org.sso_* and flag.owner_change, which used to return 400 there, now work.

Response:

{
  "logs": [
    {
      "id": "log-1",
      "projectId": "proj-1",
      "userId": "user-123",
      "action": "flag.update",
      "resourceType": "flag",
      "resourceId": "checkout-v2",
      "resourceName": "Checkout V2",
      "before": { "enabled": false },
      "after": { "enabled": true },
      "changes": [
        { "field": "enabled", "oldValue": false, "newValue": true }
      ],
      "metadata": {},
      "timestamp": "2025-07-20T10:30:00Z",
      "ipAddress": "203.0.113.1",
      "userAgent": "Mozilla/5.0..."
    }
  ],
  "nextCursor": 1753007400000,
  "hasMore": true
}

Public-floor callers (shared demo or showcase, with no membership) receive redacted entries: flag, service, rollout, experiment, impact-forecast and AI actions only; other actors shown as userId: "redacted" and userName: "Another member"; no before, after, changes, summary, metadata, ipAddress or userAgent. A userId filter for anyone else returns an empty page. Their queries cover only those actions, so nextCursor and hasMore never reflect hidden entries, and an action filter outside them returns one empty, final page ({ "logs": [], "nextCursor": null, "hasMore": false }). The same applies to GET /api/projects/{id}/audit-log, GET /api/projects/{id}/audit-logs and GET /api/audit/resource.


Webhooks

Platform admins only, from a signed-in dashboard session — API tokens, personal access tokens and connectors get 403. Registered webhooks receive events from every project.

List Webhooks

GET /api/webhooks

Register Webhook

POST /api/webhooks
{
  "url": "https://example.com/webhook",
  "secret": "whsec_your_secret",
  "events": ["flag.created", "flag.updated", "flag.deleted", "flag.toggled"],
  "active": true
}

Update / Delete Webhook

PATCH  /api/webhooks/{id}
DELETE /api/webhooks/{id}

See Webhooks Guide for payload format and signature verification.


Health Checks

Application Health

GET /api/health
{
  "status": "healthy",
  "timestamp": "2025-07-20T10:00:00Z",
  "version": {
    "app": "0.5.0",
    "commit": "abc1234",
    "environment": "production"
  },
  "cache": {
    "backend": "redis",
    "shared": true,
    "readCache": { "backend": "redis", "working": true, "testTime": 2 },
    "writeCache": { "backend": "redis", "working": true, "testTime": 3 }
  },
  "storage": { "backend": "postgres", "schema": "flaggr" }
}

cache.backend is the write plane's backend, which holds credentials, and cache.shared says whether every instance shares it: Redis (REDIS_URL or REDIS_WRITE_URL), or a KV store through KV_REST_API_URL with KV_REST_API_TOKEN (the URL alone doesn't count). readCache.backend and writeCache.backend give each plane's own, so with only REDIS_READ_URL set, cache.backend is in-memory, readCache.backend is redis and cache.shared is false. In production without a shared cache, the response also carries cache.degraded: true and cache.warning (why: revocations reach other instances only as their entries expire, within about 30 s); status doesn't change. storage.backend is postgres when DATABASE_URL is set and not blank, otherwise file.

Readiness

GET /api/readyz
{
  "status": "ready",
  "degraded": false,
  "checks": {
    "storage": { "ok": true, "backend": "postgres" },
    "cache": { "ok": true },
    "sharedCache": { "ok": true, "backend": "redis" }
  },
  "responseTime": "4ms"
}

200 when storage and the read cache work, 503 (not_ready) otherwise. checks.storage checks the storage the deployment uses (backend): with DATABASE_URL, Postgres must answer a SELECT 1 through the app's connection pool within 3 seconds (otherwise error is Postgres did not answer within 3000ms or Postgres query failed (<code>)); without it, the data/ directory must be usable, or the working directory writable. Each instance runs one Postgres check at a time and reuses its answer for 5 seconds, so checks.storage can be up to 5 seconds old.

Use /api/readyz for monitoring and alerting, and point Kubernetes readiness and liveness probes at GET /api/healthz. Every instance shares the database, so with /api/readyz as the readiness probe, a Postgres outage would take every instance out of service at once, including the flag reads the cache could still serve. A monitor that polls /api/readyz keeps a Neon compute from suspending (it costs at most one SELECT 1 per instance every 5 seconds). checks.sharedCache is { ok: true, backend: "redis" | "vercel-kv" | "memory", degraded?, reason? }: in production without Redis or KV it reports degraded: true with the reason, and the top-level degraded is true, but readiness stays 200.

Liveness

GET /api/healthz

Answers 200 with { "status": "ok" } while the process serves HTTP. It doesn't check dependencies.

Admin Health

GET /api/health/admin

Detailed health including storage, cache, and auth subsystem status.

Evaluation Health

GET /api/health/evaluation

Validates the flag evaluation pipeline is functional.


Alerts

Alert rules, incidents (firings) and channels belong to a project; see Alerting.

Project Alert Rules & Incidents

GET    /api/projects/{id}/alerts
POST   /api/projects/{id}/alerts
PATCH  /api/projects/{id}/alerts/{ruleId}
DELETE /api/projects/{id}/alerts/{ruleId}
GET    /api/projects/{id}/alert-firings?limit=50&state=open&severity=critical&ruleId=rule-1
GET    /api/projects/{id}/alert-firings/{firingId}
PATCH  /api/projects/{id}/alert-firings/{firingId}
GET    /api/projects/{id}/alert-firings/{firingId}/notes
POST   /api/projects/{id}/alert-firings/{firingId}/notes

Rule bodies take name, conditionType (error_rate | p95_latency | evaluation_count | toggle_drift | auto_rollback), threshold, windowMinutes, severity (critical | warning | info), channels ([{ "channelId", "channelName" }]), cooldownMinutes (default 15) and enabled. Legacy grpc_errors and cache_hit_rate return 400 for new rules or a switch to them; existing rules keep them but aren't evaluated. Responses include evaluation: { status, reason?, lastOutcome?, lastEvaluatedAt?, lastValue? }, the rule's latest scheduled check. Disabling or deleting a rule resolves its unresolved incidents; DELETE returns { success, resolvedIncidents }. A project can have at most 100 enabled rules: POST, or a PATCH that enables a rule, past that returns 400 (Validation Error, with limit). Callers on the shared demo's public access get 403 for POST, PATCH and DELETE and see createdBy as redacted unless it is their own.

alert-firings lists incidents newest first (limit 1–200, default 50); state (open | investigating | resolved), severity and ruleId filter before the limit, and invalid values return 400 (Invalid request). PATCH …/alert-firings/{firingId} takes { "state": "open" | "investigating" | "resolved", "assigneeId": "…" }. A state change is a compare-and-set: if the incident was resolved after it was read, PATCH returns 409 (Incident was resolved meanwhile, with the stored firing and notes) and records nothing. On the shared demo's public access, assigneeId and POST …/notes return 403; other people appear as redacted / Another member in incidents and timelines, and their note text is hidden.

GET …/alert-firings/{firingId} returns the incident with its timeline, metric series and impact. For error_rate rules, impact.browser (sessions, errorEvents, topBrowser, topPage) counts the browser analytics errors of the project's Sites in the firing window, leaving out events the ingest marked untrusted (sent from another origin than the Site's domain). impact.browserExcluded ({ untrustedEvents, untrustedSessions }) says how many it left out, also when nothing is left and impact.browser is absent. Members can count them with ?includeUntrusted=1, and impact.browserExcluded is then null; callers on a public project's floor can't. Rules other than error_rate have neither field.

Alert Evaluation (cron)

GET  /api/cron/alerts
POST /api/cron/alerts
Authorization: Bearer $CRON_SECRET

Evaluates every enabled alert rule once. Returns 503 when CRON_SECRET isn't configured and 401 for a wrong bearer. ?dryRun=0 (or false) runs live (records incidents, notifies, writes state); without dryRun, or with ?dryRun=1, it only evaluates. ?projectId= limits the run to one project. Other values, repeated parameters and misspelt names (dry_run, dryrun, projectID) return 400 (invalid_parameters). The response holds rule and project IDs, outcome counts and error codes, never rule names; a run in which a project or the orphan sweep failed, or every checked rule errored, returns 500 with error projects_failed, sweep_failed or rules_failed.

Retired endpoints

These return 410 Gone with a body of error, code: "ENDPOINT_GONE", replacement and docs:

RetiredUse instead
GET /api/alertsGET /api/projects/{projectId}/alert-firings, or scrape /api/metrics
/api/rollouts, /api/rollouts/{id}/api/projects/{projectId}/rollouts
/api/rollouts/{id}/assessment, /assessment/history, /assessment/runGET /api/projects/{projectId}/rollouts/{planId}/analysis

Streaming

Connect Stream (SSE)

GET /api/connect/stream?serviceId=web-app&environment=production&clientId=client-1

Returns a text/event-stream with real-time flag change events. Every connection needs a credential; there is no keyless mode. See Real-Time Updates for the event format.

Send API tokens and SDK keys in the Authorization header. ?token= or ?apiToken= (for browsers' EventSource, which can't send headers) accepts a signed-in dashboard session's ID token or a read-only SDK key: an evaluation-only or read-only fgr_ key, or a JWT whose scopes are all read. The key is still bound to its project and checked against the serviceId, environment and flags the stream names; a flag-scoped key must cover every flagKey the request names. Personal access tokens, connector tokens, and API tokens or JWTs that can write, delete or administer get 401 in the URL. A URL token is ignored when the request has an Authorization header.

The other streams — GET /api/flags/{key}/metrics/stream and GET /api/ai/safety-alerts/stream — accept only a signed-in session's ID token in ?token=; any other credential there gets 401.

Streams (/api/flags/stream, /api/connect/stream, /api/flags/{key}/metrics/stream, /api/ai/safety-alerts/stream, gRPC-Web StreamFlags) re-check access every 60 s. A stream that is still allowed picks up changed overrides. When access is gone (key revoked or expired, membership removed, override set to none, service deleted), the stream sends data: {"type":"access_revoked","reason":"access_revoked",…} and closes; gRPC-Web sends an end-stream message with error.code permission_denied. If the re-check itself fails twice in a row, the stream closes the same way with reason reauthorization_failed (gRPC-Web: unavailable). A re-check whose credential lookup fails (Flaggr can't read the user, the key or token, or the SSO connection from storage: an outage, not a refusal) counts as such a failure, so one alone doesn't close the stream. Reconnecting authorizes from scratch. A stream authenticated by a session ID token in ?token= ends once that token expires (at most an hour); reconnect with a fresh token. The data plane's streams on api.flaggr.dev re-check access too; see Real-Time Updates.

Legacy Stream

GET /api/flags/stream?serviceId=web-app&environment=production

Backward-compatible SSE stream. Its messages are unnamed JSON: { "type": "connected", … } first, then { "type": "flag-update", "flagKey", "eventType", "flag", "configVersion", "timestamp" } per change (eventType is a name such as CREATED, UPDATED, TOGGLED or DELETED; flag is the flag's configuration, absent for deletions), with a :ping comment every 30 seconds. On api.flaggr.dev the same path is the data plane's stream, which sends named configuration_sync, configuration_delta and heartbeat events instead (see Protocols). It also re-checks access, first 30–60 s after connect and then every 60 s, and closes with a named access_revoked event (reason access_revoked or reauthorization_failed) where flaggr.dev sends an unnamed data: message. A key with an expiry ends the data plane's stream at that expiry, with no event. Send API tokens and SDK keys in the Authorization header. ?token= (for browsers' EventSource, which can't send headers) accepts a signed-in dashboard session's ID token or a read-only SDK key: an evaluation-only or read-only fgr_ key, or a JWT whose scopes are all read. The key is still bound to its project and checked against the serviceId and environment the stream names. Personal access tokens, connector tokens, and API tokens or JWTs that can write, delete or administer get 401 in the URL. Optional environment (any environment name, custom environments included) limits updates to that environment's flags. Every update reaches only callers who may read that flag in its environment. A member whose access overrides set the service or an environment to none gets no updates for it (from ?token= as from the header; 403 when the stream names a denied service or environment). Environment- and service-scoped keys get only what they cover. Update payloads never include createdBy or updatedBy. Like the other streams it re-checks access every 60 s and closes with an access_revoked message once access is gone (see Connect Stream (SSE)).

Multi-Language Examples

# SSE streams stay open — press Ctrl-C to stop
curl -N "https://flaggr.dev/api/flags/stream?serviceId=web-app&environment=production" \
  -H "Authorization: Bearer fgr_abc123xxxxxxxxxxxx" \
  -H "Accept: text/event-stream"

Connect Protocol

Evaluate (Connect)

POST /api/connect/evaluate

Uses structured Connect protocol format with protobuf-style values. These /api/connect/* routes are served on flaggr.dev; the data plane at api.flaggr.dev serves Connect at the service paths (/flaggr.v1.EvaluationService/…) instead. See Protocols.

Bulk Evaluate (Connect)

POST /api/connect/bulk-evaluate

Both Connect routes answer 400 for invalid JSON; for a serviceId, flagKey, flagKeys[] entry or environment that isn't a 1–256 character string without control characters; and for more than 5000 flagKeys. environment also accepts the proto enum by name (ENVIRONMENT_STAGING) or number (0 and 3 production, 1 development, 2 staging); when absent it is production, as before.

OFREP v1 — Single

POST /api/ofrep/v1/evaluate/flags/{key}
X-Service-Id: web-app

OFREP v1 — Bulk

POST /api/ofrep/v1/evaluate/flags
X-Service-Id: web-app

OFREP Metadata

GET /api/ofrep/v1/metadata

Canary Rollouts (persisted rollout plans)

/api/flags/[key]/canary is a flag-centric shortcut over rollout plans. Starting a canary creates and starts a plan with the canary strategy, gated on the flag's pre-canary evaluation error rate and p99 latency. The plan is persisted, advanced by the rollout engine every 5 minutes and shown under Releases. All four routes take serviceId (body or query) and default environment to production. POST routes need write access to that service and environment; GET needs read. Cookie sessions send the CSRF token; bearer tokens are exempt.

Start a canary

POST /api/flags/[key]/canary
{
  "serviceId": "web-app",
  "environment": "production",
  "targetValue": true,
  "initialRolloutPercent": 5,
  "targetRolloutPercent": 100,
  "rampStepPercent": 20,
  "soakPeriodMinutes": 30,
  "errorRateGateDelta": 0.01,
  "latencyGateDeltaMs": 50,
  "minTrafficRatio": 0.7,
  "minSampleSize": 200,
  "autoRollbackOnBreach": true,
  "autoAdvance": true,
  "name": "Checkout v2 canary"
}

Pass either the ramp fields or stages: [{ "name", "rolloutPercentage", "soakMinutes" }], not both. guardrails: { maxErrorRateDelta, maxLatencyDeltaMs, minTrafficRatio } is accepted in place of the gate fields. Gates are the flag's error rate and p99 over the hour before the canary plus the deltas, never below 2% / 100 ms. Optional: notifyChannels (alert channel ids of the project or its org; default: the project's enabled channels) and override: { acknowledgePolicy, reason } for a governance block that allows an override.

Response 201:

{
  "id": "6f1c…", "planId": "6f1c…", "status": "active", "planStatus": "active", "strategy": "canary",
  "currentStageIndex": 0, "ruleId": "rollout-6f1c…", "targetValue": true,
  "stages": [{ "id": "canary-1", "name": "Canary", "rolloutPercentage": 5, "soakMinutes": 30, "status": "active", "autoAdvance": true, "startedAt": "…" }],
  "guardrails": { "maxErrorRateDelta": 0.01, "maxLatencyDeltaMs": 50, "minTrafficRatio": 0.7 },
  "gates": { "errorRateThreshold": 0.02, "latencyThresholdMs": 100, "minTrafficRatio": 0.7, "minSampleSize": 200, "errorRateFloored": true, "latencyFloored": true },
  "autoRollbackOnBreach": true, "safetyChecks": [], "baselineVersion": 7, "baselineRolloutPercentage": 0,
  "baseline": { "servingDigest": "…", "metrics": { "evaluations": 1000, "errorRate": 0.003, "p99LatencyMs": 40, "source": "postgres" } },
  "releasePath": "/console/acme/releases/6f1c…"
}

Get canary status

GET /api/flags/[key]/canary?serviceId=web-app&environment=production

Returns { pipeline, health, plan, analysis } for the flag's live plan (any strategy), else its newest canary. health includes isHealthy, held, canAdvance, soakRemainingMinutes, reasons, per-check checks, and metrics (error rate and p99, with their change from the baseline). Reading it also lets the engine progress due stages. RUM trends are omitted; use /api/projects/{id}/rollouts/{planId}/analysis for those.

Advance

POST /api/flags/[key]/canary/advance
{ "serviceId": "web-app", "force": false, "pipelineId": "6f1c…" }

Without force, the engine checks the stage first: a breached rollback guardrail aborts it (actionTaken: "aborted"), and the stage must have soaked with healthy guardrails and enough evaluations. force: true skips the check, the soak and the hold. actionTaken is advanced, completed, aborted or blocked; blocked returns 422 with the reason in message. Only the engine's refusals (soaking, breached, held, gated) are blocked. Another change holding the plan's lock is 409 BUSY; a rule write or engine run that failed is 503 (RULE_WRITE_FAILED, UNAVAILABLE) and nothing advanced. Approval-gated stages are never released here (use /api/projects/{id}/rollouts/{planId}/advance). A live plan that isn't a canary is advanced only when its id is passed as pipelineId.

Abort

POST /api/flags/[key]/canary/abort
{ "serviceId": "web-app", "reason": "Elevated P99 latency during the 25% stage" }

Cancels the live plan and removes its rule; edits made to the flag during the canary are kept. For a failed or rolled-back canary, it removes the rule the plan left serving. Returns { pipeline, flag, reason, baselineRestored, revertedToVersion, notifiedChannels, pendingChannels }. baselineRestored is true when the flag's serving config matches the pre-canary snapshot; revertedToVersion is then that snapshot's version. The plan's alert channels get a warning with the reason (mentions stripped; reasons are capped at 500 characters). The rule is removed, and the flag re-checked, before anything is reported: when the rule can't be removed the answer is 503 RULE_WRITE_FAILED with ruleId, no alert is sent and the plan is not reported as aborted; retry.

pipelineId, when given, must be a plan of the URL's flag, service and environment; otherwise the route answers 404.

Errors

StatuscodeWhen
400VALIDATION_ERRORInvalid body: stages with ramp fields, stages that don't increase, more than 20 stages, an environment other than development/staging/production, a targetValue of the wrong type, percentages that aren't whole numbers from 1 to 100, unknown notifyChannels
400TARGET_VALUE_REQUIREDA string, number or object flag without targetValue
404FLAG_NOT_FOUND, PIPELINE_NOT_FOUND, SERVICE_NOT_FOUNDNo such flag in the service and environment, no such pipeline, or no such service
409FLAG_DISABLEDThe flag is disabled; enable it without changing its default first
409NO_CHANGEThe flag already serves targetValue by default, or through a rule ahead that serves everyone (ruleId)
409ROLLOUT_IN_PROGRESSAnother live plan on the flag and environment (planId, planName, planStatus)
409EXPERIMENT_RUNNINGAn experiment runs or is paused on the flag (experiment: { id, name, status }); the canary didn't start and no draft is left behind. End the experiment first
409ROLLOUT_RULE_PRESENTRules left by earlier plans (ruleIds; rules[].remove gives the remove_targeting_rule call)
409ROLLOUT_RULE_SHADOWEDA rule ahead of the canary's serves everyone (no condition groups, no conditions or only the match-all condition, no schedule, and 100% or no percentage), so the canary would reach nobody (ruleIds; rules[].remove gives the remove_targeting_rule call); no draft is left behind
409APPROVAL_REQUIREDProtected environment, or a risky production start the project's governance requires approval for; start a rollout plan instead
409GOVERNANCE_BLOCKEDRollout governance blocks the start (requiresOverride says whether override.acknowledgePolicy is allowed)
409NOT_LIVEAbort of a completed canary (the message names its rule and the baseline version to roll back to), or of one with nothing serving
409NOT_CANARY_PLANAdvance of a live plan that isn't a canary without pipelineId
409BUSYAnother change to the plan holds its lock; retry
503RULE_WRITE_FAILEDThe canary's rule couldn't be written or removed; nothing was started, advanced or aborted (ruleId, pipelineId)
503UNAVAILABLEThe rollout engine or its locks are unavailable; nothing changed

Other errors are 500 without detail.

The rollout plan routes (/api/projects/{id}/rollouts/…, see Rollouts) answer with the same codes, plus:

  • creating a plan: 404 FLAG_NOT_FOUND unless the flag exists in that service and environment;
  • editing (PATCH) or deleting a draft whose start is awaiting approval: 409 PLAN_AWAITING_APPROVAL with changeRequestId and changeRequestStatus — withdraw that change request first;
  • deleting a failed, rolled-back or cancelled plan whose rule still serves: 409 ROLLOUT_RULE_PRESENT with ruleId;
  • starting: 400 ROLLOUT_IN_PROGRESS while another plan is live on the flag and environment, 503 APPROVAL_CHECK_UNAVAILABLE when the approval check can't run (nothing starts), 409 START_APPROVED when the draft's start was already approved (apply or withdraw that change request);
  • starting (POST /api/projects/{id}/rollouts/{planId}/start): 409 EXPERIMENT_RUNNING ({ error, code, experiment }) while an experiment of the project runs or is paused on the plan's flag (same service and key). This applies in every environment, because experiments have no environment. Starts that would need approval are refused too, and no change request is opened. End the experiment first. The canary start (POST /api/flags/{key}/canary) answers the same code and leaves no draft behind;
  • starting (POST /api/projects/{id}/rollouts/{planId}/start): 409 ROLLOUT_RULE_SHADOWED ({ error, code, rules }, each rule with its remove_targeting_rule call in remove) while a rule ahead of the plan's serves everyone, including a rule an earlier plan left at 100%: remove it, or give it conditions, a schedule or a percentage below 100. The check comes before any approval is requested, and applying an approved start is refused the same way (the request stays approved);
  • creating or editing a plan: stage, strategy and rollback percentages are whole numbers from 0 to 100 (400 otherwise);
  • a plan write that raced another change: 409 PLAN_CHANGED; retry.

Change Requests

Changes to environments that require approval, and rollout starts the project's governance wants approved, become change requests (flag_toggle, flag_update, promotion, rollout_start).

GET    /api/projects/{id}/change-requests?status=pending&environment=production
POST   /api/projects/{id}/change-requests
GET    /api/projects/{id}/change-requests/{requestId}
PATCH  /api/projects/{id}/change-requests/{requestId}
DELETE /api/projects/{id}/change-requests/{requestId}
POST   /api/projects/{id}/change-requests/{requestId}/apply
  • List (GET) needs read access and returns only requests whose service and environment you may read. On the shared demo and showcase, callers without a membership see other people's identities, comments and change snapshots redacted.
  • Create (POST) needs write on the project and an access override other than none on the target service and environment. The service and flag must belong to the project, payload.environment must match environment, and flag_update changes must be valid flag-update fields: a defaultValue of another type than the flag's gets 400 (Invalid flag update: …), and changes that would leave a flag the evaluation API couldn't load get 422 FLAG_NOT_SERVABLE (see Refused Flag Writes). A rollout_start is refused with 400 USE_ROLLOUT_START: start the plan instead (POST /api/projects/{id}/rollouts/{planId}/start), which opens the request. Shared-demo and showcase floor callers get 403.
  • Get (GET /{requestId}) is scoped and redacted like the list.
  • Review (PATCH /{requestId}, approve or reject) needs manage_settings on the request's service and environment (access overrides apply). Approving a rollout_start whose plan changed since it was requested returns 409 PLAN_CHANGED_SINCE_APPROVAL and retires the request.
  • Withdraw (DELETE /{requestId}): the requester, or an admin of the request's service and environment, withdraws a pending or approved-but-unapplied request (409 otherwise).
  • Apply (POST /{requestId}/apply) needs manage_settings on the request's scope and re-checks the target against the project, a flag_update's changes included (400 for a default of another type than the flag's, 422 FLAG_NOT_SERVABLE; the request stays approved). A promotion that can't copy some flags is partly applied: 409 with the first refusal's code (FLAG_TYPE_MISMATCH, FLAG_NOT_SERVABLE, FLAG_KEY_RESERVED, ROLLOUT_IN_PROGRESS or BUSY), promoted and refused, and the request stays approved; applying it again copies the same fields again. A rollout_start starts only the plan content that was approved, else 409 PLAN_CHANGED_SINCE_APPROVAL (the request is retired; request approval again with start). Another live plan on the flag is 409 ROLLOUT_IN_PROGRESS, a busy lock 409 BUSY, and a rule write that failed 503 RULE_WRITE_FAILED. An approved rollout_start whose plan no longer exists (deleted, for instance with its service) answers 410 PLAN_NOT_FOUND (with rolloutPlanId): nothing starts, and the request is retired (expired, with the reason as a comment). One whose plan's flag no longer exists in the plan's environment (deleting a flag leaves its rollout plans) answers 410 FLAG_NOT_FOUND (with rolloutPlanId, flagKey and environment) and is retired the same way; after creating the flag again, start the plan again to request a new approval. Other rule-write failures stay 503 RULE_WRITE_FAILED, and the request stays approved so the apply can be retried. 409 CHANGE_REQUEST_EXPIRED when the request is past its expiresAt (requests expire 7 days after they are opened): the request is marked expired and nothing is applied; request the change again. An approved rollout_start answers 409 EXPERIMENT_RUNNING (with experiment: { id, name, status }) while an experiment runs or is paused on the plan's flag; the request stays approved.

Targeting Rule Explanation & Blast-Radius Simulator

Explain Flag Evaluation

POST /api/flags/[key]/explain

Step-by-step diagnostic evaluation debugger explaining clause-by-clause why a user context resolved to a specific variant. It only reads, so it needs read access: read-tier connectors, API tokens and personal access tokens can call it, as they can /simulate, /advice and POST /code-refs.

{
  "serviceId": "web-app",
  "environment": "production",
  "context": {
    "targetingKey": "user-42",
    "tier": "enterprise",
    "country": "US"
  }
}

Simulate Blast-Radius

POST /api/flags/[key]/simulate

Counterfactual blast-radius simulation comparing current baseline flag vs proposed candidate flag across synthetic user cohorts.

{
  "serviceId": "web-app",
  "environment": "production",
  "cohortSize": 200,
  "candidateFlag": {
    "targeting": [
      {
        "id": "new-rule",
        "conditions": [{ "property": "tier", "operator": "equals", "value": "enterprise" }],
        "rolloutPercentage": 100,
        "value": true
      }
    ]
  }
}

Adaptive Multi-Armed Bandits

Bayesian Thompson Sampling and Epsilon-Greedy dynamic traffic weight reallocation with automated statistical stopping rules.

GET /api/experiments/bandit without projectId lists only experiments you can read. Creating an experiment needs write access to the flag's service, and serviceId must belong to projectId (400 otherwise). reallocate needs write; bandit-status needs read. reward is SDK-facing: authenticate with a project API token or SDK key for the experiment's project. Experiments are served only for flags of their own project.

A bandit experiment lives only in the memory of the server instance that created it; nothing is stored. A request that reaches another instance, or comes after a restart, gets 404 Bandit experiment "…" not found, and the recorded rewards are lost.

List Bandit Experiments

GET /api/experiments/bandit?projectId=proj-1&serviceId=web-app

Create Bandit Experiment

POST /api/experiments/bandit
{
  "name": "Checkout CTA Optimization",
  "projectId": "proj-1",
  "serviceId": "web-app",
  "flagKey": "checkout-cta",
  "algorithm": "thompson_sampling",
  "minExplorationFloor": 5,
  "minSampleSizePerVariant": 100,
  "confidenceThreshold": 0.95,
  "autoRolloutWinner": true
}

name, projectId, serviceId and flagKey are required. The tuning fields are optional and checked: environment (default production), algorithm (thompson_sampling, the default, or epsilon_greedy), epsilon (0 to 1), minExplorationFloor (the share each variant keeps, a whole-number percentage from 0 to 100, default 5), minSampleSizePerVariant (a whole number, at least 1), confidenceThreshold (above 0, at most 1) and autoRolloutWinner (a boolean). Other values get 400 ("error": "Validation Error", with each problem's path and message in details): the experiment writes the floor into the flag's variant weights, which must be whole numbers.

Get Bandit Status

GET /api/experiments/[id]/bandit-status

Reallocate Bandit Traffic

POST /api/experiments/[id]/reallocate

Rebalances variant traffic allocations according to posterior win probabilities. If the statistical confidence threshold is met, automatically promotes the winner to 100% rollout.

409 APPROVAL_REQUIRED where the experiment's environment requires approval; 409 ROLLOUT_IN_PROGRESS while a live rollout plan manages the flag; 422 FLAG_NOT_SERVABLE when the new weights would leave a flag the evaluation API couldn't load. The reallocation runs under the flag's rollout lock.

Record Bandit Reward

POST /api/experiments/[id]/reward
{
  "variantName": "variant-b",
  "converted": true
}

Authorized like flag evaluation for the experiment's project, with the experiment's service, environment and flag as the scope: service-, environment- and flag-scoped SDK keys work for their own experiment, and a signed-in member's access overrides apply. Anonymous calls get 401.


Dynamic Audience Cohorts & Membership

Both cohort creation routes (POST /api/projects/{id}/cohorts and POST /api/cohorts) record the caller as createdBy; a createdBy in the body is ignored, as it is on PATCH.

Evaluate Cohort Membership

POST /api/projects/[id]/cohorts/[cohortId]/evaluate
{
  "userId": "user-123",
  "context": {
    "email": "alice@corp.com",
    "country": "AU"
  }
}

Evaluating membership only reads, so it is tiered as a read: read-tier connectors, API tokens and personal access tokens can call it.


Flag Triggers

Scoped, revocable URLs that apply a flag action — designed for CI/CD pipelines ("enable the flag when deploy completes"). The token is the capability: POST the URL with no auth headers.

Create a Trigger

POST /api/flags/{key}/triggers
Authorization: Bearer <dashboard session or admin-tier connector token>

{
  "serviceId": "web",
  "environment": "production",
  "action": "enable",          // enable | disable | toggle
  "name": "deploy-complete"
}

Returns the trigger url and raw token once — only the SHA-256 hash is stored. Triggers are also managed from the flag's Triggers tab in the console.

Creating a trigger needs write access to the flag's service and environment, from a signed-in dashboard session or an MCP connector with the admin tier. Project API tokens and personal access tokens can't mint credentials (403). Creation is also refused where execution would refuse the trigger: 403 ("capabilities on the shared demo need a project membership") if you reach the project only through the shared demo's public access, and 409 APPROVAL_REQUIRED if the environment is protected with required approval. A trigger can't open a change request, so change the flag from the dashboard or with POST /api/flags/{key}/toggle instead. The audit log records trigger.create and trigger.revoke on the flag, including which kind of credential minted the trigger.

Execute a Trigger

POST /api/triggers/{token}     // no auth — the token is the capability

Applies the action through the full mutation path: version snapshot, a flag.toggle audit entry as trigger:{name} with metadata.capability: "flag_trigger", SSE fanout and cache invalidation. Rate-limited to 30 executions/minute per token. 404 for unknown and revoked tokens.

A trigger acts for the member who created it, and every run re-checks that member's current access:

  • 403 (CAPABILITY_CREATOR_UNAUTHORIZED) once the creator has left the project or no longer has write on the trigger's service and environment (role or access override). Ask a current member with write access to create a new trigger.
  • 409 (APPROVAL_REQUIRED) in a protected environment that requires approval. A trigger can't open a change request: change the flag from the dashboard or with POST /api/flags/{key}/toggle, which requests approval.
  • 409 (ROLLOUT_IN_PROGRESS) when the trigger would switch on a flag that a live (active or paused) rollout plan manages in that environment. For a boolean flag, enable also sets the default to true. Switching the flag off — the kill switch — always works.

List / Revoke

GET    /api/flags/{key}/triggers?serviceId=web
DELETE /api/flags/{key}/triggers/{triggerId}?serviceId=web

Listing needs read access to the flag's service (and environment, when given). Without environment, only triggers in environments you can read are listed (access overrides apply). Callers who reach the project only through the shared demo's public access get an empty list. DELETE only revokes a trigger on that flag and service (404 otherwise). Like creating one, it needs write on the trigger's own service and environment (access overrides and narrow token scopes apply) and a project membership: shared-demo floor callers get 403 ("capabilities on the shared demo need a project membership").

POST   /api/flags/{key}/share          { "serviceId": "web", "environment": "production", "permissions": "view" | "toggle", "expiresIn": "1h" | "24h" | "7d" | "30d" }
GET    /api/flags/{key}/share?serviceId=web&environment=production
DELETE /api/flags/{key}/share/{shareId}
GET    /api/f/{shareId}                // public — the link id is the capability
POST   /api/f/{shareId}                // public, toggle links only — { "enabled": true | false }, or no body to flip

A share link shows (view) or flips (toggle) one flag in one environment for anyone holding the URL, and keeps working after the credential that created it is revoked. environment defaults to development.

Creating any share link therefore counts as credential issuance: it needs write access to the flag's service and environment from a dashboard session or an admin-tier MCP connector. Project API tokens, personal access tokens and write-scope connectors get 403. Callers who reach the project only through the shared demo's public access can't create or revoke links (403). Toggle links aren't created in environments that require approval (409 APPROVAL_REQUIRED). Creation is audited as share_link.create, never with the link id.

Listing needs read access; toggle links are shown only to callers who could create one. Callers who reach the project only through the shared demo's public access see createdBy only on links they created (others: "redacted").

Revoking needs write on the link's service and environment (access overrides and narrow token scopes apply), returns 404 when the URL's flag key doesn't match the link, and is recorded in the audit log as share_link.revoke.

Using a link. A share link acts for the member who created it:

  • it shows the flag only while they can still read it (404 otherwise);
  • it reports permissions: "view" once they can no longer change the flag.

A toggle answers:

  • 403 (CAPABILITY_CREATOR_UNAUTHORIZED) once the creator lost write;
  • 409 (APPROVAL_REQUIRED) in protected environments that require approval;
  • 409 (ROLLOUT_IN_PROGRESS) when it would switch on a flag a live rollout plan manages. Switching off always works.

Toggles are limited to 30 a minute per link and audited as flag.toggle with metadata.capability: "share_link". The entry carries a short fingerprint, never the link id. Shared flag pages (/f/{shareId}) show why a toggle was refused.

Watching Flags & Notifications

Follow a flag to see its mutations in the console notifications bell.

POST   /api/flags/{key}/watch     { "serviceId": "web", "environment": "production" }
DELETE /api/flags/{key}/watch?serviceId=web&environment=production
GET    /api/flags/{key}/watch?serviceId=web&environment=production   // { "watching": true }

GET    /api/notifications          // recent audit events on watched flags + unreadCount
POST   /api/notifications          // mark all read

Watching a flag and reading its watch state need read access to the flag in that service and environment. Access overrides apply: 403 where yours hides the service or environment.

GET /api/notifications returns events only for watched flags in projects you can still read (with an API token or connector: its own projects), and only events in services and environments you can read. An event's service and environment are the ones the audit log recorded (details.metadata, or the flag snapshot in details.before/details.after). Every one an event names must be readable, and the first of each fills the notification's serviceId and environment. An event that names no environment (other than a flag-owner change, which concerns none) or no service is left out for callers whose access overrides set some environment or service to none. It returns up to 50 events from the last 14 days, newest first. Events in a service or environment you can't read (access overrides, narrow tokens) are skipped without taking places in the feed. On the shared demo and showcase, callers who reach the project only through its public access get the audit trail's floor view: flag, service, rollout, experiment, impact and AI events only, with actorId: "redacted" and actorEmail: null for anyone else. Their own events and the system's keep the actor. POST /api/notifications (mark all read) needs a signed-in dashboard session.

Evaluation Contexts

GET /api/contexts?serviceId=web&environment=production
GET /api/contexts?serviceId=web&key=user-alice-1     // one context's flag→value map

Recent evaluation contexts grouped by targetingKey — attributes, eval count, and what each flag resolved to. Backed by the in-memory evaluation ring (last ~1,000 evals per instance).

Rate Limiting

Rate-limited routes on flaggr.dev (single and batch evaluation, OFREP, Connect evaluation and configuration, and event ingestion) send headers for each limit they check:

HeaderDescription
X-RateLimit-Limit-IPRequests allowed per window for the caller's IP address
X-RateLimit-Remaining-IPRequests left in the window
X-RateLimit-Reset-IPUnix time (seconds) when the window resets

The per-token and per-service limits send the same headers ending in -Token and -Service.

Limits: 1,000/min per IP (an IPv6 address counts by its /64), 5,000/min per API token, 10,000/min per service. Requests that the api.flaggr.dev edge sends on to flaggr.dev (see Hosts) count against the caller's own address.

A rate-limited request gets 429 with a Retry-After header (seconds) and a body of { "error": "Too Many Requests", "message": "…", "retryAfter": 45 }. The data plane at api.flaggr.dev doesn't send these headers. See Rate Limiting.

Error Responses

All errors follow a consistent format:

{
  "error": "Not Found",
  "message": "Flag 'checkout-v3' not found in service 'web-app'"
}
StatusDescription
400Bad request — invalid parameters or validation failure
401Unauthorized — missing or invalid authentication
403Forbidden — insufficient permissions
404Not found
409Conflict — duplicate resource
422Unprocessable — the write would leave a flag the evaluation API couldn't load ("code": "FLAG_NOT_SERVABLE"), see Refused Flag Writes
429Rate limited
500Internal server error
503Service unavailable

Request Size Limits

EndpointMax request body
Flag create and update (POST /api/flags, PATCH /api/flags/{key}, toggle)256 KB
Flag evaluation on flaggr.dev (POST /api/flags/evaluate, /evaluate/batch, /evaluate-debug)64 KB
Bulk create and import (POST /api/flags/bulk, POST /api/flags/import, POST /api/projects/{id}/import)25 MiB (26,214,400 bytes)
Bulk update (PATCH /api/flags/bulk)1 MB
Evaluation on api.flaggr.dev (REST, batch, OFREP, the playground)128 KiB
POST /api/events/outcomes (either host)128 KiB
POST /api/events/exposures/batch1 MiB
POST /api/analytics/sdk-telemetry (either host)2 MiB
POST /api/ingest/server-events256 KiB

A larger body gets 413. On flaggr.dev the flag limits are checked against Content-Length, and the hosting platform's own limit (4.5 MB on Vercel) applies before any of them. The outcome, exposure and telemetry routes also stop reading a body sent without a Content-Length once it passes the limit, and answer 413 before they check its credential (outcomes and exposure batches first answer 401 to a request with no Authorization header). On those three routes, a body that can't be read gets 400. An OFREP evaluation context may hold at most 128 attributes and 64 KiB on both hosts.