REST API Reference
Base URL
http://your-checkgate-server:3000Authentication
All protected endpoints require one of:
Authorization: Bearer sk_live_your_sdk_keyAuthorization: Bearer pat_your_personal_access_tokenor an active session cookie set by POST /api/auth/login.
An SDK key is for the SDKs themselves and ships inside browser and mobile apps, so treat it as public. It only reaches the SDK endpoints, and only for the environment it is bound to: the SSE stream, the flags snapshot, reading flags (GET /api/environments/{env_id}/flags[/{key}]), and reporting impressions and events. Every other endpoint returns 403 for an SDK key.
For CI/CD, Terraform, the Kubernetes operator, or any other automation, use a personal access token (see Personal Access Tokens): it acts as its owning user — same role, same project memberships — and can be capped to read-only.
Dashboard mutation requests also require:
X-Checkgate-Request: trueThis header is required for all state-changing requests from browser clients (CSRF protection). SDK clients using Authorization: Bearer are exempt.
Auth
Login
POST /api/auth/login
Content-Type: application/jsonRequest Body
{
"email": "admin@example.com",
"password": "your-password"
}Response 200 OK
{
"email": "admin@example.com",
"name": "Juan Dela Cruz",
"role": "admin",
"workspace_name": "Acme Corp",
"is_setup_complete": true
}Sets an HttpOnly SameSite=Strict session cookie valid for 7 days. The server enforces the expiry and checks the account and its current role on every authenticated request. Deleting an account invalidates its existing sessions.
Response 401 Unauthorized
{
"error": "Incorrect email or password.",
"attempts_remaining": 4
}Response 429 Too Many Requests — this client is locked out of the account after LOGIN_MAX_FAILURES_PER_CLIENT (default 5) failures in 10 minutes, or the account is locked for every client after LOGIN_MAX_FAILURES_PER_ACCOUNT (default 50); see Login lockout. attempts_remaining counts the calling client's own failures only.
{
"error": "Too many failed attempts. Account locked for 15 minutes.",
"retry_after_seconds": 900
}Logout
POST /api/auth/logoutClears the session cookie.
Response 204 No Content
Get Current User
GET /api/auth/meResponse 200 OK — returns the authenticated user (same shape as login response, includes is_setup_complete).
Response 401 Unauthorized — no valid session.
Workspace Info
GET /api/auth/workspacePublic endpoint — no auth required. Returns the workspace name for the login page.
Response 200 OK
{ "workspace_name": "Acme Corp", "is_setup_complete": true }First-Run Setup
These endpoints exist only until the first admin has been created; afterwards both return 404. They require the installation's one-time setup token in a header (never a query parameter):
X-Checkgate-Setup-Token: <token>The token is the server's SETUP_TOKEN value, or — when that is unset — a random token each instance writes to its SETUP_TOKEN_FILE on boot (see Self-Hosting → First-run setup). A missing or wrong token returns 401.
Get the Seeded SDK Key
GET /api/setup/key
X-Checkgate-Setup-Token: <token>Response 200 OK — the SDK key generated on first boot, in the same shape as Create SDK Key (id, name, key, prefix, environment_id, environment_name, created_at).
Complete Setup
POST /api/setup/complete
Content-Type: application/json
X-Checkgate-Request: true
X-Checkgate-Setup-Token: <token>{
"workspace_name": "Acme Corp",
"project_name": "My App",
"name": "Juan Dela Cruz",
"email": "admin@example.com",
"password": "at-least-8-characters"
}Response 200 OK — the new admin (same shape as Login), with a session cookie set.
| Status | Meaning |
|---|---|
401 | Missing or invalid setup token |
404 | Setup is already complete |
409 | An account with this email already has a password |
422 | Missing field or password shorter than 8 characters |
Setup is atomic: it runs in one transaction under a PostgreSQL advisory lock and re-checks completion while holding it, so if several requests race — on one instance or many — exactly one creates the admin and the others get 404.
Rate Limits
Requests are limited per client IP, with a separate budget per kind of endpoint. Defaults (requests per minute, configurable — see Self-Hosting → Rate limits):
| Class | Endpoints | Default |
|---|---|---|
| Auth | POST /api/auth/login, /api/setup/* | 20 |
| API | every other /api/* route | 300 |
| SDK | GET /flags/snapshot | 600 |
| SSE connect | opening GET /stream (events on an open stream are not counted) | 120 |
| Ingest | POST /api/environments/{env_id}/impressions and /events | 600 |
| — | GET /health, /health/live, /health/ready, dashboard files | never limited |
A refused request gets 429 Too Many Requests with a Retry-After header (seconds) and:
{
"error": "Too many requests. Please slow down and try again shortly.",
"retry_after_seconds": 3
}Impression and event ingestion additionally has a quota per credential (each SDK key, and each user ingesting with a session or token), shared by all instances: 20,000 requests and 60,000 rows per minute by default, where a row counts as one unit, or one unit per started KiB of body if that is larger. A request over either budget gets the same 429 response (Retry-After at most 61 s) and none of its rows are stored. See Self-Hosting → Per-key ingest quota.
Projects
Projects are the top-level namespace for environments, flags, and SDK keys. Workspace admins can manage all projects; other users see only projects they are members of.
List Projects
GET /api/projectsReturns all projects the caller has access to (all projects for workspace admins; only member projects for others).
Response 200 OK
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Mobile App",
"slug": "mobile-app",
"environment_count": 3,
"member_count": 4,
"created_at": "2026-04-18T00:00:00Z"
}
]Get Project
GET /api/projects/{project_id}Any member of the project (workspace admins always have access).
Response 200 OK
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Mobile App",
"slug": "mobile-app",
"created_at": "2026-04-18T00:00:00Z"
}Response 403 Forbidden — the caller is not a member of the project.
Response 404 Not Found — project does not exist.
Create Project
POST /api/projects
Content-Type: application/jsonAdmin only. Creates a new, empty project: add its environments (POST /api/projects/{project_id}/environments) and SDK keys before creating flags. (Only the first project, created at setup, is seeded with environments and an SDK key.)
Request Body
{ "name": "Mobile App" }Response 200 OK — returns the created project.
Response 409 Conflict — slug derived from the name already exists.
Rename Project
PATCH /api/projects/{project_id}
Content-Type: application/json{ "name": "Mobile App v2" }Response 200 OK — returns the updated project.
Delete Project
DELETE /api/projects/{project_id}Admin only. Cascades to all environments, flags, SDK keys, and impressions in the project.
Response 204 No Content
Response 422 Unprocessable Entity — cannot delete the last project.
Project Members
List Members
GET /api/projects/{project_id}/membersResponse 200 OK
[
{
"user_id": 1,
"name": "Juan Dela Cruz",
"email": "juan.delacruz@example.com",
"role": "admin"
}
]Add Member
POST /api/projects/{project_id}/members
Content-Type: application/json{ "user_id": 2, "role": "editor" }rolemust be"admin","editor", or"viewer"
Response 200 OK — returns the added member.
Response 409 Conflict — user is already a member.
Update Member Role
PATCH /api/projects/{project_id}/members/{user_id}
Content-Type: application/json{ "role": "viewer" }Response 200 OK — returns the updated member.
Remove Member
DELETE /api/projects/{project_id}/members/{user_id}Response 204 No Content
Since 0.2.1, the removed user's open /stream connections (session or personal access token) that cover the project close on every instance, through Redis; nobody else's streams are affected. If Redis does not deliver the signal, each stream also re-checks its user's access every SSE_SESSION_RECHECK_SECS (default 30) and closes then. A reconnect is authorized again: a user left with access to no environment gets 403.
Environments
Environments are scoped to a project. All environment routes are nested under /api/projects/{project_id}/environments.
List Environments
GET /api/projects/{project_id}/environmentsResponse 200 OK
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "Production",
"slug": "production",
"color": "#ef4444",
"is_default": false,
"created_at": "2026-04-10T00:00:00Z"
}
]Create Environment
POST /api/projects/{project_id}/environments
Content-Type: application/jsonRequest Body
{
"name": "Canary",
"slug": "canary",
"color": "#f59e0b"
}name— required, max 100 charactersslug— required, max 64 characters, lowercase alphanumerics and hyphens onlycolor— optional, must be a valid hex color (#rgbor#rrggbb); defaults to#6366f1
Response 200 OK — returns the created environment.
Response 409 Conflict — slug already exists in this project.
Delete Environment
DELETE /api/projects/{project_id}/environments/{env_id}Response 204 No Content
Response 422 Unprocessable Entity — cannot delete the default or the last environment.
Set Default Environment
POST /api/projects/{project_id}/environments/{env_id}/defaultResponse 200 OK — returns the updated environment with is_default: true.
Set Approval Requirement
POST /api/projects/{project_id}/environments/{env_id}/require-approval
Content-Type: application/json{ "require_approval": true }When enabled, PATCH requests against flags in this environment no longer apply immediately — see Partially Update a Flag and Change Requests.
Response 200 OK — returns the updated environment.
Flags
Flag endpoints remain environment-scoped via {env_id} (UUID). The environment UUID can be obtained from the environments list.
List Flags
GET /api/environments/{env_id}/flags?limit=200&offset=0&include_archived=false&tag=checkoutAll query parameters are optional: limit (default 200, capped at 500), offset (capped at 1,000,000), include_archived (default false), and tag (only flags carrying that exact tag).
Response 200 OK
[
{
"key": "new-checkout-flow",
"is_enabled": true,
"rollout_percentage": 50,
"description": "New checkout UI rollout",
"rules": []
}
]Response 404 Not Found — environment does not exist.
Get a Flag
GET /api/environments/{env_id}/flags/{key}Response 200 OK — returns the flag object.
Response 404 Not Found — flag or environment does not exist.
Create or Replace a Flag
POST /api/environments/{env_id}/flags
Content-Type: application/jsonCreates a flag. If the key already exists in this environment, replaces it entirely unless the environment requires approval. In that case replacement returns 409 Conflict; use PATCH to submit a change request.
In an environment that requires approval (since 0.2.0), only an inert flag is created at once: is_enabled: false with no disabled_value (or disabled_value: false), which serves the built-in false and nothing else. Any other creation — an enabled flag, or a disabled one with its own off value — returns 202 Accepted with a pending change request whose action is create: nothing is stored or served to SDKs until someone other than the requester approves it. While one creation of a key is pending, another returns 409 Conflict.
A propose-scoped token (since 0.2.0) gets 403 Forbidden: a new flag is served to SDKs at once, and even a disabled one makes code that already reads the key get false instead of its own default, so creating flags is left to people.
Request Body
{
"key": "new-checkout-flow",
"is_enabled": true,
"rollout_percentage": 50,
"description": "New checkout UI rollout",
"rules": []
}Response 200 OK — returns the created flag.
Response 202 Accepted — the environment requires approval and the flag is not inert; returns the pending create change request, not a flag.
Response 403 Forbidden — the caller uses a propose or read_only token, or lacks write access to the project.
Response 409 Conflict — the environment requires approval and the key exists or already has a pending creation.
Response 422 Unprocessable Entity — invalid flag key or rollout_percentage out of range.
Partially Update a Flag
PATCH /api/environments/{env_id}/flags/{key}
Content-Type: application/jsonApplies a JSON merge patch. Only the provided fields are updated; omitted fields retain their current values.
{ "rollout_percentage": 100 }{ "is_enabled": false }Response 200 OK — returns the updated flag (applied immediately).
Response 202 Accepted — the environment has require_approval set, or the caller uses a propose token (always, in any environment); the patch was validated and queued as a pending change request instead of applied. Returns the created change request, not the flag (which is unchanged).
Response 404 Not Found — flag does not exist.
Response 422 Unprocessable Entity — the flag is over a configuration limit (since 0.1.31; stored flags keep working, only writes are checked): more than 500 rules; the same segment referenced twice, or more than 50 distinct segments; a prerequisite on the flag itself, listed twice, or more than 50 prerequisites; more than 100 variants. The same applies to Create or Replace a Flag. Segments are limited to 500 rules.
Delete a Flag
DELETE /api/environments/{env_id}/flags/{key}Deletes the flag and broadcasts a DELETE event to connected SDK clients. Returns 409 Conflict when the environment requires approval, preventing deletion and recreation from bypassing review.
Response 204 No Content
Promote a Flag
POST /api/environments/{env_id}/flags/{key}/promote
Content-Type: application/jsonCopies the flag's configuration from {env_id} to another environment atomically. The caller must have write access to the target project. Returns 409 Conflict when the target environment requires approval; submit a PATCH there for review instead.
Request Body
{ "target_env_id": "uuid-of-target-environment" }Response 200 OK — returns the flag as it now exists in the target environment.
Archive or Unarchive a Flag
POST /api/environments/{env_id}/flags/{key}/archive
POST /api/environments/{env_id}/flags/{key}/unarchiveNo request body. Requires editor role or above.
Archiving only hides a flag from the default list (GET …/flags without include_archived=true); it has no effect on evaluation. SDKs keep receiving and evaluating an archived flag exactly as before, so no SSE update or webhook is sent. Each call is recorded in the audit log (ARCHIVE / UNARCHIVE).
Response 200 OK — returns the flag with its metadata; archived_at (RFC 3339) is present while the flag is archived.
Response 404 Not Found — flag does not exist in this environment.
Evaluate a Flag (Playground)
POST /api/environments/{env_id}/flags/{key}/evaluateEvaluates a flag for a hypothetical user and explains the result, with the SDK engine and the configuration SDKs are served (segments expanded). It changes nothing: no audit entry, no impression, and the request body is neither logged nor stored. Any project member may call it, read_only tokens included; SDK keys may not.
{ "targeting_key": "user-123", "attributes": { "plan": "pro", "seats": 12, "beta": true } }Attribute values must be strings, numbers or booleans (numbers and booleans are evaluated as their string form, as SDKs receive them). Limits: targeting key 512 bytes, 100 attributes, names 128 bytes, values 1024 bytes.
Response 200 OK
{
"environment_id": "…", "flag_key": "new-checkout", "flag_type": "boolean",
"revision": 1042,
"enabled": true, "value": true, "reason": "TARGETING_MATCH",
"matched_rule": {
"rule": { "attribute": "plan", "operator": "equals", "values": ["pro"] },
"source_index": 1, "segment_key": "paying", "segment_rule_index": 0
},
"prerequisites": [],
"referenced_attributes": ["country", "plan"],
"missing_attributes": ["country"]
}reason is one of DISABLED, PREREQUISITE_FAILED, TARGETING_MATCH, ROLLOUT_EXCLUDED, SPLIT, DEFAULT, STATIC. matched_rule.source_index is the rule's index as stored (and shown in the dashboard); segment_key/segment_rule_index say which segment rule matched. rollout ({ percentage, bucket }) and variant ({ index, weight, total_weight, value }) appear when hashing was involved. prerequisites lists the flag's own prerequisites as checked (outcome: satisfied, unsatisfied, not_found, limit_exceeded), with each one's result and revision.
Response 422 Unprocessable Entity — invalid body; { "error": "…" } says why. Response 404 Not Found — no such flag in this environment. Response 503 Service Unavailable with Retry-After: 1 — this instance is already running PLAYGROUND_MAX_CONCURRENT playground evaluations (since 0.2.1); retry shortly. Requests are refused at once rather than queued.
Segments
Segments are named, reusable groups of targeting rules scoped to an environment. A flag targeting rule can reference a segment by segment_key instead of repeating the rules inline; the server expands the reference before flags reach SDK clients. Editing or deleting a segment automatically re-broadcasts every flag that references it. Segment writes return 409 Conflict in environments that require approval, because they can change the behavior of existing flags. Segment keys follow the same constraints as flag keys (alphanumerics, underscores, hyphens; max 100 chars). Writes require editor role or above.
List Segments
GET /api/environments/{env_id}/segmentsResponse 200 OK
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"environment_id": "660e8400-e29b-41d4-a716-446655440001",
"name": "Beta Users",
"key": "beta-users",
"description": "Internal beta cohort",
"rules": [
{ "attribute": "plan", "operator": "equals", "values": ["beta"] }
],
"created_at": "2026-07-04T00:00:00Z"
}
]Get a Segment
GET /api/environments/{env_id}/segments/{key}Response 200 OK — returns the segment object.
Response 404 Not Found — segment does not exist.
Create a Segment
POST /api/environments/{env_id}/segments
Content-Type: application/jsonEditor role or above.
Request Body
{
"name": "Beta Users",
"key": "beta-users",
"description": "Internal beta cohort",
"rules": [
{ "attribute": "plan", "operator": "equals", "values": ["beta"] }
]
}name— requiredkey— required, alphanumerics, underscores, hyphens; max 100 charsdescription— optionalrules— array of TargetingRule objects; defaults to[]
Response 200 OK — returns the created segment.
Response 422 Unprocessable Entity — invalid segment key.
Partially Update a Segment
PATCH /api/environments/{env_id}/segments/{key}
Content-Type: application/jsonEditor role or above. Only the provided fields are updated; omitted fields retain their current values, and "description": null clears the description. Flags referencing this segment are re-broadcast to connected SDK clients.
{ "rules": [ { "attribute": "plan", "operator": "equals", "values": ["beta", "trial"] } ] }Response 200 OK — returns the updated segment.
Response 404 Not Found — segment does not exist.
Delete a Segment
DELETE /api/environments/{env_id}/segments/{key}Editor role or above. Flags referencing this segment are re-broadcast without the segment's rules.
Response 204 No Content
Response 404 Not Found — segment does not exist.
Change Requests
Created by a flag PATCH in environments with require_approval enabled, by every PATCH made with a propose token, and (since 0.2.0) by creating a flag that is not inert in such an environment. A change request captures a flag PATCH (action: "update") or a new flag (action: "create", patch is the whole creation body) that hasn't been applied yet — see Partially Update a Flag and Create or Replace a Flag for how one gets created. Someone other than the requester must approve it (self-approval is rejected); admins may cancel anyone's pending request, mirroring how workspace admins bypass project membership elsewhere.
List Change Requests
GET /api/environments/{env_id}/change-requests?status=pendingstatus is optional — one of pending, approved, rejected, cancelled. Omit to list all.
Response 200 OK
[
{
"id": 1,
"environment_id": "550e8400-e29b-41d4-a716-446655440000",
"flag_key": "dark_mode",
"action": "update",
"patch": { "is_enabled": true },
"requested_by": "alice@acme.com",
"status": "pending",
"reviewed_by": null,
"reason": null,
"created_at": "2026-07-04T00:00:00Z",
"reviewed_at": null
}
]Approve Change Request
POST /api/environments/{env_id}/change-requests/{id}/approveApplies the stored patch to the flag's current state (not a stale snapshot from when the request was filed) and marks the request approved. For a create request, inserts the new flag; the audit log records the reviewer as actor, with change_request_id and requested_by in its metadata.
Response 200 OK — returns the updated (or created) flag.
Response 403 Forbidden — the caller is the original requester, or uses a propose or read_only token (neither can ever approve or reject).
Response 409 Conflict — the request is no longer pending (already approved/rejected/cancelled), or it is a create request and the key exists by now (the request stays pending; reject or cancel it).
Reject Change Request
POST /api/environments/{env_id}/change-requests/{id}/reject
Content-Type: application/json{ "reason": "Not ready for this rollout yet" }reason is optional. The flag is never touched.
Response 204 No Content
Cancel (Withdraw) Change Request
DELETE /api/environments/{env_id}/change-requests/{id}Only the original requester or a workspace admin may cancel, and only while still pending. A propose token may cancel only its owner's own requests — the admin override does not apply to it.
Response 204 No Content
Response 404 Not Found — no such pending request, or the caller doesn't own it.
Flag Schema
Flag Object
| Field | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Unique within environment. Alphanumerics, underscores, hyphens. Max 100 chars. Immutable after creation. |
is_enabled | boolean | Yes | Master switch. false always evaluates to the disabled result. |
rollout_percentage | integer | null | No | 0–100. null is treated as 100%. |
description | string | null | No | Human-readable description. |
rules | TargetingRule[] | No | Targeting rules, evaluated in order (first match wins). Defaults to []. |
flag_type | "boolean" | "string" | "integer" | "json" | No | Variant type. Defaults to "boolean". |
default_value | any (matching flag_type) | No | Returned when enabled, inside the rollout, and no rule matched. |
disabled_value | any (matching flag_type) | No | Returned when disabled, outside the rollout, or a prerequisite fails. |
variants | WeightedVariant[] | No | Weighted multivariate distribution — see Weighted Variants. Defaults to []. |
prerequisites | Prerequisite[] | No | Other flags this flag depends on — see Prerequisite Flags. Defaults to []. |
tags | string[] | No | Free-form lifecycle/organization tags. Defaults to []. |
owner_email | string | null | No | Email of the flag's owner. Omitted from reads made with an SDK key (SDK keys are public). |
archived_at | ISO-8601 string | null | No | Set when the flag is archived; null for active flags. |
TargetingRule Object
| Field | Type | Required | Description |
|---|---|---|---|
attribute | string | Yes* | User attribute name to match against. Not required when segment_key is set. |
operator | Operator | Yes* | Comparison operator. Not required when segment_key is set. |
values | string[] | Yes* | One or more values to match. At least one must match. Not required when segment_key is set. |
segment_key | string | null | No | References a named segment instead of a concrete attribute check. Expanded server-side before reaching SDKs. |
variant | any (matching flag_type) | No | Value returned when this rule matches (non-boolean flags). Falls back to default_value if unset. |
Operator Enum
| Value | Description |
|---|---|
equals | Attribute value equals any of the provided values |
not_equals | Attribute value does not equal any of the provided values |
contains | Attribute value contains any of the provided values as a substring |
starts_with | Attribute value starts with any of the provided values |
ends_with | Attribute value ends with any of the provided values |
greater_than | Attribute, parsed as a number, is greater than any of the provided values |
greater_than_or_equal | Attribute, parsed as a number, is greater than or equal to any of the provided values |
less_than | Attribute, parsed as a number, is less than any of the provided values |
less_than_or_equal | Attribute, parsed as a number, is less than or equal to any of the provided values |
Non-numeric attribute or rule values never match the four numeric operators (no error — the comparison is simply skipped).
WeightedVariant Object
| Field | Type | Required | Description |
|---|---|---|---|
weight | integer | Yes | Relative weight. Weights need not sum to 100 — normalized against their total. |
value | any (matching flag_type) | Yes | The variant value returned when this weighted bucket is selected. |
Prerequisite Object
| Field | Type | Required | Description |
|---|---|---|---|
flag_key | string | Yes | The prerequisite flag's key. |
required_value | any (matching the prerequisite's flag_type) | No | The value the prerequisite must resolve to. Omit to just require it be enabled. |
Impressions
Ingest Impressions
POST /api/environments/{env_id}/impressions
Authorization: Bearer sk_live_your_key
Content-Type: application/jsonReports a batch of flag evaluation events from an SDK client. Accepts an SDK key bound to env_id, or a user (session or read_write token) with write access to the environment — viewers and read_only tokens get 403. CSRF header not required for Bearer-authenticated requests.
Request Body — array of up to 500 impression objects
[
{
"flag_key": "checkout_v2",
"user_id": "user-123",
"value": "true",
"context": { "plan": "pro" },
"evaluated_at": "2026-04-18T10:00:00Z"
}
]| Field | Type | Required | Description |
|---|---|---|---|
flag_key | string | Yes | The evaluated flag key |
user_id | string | null | No | User identifier; null for anonymous |
value | string | Yes | Evaluation result (e.g. "true", "false") |
context | object | null | No | Evaluation context attributes |
evaluated_at | ISO-8601 string | No | When the evaluation happened. Defaults to server receive time; the SDKs always send it, so experiment attribution doesn't depend on which batch arrives first |
Response 204 No Content
| Status | When | Rows stored |
|---|---|---|
400 / 422 | Body is not valid JSON / not an array of impression objects | None |
403 | The SDK key is bound to another environment, or the user cannot write to it | None |
413 | More than 500 items, or a body over 256 KiB | None |
415 | Content-Type is not JSON | None |
429 | Per-address rate limit or per-key ingest quota exceeded; Retry-After says when to retry | None |
Rows with an empty flag_key or one longer than 100 characters are skipped; the rest of the batch is stored. Rows are kept for ANALYTICS_RETENTION_DAYS (default 90) after they are received, longer while a running or paused experiment uses them (Self-Hosting → Analytics retention).
List Impressions
GET /api/environments/{env_id}/impressionsQuery Parameters
| Param | Default | Description |
|---|---|---|
flag_key | — | Filter by exact flag key |
user_id | — | Filter by exact user ID |
value | — | Filter by evaluated value (e.g. "true", "false") |
since_id | — | Return only rows with id > since_id — for live polling |
limit | 50 | Max results (1–200) |
offset | 0 | Pagination offset (ignored when since_id is set) |
total in the response always reflects the count matching the base filters (ignoring since_id), so it can be used for pagination display regardless of polling state.
Response 200 OK
{
"items": [
{
"id": 142,
"flag_key": "checkout_v2",
"user_id": "user-123",
"value": "true",
"context": { "plan": "pro" },
"evaluated_at": "2026-04-18T10:00:00Z"
}
],
"total": 142
}Impression Stats
GET /api/environments/{env_id}/impressions/statsReturns per-flag aggregate counts.
Response 200 OK
[
{
"flag_key": "checkout_v2",
"total": 1420,
"true_count": 750,
"false_count": 670,
"unique_users": 89,
"last_seen": "2026-04-18T10:30:00Z"
}
]Exposure
GET /api/environments/{env_id}/impressions/exposure?flag_key=checkout_v2&days=14Exposure breakdown for a single flag — per-variant impression and unique-user counts across the whole retained window, plus a daily timeline of evaluations per variant. Powers the "which users are being exposed to which variant?" dashboard.
Query Parameters
| Param | Default | Description |
|---|---|---|
flag_key | — | Required. The flag to break down (max 100 chars). |
days | 14 | Trailing days included in the daily timeline (clamped to 1–90). |
Response 200 OK
{
"flag_key": "checkout_v2",
"total_impressions": 1420,
"total_users": 89,
"variants": [
{ "value": "true", "impressions": 750, "unique_users": 60 },
{ "value": "false", "impressions": 670, "unique_users": 52 }
],
"timeline": [
{ "day": "2026-07-01", "value": "true", "count": 42 },
{ "day": "2026-07-01", "value": "false", "count": 38 }
]
}Response 422 Unprocessable Entity — flag_key missing or too long.
Experiments
Experiments pair a flag with a goal event to measure conversion per variant. They are environment-scoped. Each experiment names the flag_key whose variants are the treatment arms and the goal_event_key (see Events) that counts as a conversion. Writes require editor role or above.
List Experiments
GET /api/environments/{env_id}/experimentsResponse 200 OK
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"environment_id": "660e8400-e29b-41d4-a716-446655440001",
"key": "checkout-copy-test",
"name": "Checkout copy test",
"description": "Does the new CTA convert better?",
"flag_key": "checkout_v2",
"goal_event_key": "purchase_completed",
"control_variant": "false",
"status": "running",
"created_at": "2026-07-04T00:00:00Z"
}
]Get an Experiment
GET /api/environments/{env_id}/experiments/{key}Response 200 OK — returns the experiment object.
Response 404 Not Found — experiment does not exist.
Create an Experiment
POST /api/environments/{env_id}/experiments
Content-Type: application/jsonEditor role or above.
Request Body
{
"name": "Checkout copy test",
"key": "checkout-copy-test",
"description": "Does the new CTA convert better?",
"flag_key": "checkout_v2",
"goal_event_key": "purchase_completed",
"control_variant": "false"
}name— required, non-emptykey— required, alphanumerics, underscores, hyphens; max 100 charsflag_key— required, the flag under test (same key constraints)goal_event_key— required, the conversion event key (same key constraints)control_variant— optional, the baseline variant to compare againstdescription— optional
Response 200 OK — returns the created experiment.
Response 409 Conflict — an experiment with this key already exists in the environment.
Response 422 Unprocessable Entity — invalid key, flag key, goal event key, or empty name.
Partially Update an Experiment
PATCH /api/environments/{env_id}/experiments/{key}
Content-Type: application/jsonEditor role or above. Only the provided fields are updated.
{ "status": "paused" }status— one ofrunning,paused,completedname,description,goal_event_key,control_variant— also updatable (goal_event_keymust satisfy the key constraints)
Response 200 OK — returns the updated experiment.
Response 404 Not Found — experiment does not exist.
Response 422 Unprocessable Entity — invalid status or goal_event_key.
Delete an Experiment
DELETE /api/environments/{env_id}/experiments/{key}Editor role or above.
Response 204 No Content
Response 404 Not Found — experiment does not exist.
Experiment Results
GET /api/environments/{env_id}/experiments/{key}/resultsComputes per-variant conversion rates and a two-proportion significance test of each variant against the control. Each user enters the experiment at their first exposure to the flag and is bucketed into the variant they saw then; a user counts as converted only if they fired the goal event at or after that first-exposure timestamp. The control is the experiment's control_variant when present in the data, otherwise the highest-exposure variant.
Response 200 OK
{
"experiment": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"environment_id": "660e8400-e29b-41d4-a716-446655440001",
"key": "checkout-copy-test",
"name": "Checkout copy test",
"description": "Does the new CTA convert better?",
"flag_key": "checkout_v2",
"goal_event_key": "purchase_completed",
"control_variant": "false",
"status": "running",
"created_at": "2026-07-04T00:00:00Z"
},
"control_variant": "false",
"total_exposed": 1200,
"total_converted": 240,
"variants": [
{
"variant": "false",
"exposed": 600,
"converted": 90,
"conversion_rate": 0.15,
"is_control": true,
"uplift": null,
"z_score": null,
"p_value": null,
"significant": false
},
{
"variant": "true",
"exposed": 600,
"converted": 150,
"conversion_rate": 0.25,
"is_control": false,
"uplift": 0.6667,
"z_score": 4.33,
"p_value": 0.0000149,
"significant": true
}
]
}| Field (per variant) | Type | Description |
|---|---|---|
variant | string | The evaluated value that defines this arm. |
exposed | integer | Distinct users bucketed into this variant (by first exposure). |
converted | integer | Of those, how many fired the goal event at/after exposure. |
conversion_rate | number | converted / exposed, in [0, 1]. |
is_control | boolean | true for the baseline variant the others compare against. |
uplift | number | null | Relative uplift vs. control (e.g. 0.12 = +12%). null for the control or when control conversion is zero. |
z_score | number | null | Two-proportion z-score vs. control. null for the control or when the test is undefined. |
p_value | number | null | Two-sided p-value for the z-score. null when z_score is null. |
significant | boolean | true when p_value < 0.05 (95% gate). |
Response 404 Not Found — experiment does not exist.
Events (A/B Goal Events)
Goal (conversion) events reported by SDK clients via track(). They are the denominator-matched conversions used by experiment results. Ingest is fire-and-forget, mirroring impression ingest.
Ingest Events
POST /api/environments/{env_id}/events
Authorization: Bearer sk_live_your_key
Content-Type: application/jsonAccepts an SDK key bound to env_id, or a user (session or read_write token) with write access to the environment — viewers and read_only tokens get 403. CSRF header not required for Bearer-authenticated requests.
Request Body — array of up to 500 event objects
[
{
"event_key": "purchase_completed",
"user_id": "user-123",
"value": 49.99,
"context": { "plan": "pro" },
"occurred_at": "2026-04-18T10:00:00Z"
}
]| Field | Type | Required | Description |
|---|---|---|---|
event_key | string | Yes | Goal event identifier (max 100 chars; rows with an empty or over-long key are skipped) |
user_id | string | null | No | User identifier; null for anonymous |
value | number | null | No | Optional numeric payload (revenue, count, duration…) |
context | object | null | No | Arbitrary context attributes |
occurred_at | ISO-8601 string | No | Defaults to server receive time; clamped to the server clock so a conversion never sorts ahead of its exposure |
Response 204 No Content
Response 404 Not Found — environment does not exist.
The other error responses (400, 403, 413, 415, 422, 429) are the same as for impression ingest, and none of them stores any row. Events share the impressions' per-key quota and retention.
List Event Keys
GET /api/environments/{env_id}/events/keysReturns the distinct goal-event keys seen in this environment, each with a usage count — used to populate the goal-event picker when creating an experiment.
Response 200 OK
[
{
"event_key": "purchase_completed",
"total": 1240,
"unique_users": 310,
"last_seen": "2026-04-18T10:30:00Z"
}
]SDK Keys
SDK keys are scoped to a project and bound to a specific environment. All key routes are nested under /api/projects/{project_id}/keys.
List Keys
GET /api/projects/{project_id}/keysReturns all SDK keys for the project. The full key value is never returned after creation.
Response 200 OK
[
{
"id": 1,
"name": "Default",
"prefix": "sk_live_a1b2c3…",
"environment_id": "550e8400-e29b-41d4-a716-446655440000",
"environment_name": "Production",
"created_at": "2026-04-10T00:00:00Z"
}
]Create Key
POST /api/projects/{project_id}/keys
Content-Type: application/json{
"name": "iOS Production",
"environment_id": "550e8400-e29b-41d4-a716-446655440000"
}environment_idmust belong to the project
Response 200 OK — returns the key including the full value (shown once only).
{
"id": 2,
"name": "iOS Production",
"key": "sk_live_a1b2c3d4e5f6...",
"prefix": "sk_live_a1b2c3…",
"environment_id": "550e8400-e29b-41d4-a716-446655440000",
"environment_name": "Production",
"created_at": "2026-04-18T12:00:00Z"
}Revoke Key
DELETE /api/projects/{project_id}/keys/{id}Response 204 No Content. Requests with the key are refused (401) from then on, on every instance. Streams already open in the key's environment close within SSE_RESYNC_SPREAD_MS (default 5 s) on every instance: the revoked key's clients are refused when they reconnect, and clients using other keys reconnect and re-bootstrap once.
Response 422 Unprocessable Entity — cannot revoke the last key in the project.
Personal Access Tokens
Personal access tokens are user-owned, not project-scoped — routes are flat under /api/tokens and always operate on the caller's own tokens. There is no admin override; revoking a departing or compromised user's automation access is done by deleting the user, which cascades to their tokens.
Token scopes
A token acts as its owning user — same workspace role, same project memberships — capped by its scope:
| Scope | Reads | Writes |
|---|---|---|
read_only | everything the owner can read | none |
propose | everything the owner can read | only: PATCH a flag → always a pending change request (202), in every environment; DELETE the owner's own pending change request; POST /api/tokens for a propose or read_only token (never read_write). Everything else (creating a flag, approve, reject, delete, promote, archive, segments, environments, keys, users, webhooks, revoking tokens, analytics ingest) is 403. |
read_write | everything the owner can read | everything the owner can do |
propose is meant for AI agents and other automation that should suggest changes but never apply, approve or reject one — the server enforces it on every request, whatever client sends it. Project roles still apply (a viewer's propose token cannot propose), and a change request can only be approved by someone other than its requester. See AI agents (MCP).
List Tokens
GET /api/tokensReturns the caller's own tokens. The full token value is never returned after creation.
Response 200 OK
[
{
"id": 1,
"name": "Terraform CI",
"prefix": "pat_a1b2c3d4e5f6…",
"scope": "read_only",
"created_at": "2026-07-04T00:00:00Z",
"last_used_at": "2026-07-04T09:02:09Z",
"expires_at": "2026-08-03T00:00:00Z"
}
]Create Token
POST /api/tokens
Content-Type: application/json{
"name": "Terraform CI",
"scope": "read_only",
"expires_in_days": 90
}scopeis"read_only","propose"(since 0.2.0) or"read_write"— see Token scopes. A request authenticated by a token may only create tokens at most as capable as itself (read_only<propose<read_write): a leaked read-only or propose credential cannot mint itself a more privileged replacement.expires_in_daysis optional (1–365); omit for a token that never expires.
Response 200 OK — returns the token including the full value (shown once only).
{
"id": 2,
"name": "Terraform CI",
"token": "pat_a1b2c3d4e5f6...",
"prefix": "pat_a1b2c3d4e5f6…",
"scope": "read_only",
"created_at": "2026-07-04T00:00:00Z",
"expires_at": "2026-10-02T00:00:00Z"
}Response 403 Forbidden — a token-authenticated caller tried to create a token more capable than itself (or one that outlives it).
Response 422 Unprocessable Entity — unknown scope, empty or over-long name, or expires_in_days outside 1–365.
Revoke Token
DELETE /api/tokens/{id}Response 204 No Content
Response 404 Not Found — no such token owned by the caller.
Users
Users are workspace-level. Role here is the workspace role; per-project access is managed via Project Members.
List Users
GET /api/usersResponse 200 OK
[
{
"id": 1,
"name": "Juan Dela Cruz",
"email": "juan.delacruz@example.com",
"role": "admin",
"created_at": "2026-04-10T00:00:00Z"
}
]Create User
POST /api/users
Content-Type: application/json{
"name": "Bob Jones",
"email": "bob@example.com",
"role": "viewer",
"password": "their-initial-password"
}rolemust be"admin","editor", or"viewer"passwordmust be at least 8 charactersemailmust be unique
Response 200 OK — returns the created user (password hash is never returned).
Response 409 Conflict — email already in use.
{ "error": "Email address is already in use." }Response 422 Unprocessable Entity — invalid input or password too short.
Delete User
DELETE /api/users/{id}Response 204 No Content
Response 422 Unprocessable Entity — cannot delete yourself or the last admin.
Scheduled Changes
A scheduled change stores a flag PATCH to be applied automatically at a future time. Each is bound to a specific flag and environment; once applied, its executed_at is set and it can no longer be deleted. Writes require editor role or above.
List Scheduled Changes
GET /api/environments/{env_id}/scheduled-changesLists all scheduled changes in the environment, ordered by scheduled_at. Each response includes attempts and last_error. Failed changes remain pending and are retried after at least 60 seconds; a successful retry clears last_error. If approval is enabled after scheduling, the worker retains the change without applying it until the policy permits execution.
Response 200 OK
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"environment_id": "660e8400-e29b-41d4-a716-446655440001",
"flag_key": "checkout_v2",
"scheduled_at": "2026-07-20T09:00:00Z",
"patch": { "is_enabled": true },
"executed_at": null,
"attempts": 0,
"last_error": null,
"created_at": "2026-07-04T00:00:00Z"
}
]List Scheduled Changes for a Flag
GET /api/environments/{env_id}/flags/{key}/scheduled-changesSame shape as above, filtered to a single flag.
Response 200 OK — array of scheduled changes for the flag.
Create a Scheduled Change
POST /api/environments/{env_id}/flags/{key}/scheduled-changes
Content-Type: application/jsonEditor role or above. The target flag must already exist.
Request Body
{
"scheduled_at": "2026-07-20T09:00:00Z",
"patch": { "is_enabled": true }
}scheduled_at— required, RFC-3339 / ISO-8601 timestamp; more than 30 seconds in the past is rejectedpatch— required, a JSON object validated against the current flag before scheduling
Returns 422 Unprocessable Entity for an invalid patch or timestamp, and 409 Conflict if the environment requires approval.
Response 200 OK — returns the created scheduled change.
Response 404 Not Found — the flag does not exist.
Delete a Scheduled Change
DELETE /api/environments/{env_id}/scheduled-changes/{id}Editor role or above. Only changes that have not yet executed can be deleted.
Response 204 No Content
Response 404 Not Found — no such pending change, or it has already executed.
Webhooks
Webhooks POST a JSON payload to an external URL when flags change in an environment. Delivery attempts are recorded in a per-webhook delivery log. All webhook routes require admin role. The secret is never returned after creation — responses expose only a has_secret boolean.
Delivery. Each event is a POST with Content-Type: application/json and User-Agent: Checkgate-Webhooks/1.0:
{
"event": "flag.updated",
"environment_id": "<uuid>",
"flag_key": "new-checkout-flow",
"flag": { "key": "new-checkout-flow", "is_enabled": true, "...": "..." },
"actor_email": "admin@example.com",
"metadata": null,
"timestamp": "<unix seconds>"
}Events include flag.created, flag.updated, flag.deleted, flag.promoted, flag.scheduled_change_applied, and change_request.opened / approved / rejected.
- Signature. With a
secret, the request carriesX-Checkgate-Signature: sha256=<hex>: HMAC-SHA256 of the raw request body, keyed with the secret. Verify it against the exact bytes received, with a constant-time comparison. - Retries. Up to 3 attempts, 1 s and then 5 s apart, only when the request fails to complete (connection or timeout errors). Any HTTP response, including a non-2xx one, is recorded and not retried.
- Redirects are not followed (a 3xx is recorded as the result), and at most 1 KiB of each response body is stored in the delivery log.
List Webhooks
GET /api/environments/{env_id}/webhooksResponse 200 OK
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"environment_id": "660e8400-e29b-41d4-a716-446655440001",
"name": "Slack notifier",
"url": "https://hooks.example.com/flag-changes",
"has_secret": true,
"enabled": true,
"created_at": "2026-07-04T00:00:00Z"
}
]Create a Webhook
POST /api/environments/{env_id}/webhooks
Content-Type: application/jsonAdmin only.
Request Body
{
"name": "Slack notifier",
"url": "https://hooks.example.com/flag-changes",
"secret": "whsec_your_signing_secret",
"enabled": true
}name— requiredurl— required, non-empty. It may not name a link-local address (169.254.0.0/16, where cloud metadata services answer,fe80::/10),fd00:ec2::254or the unspecified address (0.0.0.0/8,::); a hostname that resolves only to such addresses fails at delivery. Loopback and private addresses are allowed for internal receivers unless the server runs withWEBHOOK_ALLOW_PRIVATE_TARGETS=false(since 0.2.1), which refuses them too (see self-hosting); restrict the server's egress at the network layer as well.secret— optional; used to sign delivery payloads. Never returned afterwards.enabled— optional, defaults totrue
Response 200 OK — returns the created webhook (with has_secret, not the secret).
Response 422 Unprocessable Entity — empty url, or a refused address (above). The same check applies to url in an update.
Update a Webhook
PATCH /api/environments/{env_id}/webhooks/{id}
Content-Type: application/jsonAdmin only. Only the provided fields are updated.
{ "enabled": false }Response 200 OK — returns the updated webhook.
Response 404 Not Found — webhook does not exist in this environment.
Delete a Webhook
DELETE /api/environments/{env_id}/webhooks/{id}Admin only.
Response 204 No Content
Response 404 Not Found — webhook does not exist in this environment.
List Webhook Deliveries
GET /api/environments/{env_id}/webhooks/{id}/deliveriesReturns the 100 most recent delivery attempts for the webhook, newest first.
Response 200 OK
[
{
"id": 42,
"webhook_id": "550e8400-e29b-41d4-a716-446655440000",
"event": "flag.updated",
"status_code": 200,
"response_body": "ok",
"error": null,
"delivered_at": "2026-07-04T10:00:00Z"
}
]status_code/response_bodyarenullwhen the request never completed;errorthen holds the failure reason.
Response 404 Not Found — webhook does not exist in this environment.
Integrations (Slack / Microsoft Teams)
Chat integrations post a formatted message to a Slack or Microsoft Teams incoming webhook when something changes in an environment. Setup and troubleshooting: Slack & Teams Alerts. Reading integrations needs access to the environment; creating, changing, deleting and testing them requires admin role (the URL is a credential that can post to the channel).
The incoming-webhook URL is never returned after creation: responses carry webhook_url_preview, the last six characters.
Integration object
{
"id": "8f6c1c2e-1b7a-4d4e-9a55-0c4e2b6f1d3a",
"environment_id": "<uuid>",
"kind": "slack",
"name": "#releases",
"webhook_url_preview": "…Xy12Ab",
"events": ["flag.updated", "change_request.opened"],
"enabled": true,
"created_at": "2026-11-19 08:00:00+00"
}kind—slackorteams.events— the events to post. Empty means all. Supported:flag.created,flag.updated,flag.deleted,flag.promoted,change_request.opened,change_request.approved,change_request.rejected.- The URL must use
https://; plainhttp://is accepted only forlocalhost,127.0.0.1and::1(a local relay).
List Integrations
GET /api/environments/{env_id}/integrationsResponse 200 OK — an array of integration objects.
Create an Integration
POST /api/environments/{env_id}/integrations
Content-Type: application/json{
"kind": "slack",
"name": "#releases",
"webhook_url": "https://hooks.slack.com/services/T000/B000/XXXX",
"events": ["flag.updated"],
"enabled": true
}events (default [], all events) and enabled (default true) are optional.
Response 200 OK — the created integration.
Response 422 Unprocessable Entity — unknown kind, an empty or non-HTTPS URL (plain http:// is accepted only for localhost, 127.0.0.1 and ::1, and not at all when WEBHOOK_ALLOW_PRIVATE_TARGETS=false), a refused address (the same rule as for webhook URLs), or an unsupported event name.
Update an Integration
PATCH /api/environments/{env_id}/integrations/{id}
Content-Type: application/jsonAny of name, webhook_url, events, enabled; omitted fields are unchanged.
Response 200 OK — the updated integration. 404 if it does not exist in this environment; 422 for an invalid URL or event name.
Delete an Integration
DELETE /api/environments/{env_id}/integrations/{id}Response 204 No Content. 404 if it does not exist in this environment. Deleting the row stops Checkgate from posting; to invalidate the URL itself, remove the webhook in Slack or Teams.
Send a Test Message
POST /api/environments/{env_id}/integrations/{id}/testSends a sample message (a flag.updated for flag checkgate_test_flag, rendered for the integration's provider) to this integration only, and waits for the receiver's answer. It is sent even when the integration is disabled or does not subscribe to flag.updated, so the wiring can be checked before it is turned on; no other integration receives it. One attempt, no retries, at most 10 seconds. The attempt is recorded in the integration's delivery log with event test. Admin role required.
Response 200 OK, whether or not the message was delivered:
{ "delivered": false, "status_code": 404, "error": null }| Field | Meaning |
|---|---|
delivered | The receiver answered with a 2xx status |
status_code | The receiver's HTTP status; null when it was never reached |
error | Why nothing was delivered when the receiver was not reached (for example timed out after 10 s, could not connect: Connection refused (os error 111)); never contains the URL. null otherwise |
404 if {id} is not an integration of this environment.
Before v0.1.31 the endpoint answered 202 Accepted without a body and queued the sample as an environment event, which reached every enabled integration subscribed to flag.updated and not a disabled or filtered {id}.
List Integration Deliveries
GET /api/environments/{env_id}/integrations/{id}/deliveriesResponse 200 OK — the 50 most recent delivery attempts, newest first:
[
{
"id": 31,
"integration_id": "8f6c1c2e-1b7a-4d4e-9a55-0c4e2b6f1d3a",
"event": "flag.updated",
"status_code": 200,
"response_body": "ok",
"error": null,
"delivered_at": "2026-11-19 08:00:01+00"
}
]status_code is null and error is set when the request could not be completed. At most 1 KiB of each response body is stored. Delivery retries and redirects behave as for webhooks.
Audit Log
An append-only record of flag changes per environment. Each entry captures the actor, action, and before/after flag state.
List Audit Log
GET /api/environments/{env_id}/audit?flag_key=checkout_v2&limit=50&offset=0Query Parameters
| Param | Default | Description |
|---|---|---|
flag_key | — | Filter to a single flag |
limit | 50 | Max results |
offset | 0 | Pagination offset |
Entries are returned newest first.
Response 200 OK
[
{
"id": 128,
"environment_id": "660e8400-e29b-41d4-a716-446655440001",
"flag_key": "checkout_v2",
"actor_email": "juan.delacruz@example.com",
"action": "update",
"before_data": { "is_enabled": false },
"after_data": { "is_enabled": true },
"metadata": null,
"created_at": "2026-07-04T10:00:00Z"
}
]SSE Stream
Connect
GET /stream
Authorization: Bearer sk_live_your_key
Accept: text/event-streamOr for browser EventSource:
GET /stream?sdk_key=sk_live_your_keyOpens a persistent SSE connection scoped to the environment associated with the SDK key. The server sends:
- A
connectedevent immediately - One
updateevent per existing flag in the key's environment (bootstrap) - A
readyevent once the bootstrap replay is complete updateevents as flags change in that environment in real time- A
heartbeatevent whenever the stream has been quiet forSSE_HEARTBEAT_INTERVAL_SECS(default 15)
Event: connected
event: connected
data: {"environment_id":"<uuid>","heartbeat_ms":15000}Sent once when the connection is established. heartbeat_ms (0.1.31+) is the longest the stream stays silent while healthy; a client should treat a stream that sends nothing for several intervals as dead (the SDKs use 3) and reconnect. environment_id is null for session-cookie (dashboard) connections, which aren't scoped to a single environment. SDK clients should start staging the bootstrap replay that follows (keeping their current flags live until ready), and use environment_id to route impression reporting (POST /api/environments/{environment_id}/impressions).
Event: update
event: update
data: {"type":"UPSERT","env_id":"<uuid>","flag":{"key":"my-flag","is_enabled":true,...},"revision":41}event: update
data: {"type":"DELETE","env_id":"<uuid>","key":"my-flag","revision":42}Every event carries the flag's revision. Each write to a flag gets a higher one, and a DELETE carries the deleted row's last revision. Change events can arrive out of order — post-commit work such as audit logging runs concurrently — so clients should ignore an UPSERT older than the revision they hold for that flag (or not newer than the DELETE that removed it), and a DELETE older than the revision they hold. Servers before 0.1.25 send no revision.
A segment change counts as a write to every flag that uses the segment: those flags get a new revision and are republished with the new rules. The bootstrap replay also includes a DELETE for each flag deleted in the last day, carrying its last revision, so a client that connects after a delete can still reject a delayed event from before it.
Event: ready
event: ready
data: "3"Sent once the full bootstrap replay (the update events above) is complete — data is the number of flags sent. SDK clients should resolve their connect() promise on this event rather than guessing when bootstrap has finished. Sent on every (re)connection, not just the first.
Event: heartbeat
event: heartbeat
data: {}Sent when the stream has carried nothing else for heartbeat_ms; any other event resets the timer, so a busy stream sends none. It keeps proxies from closing an idle stream and lets clients detect a dead one. It is a named event, not an SSE comment, because EventSource never surfaces comments; it has data because EventSource drops events without data. Servers before 0.1.31 sent the comment : keep-alive-text every 15 s instead.
Errors
401 (unknown or revoked key) and 403 (key not allowed here) mean the key itself is rejected: retrying does not help, and the SDKs stop. A session or personal access token whose user can read no environment also gets 403 (since 0.2.1). 503 (instance draining, at SSE_MAX_CONNECTIONS, or bootstrap queue full) carries Retry-After; retry with backoff.
Reconnection
If the SSE connection drops, clients should reconnect with exponential backoff. On reconnect:
- Server sends
connected→ SDK starts staging a fresh copy, still evaluating the old one - Server replays all current flags for the environment → SDK collects them in the staged copy
- Server sends
ready→ SDK swaps the staged copy in as a whole, and resolvesconnect()if it hadn't already
This brings the SDK back to the server's state after updates missed while disconnected, and a replay cut short by another disconnect never replaces a complete flag set with a partial one. With a 0.1.31 server and SDK, a replay is also merged per flag with anything newer learned meanwhile; ordering is per flag, not across flags (configuration consistency).
The server also closes streams itself to force this resync when it may have missed updates: after its Redis subscription is re-established, once Redis is reachable again after a failed publish, or when its periodic reconciliation with PostgreSQL finds a committed change that never reached it (then only the affected environment's streams). These closes are spread over a few seconds (SSE_RESYNC_SPREAD_MS) so clients do not reconnect in lockstep. A stream more than 256 events behind is closed the same way. The server also closes every stream when it shuts down.
Refusals
GET /stream answers 503 Service Unavailable with a Retry-After header (seconds, jittered) when the instance is at SSE_MAX_CONNECTIONS, when no bootstrap slot frees up in time, or while it drains for shutdown:
{ "error": "Too many open streams on this instance.", "retry_after_seconds": 6 }Treat it like any failed connection attempt: back off and retry (the official SDKs do, and fall back to /flags/snapshot after repeated failures).
Flags Snapshot (Poll Fallback)
GET /flags/snapshot
Authorization: Bearer sk_live_your_keyReturns the full, segment-expanded flag set for the environment associated with the SDK key, as a plain JSON array — the same shape each flag has in an SSE update event, but without the type/env_id envelope:
[
{ "key": "my-flag", "is_enabled": true, "rollout_percentage": null, "rules": [], "flag_type": "boolean", ... }
]The response header X-Checkgate-Environment-Id identifies the environment for impression and conversion reporting. The response body remains a plain array, and the header is exposed through CORS.
Revisioned snapshot (?v=2, since 0.1.31)
GET /flags/snapshot?v=2
Authorization: Bearer sk_live_your_keyReturns the same flags with the revision of each and the environment's recent deletions:
{
"v": 2,
"flags": [ { "key": "my-flag", "is_enabled": true, "rules": [], ... } ],
"revisions": { "my-flag": 4182 },
"tombstones": { "old-banner": 4011 }
}revisions— each flag's committed revision: the same number its SSEupdateevents carry.tombstones— flags deleted within the tombstone retention (at least 24 hours) and not re-created, at the revision of the version deleted (what theDELETEevent carried).v— the format answered. An unknown highervgets the newest format the server knows; an older or unparsable one gets the plain array. Servers before 0.1.31 ignore the parameter.
Everything comes from one consistent read. Official SDKs from 0.1.31 request this format so they can merge a poll with a stream replay per flag and never go back to an older version (configuration consistency describes the guarantee and its limits). Revisions are ordered per flag only; do not compare the revisions of different flags.
Intended as a fallback for SDK clients when the SSE connection at /stream cannot be established at all — e.g. a corporate proxy or firewall blocking long-lived connections. Official SDKs poll this endpoint automatically after a configurable number of consecutive failed SSE reconnects (default: 3), and stop polling as soon as SSE reconnects successfully.
Unlike GET /api/environments/{env_id}/flags (user or SDK-key auth, segment references left unexpanded — intended for the dashboard UI), this route is keyed by SDK key alone, exactly like /stream, and returns segment-expanded flags ready to evaluate against directly.
Returns 400 if called with session-cookie auth rather than an SDK key (the dashboard isn't scoped to a single environment the way an SDK key is), 401 for missing/invalid credentials, and 503 with Retry-After when no read slot frees up in time (it shares SSE_BOOTSTRAP_CONCURRENCY with stream bootstraps).
Health Check
Public endpoints — no authentication, never rate limited.
GET /health/liveLiveness. 200 {"status":"alive"} whenever the process serves requests; never fails because PostgreSQL or Redis is down.
GET /health/readyReadiness — whether the instance should receive traffic.
{ "status": "ready", "checks": { "database": "ok", "redis": "ok" } }status | HTTP | Meaning |
|---|---|---|
ready | 200 | PostgreSQL and the Redis subscription are up |
degraded | 200 | Redis subscription down; serving, with changes from other instances recovered by reconciliation (503 instead with READY_REQUIRES_REDIS=true) |
unavailable | 503 | PostgreSQL did not answer within 2 s |
draining | 503 | Shutting down |
GET /healthLegacy check, unchanged: 200, body OK, while the process serves requests.
Metrics are not served on this port; see METRICS_ADDR in Observability.
SDK Connections
GET /api/health/connectionsLists the SSE connections currently open on the server instance that answers the request — connections are tracked in that process's memory, so behind a load balancer each instance reports only its own clients. Requires a session or a personal access token (either scope); SDK keys get 403.
Visibility follows project membership:
- Workspace admins see every connection, with the full client address.
- Everyone else sees only connections of environments in projects they are a member of, with
client_ipreduced to its network (/24for IPv4,/48for IPv6). Connections with no environment (dashboard sessions, the legacySDK_KEY) are visible to workspace admins only.
Response 200 OK
[
{
"connection_id": "9f2c4e1a7b3d5e60",
"environment_id": "a1b2c3d4-…",
"sdk_key_name": "Production",
"client_ip": "203.0.113.0/24",
"connected_at": 1767225600,
"last_delivered_revision": 1042
}
]last_delivered_revision is the highest flag revision this instance has written to the stream (null until the bootstrap replay was sent). It shows delivery as the server sees it, not what the SDK applied; an SDK reports that itself with getHealth().
GET /api/health/environmentsPer environment with open streams on this instance (same visibility rules, counts only):
[
{
"environment_id": "a1b2c3d4-…",
"connections": 12,
"latest_revision": 1042,
"connections_behind": 0,
"oldest_connected_at": 1767225600
}
]latest_revision is the environment's highest committed flag revision (deletions included). connections_behind counts streams not yet sent it: briefly non-zero while a change is in flight; persistently non-zero means notifications are being lost (see sync_divergences_total).