# Spoonity Flags API

Spoonity Flags is the feature-flag and experimentation service behind a
brand's apps. You define a flag once per brand, give it a set of treatments
(`on` and `off`, or any named variants), and write per-environment rules that
decide which treatment each customer or device gets: a percentage rollout,
a market restriction, a minimum app version, a list of beta testers, or a
kill switch. Apps evaluate flags **locally** through the Flags SDKs (Swift,
Kotlin, React Native), offline and with no network round trip per
evaluation, against definitions the service hands out and keeps fresh. A
backend that does not embed an SDK can ask the service to evaluate instead.

**Base URL:** `https://flags.spoonity.com`

The service has two API surfaces under that one host:

| Surface | Prefix | Credential | Who calls it |
|---|---|---|---|
| SDK API | `/sdk/v1` | SDK key (`sdk_c_…` client, `sdk_s_…` server) | Your mobile apps (through an SDK) and your backend services. **This is the integration surface.** |
| Admin API | `/admin/v1` | Spoonity account session (from `/auth/v1/login`) | People managing flags: the Flags console at `https://flags.spoonity.com/`, Prism's Flags section, and any script a brand admin writes against their own brand |

`/auth/v1` issues the admin session, and a handful of unauthenticated
operational routes (`/health`, `/ready`, `/version`, `/openapi.json`) sit at
the root.

The machine-readable contract is the OpenAPI 3.1 document at
[/docs/openapi/flags.yaml](openapi/flags.yaml), a copy of the one the
service generates and serves live at `https://flags.spoonity.com/openapi.json`.

The request and response bodies on this page were captured from the service
itself (a local instance built from the same source as production). The
vendor id and brand name are Spoonity's demo brand, secrets are replaced with
samples of the same shape, and long documents are shortened with `…`.

## Concepts

| Term | Meaning |
|---|---|
| **Workspace** | One per brand. A workspace **is** a Spoonity vendor: it carries a `vendorId`, and every admin route that takes `{ws}` accepts either the workspace id (`ws_01…`) or the vendor id (`1047166`). |
| **Environment** | A separate set of definitions, segments and SDK keys inside a workspace, usually `production` and `staging`. An SDK key belongs to exactly one environment, so the key alone decides which definitions an app sees. |
| **Flag** | Workspace-level metadata: key, name, description, tags, owner, archived. A flag has no behaviour of its own. |
| **Definition** | A flag's behaviour in one environment: whether it is enabled or killed, its treatments, traffic allocation, targeting rules and default rule. Versioned; every write bumps `version`. |
| **Treatment** | A named outcome (`on`, `off`, `v2`, …), optionally carrying a `config` string of JSON. The name `control` is reserved: it is what an evaluation returns when the flag has no definition or the SDK has nothing to answer with. |
| **Rule** | A list of conditions (all must match) and a distribution of treatments by percent. Rules are walked in order; the first match wins. |
| **Segment** | A named list of context keys in one environment (for example beta testers), used by the `in_segment` and `not_in_segment` matchers. |
| **Context** | What is being evaluated: a `key` (1 to 250 characters: a loyalty member id when signed in, a stable device id when not) plus optional `attributes`. |
| **Change number** | A per-environment counter, bumped on every definition or segment write to `max(previous + 1, now in epoch milliseconds)`. SDKs send the last one they saw as `since` and receive the current one as `till`. |
| **Impression** | A record that a context was shown a treatment. SDKs report them; server-side evaluation records them unless `dryRun` is set. |
| **Event** | A conversion outcome you report with `track` (`order.completed`, `wallet.pass_added`), used to measure what a rollout moved. |

**Keys must be opaque.** Impressions store the context key verbatim, and a
client key is public by design, so use a loyalty member id or a device id,
never an email address or phone number.

## Authentication

### SDK keys

```
Authorization: Bearer sdk_c_01h4z0k3s6tz0q6r8n1m2p3q4r
```

| Kind | Prefix | Where it lives | May call |
|---|---|---|---|
| client | `sdk_c_` | Inside the mobile app binary or its remote config. Treat it as public. | `definitions`, `memberships`, `impressions`, `events`, `stream` |
| server | `sdk_s_` | Your backend only. Secret. | Everything a client key may, plus `segments/{name}`, `flags/{flag}` and `evaluate` |

Full pattern: `^sdk_(c|s)_[0-9abcdefghjkmnpqrstvwxyz]{26}$`. A key belongs to
one environment of one brand, and that is the whole tenant model: there is no
vendor header on the SDK API. A client key on a server-only route answers
`403 forbidden`; an unknown or revoked key answers `401 unauthorized`.

The service stores only a SHA-256 hash of each key. The plaintext appears
exactly once, in the response that creates it.

**Getting a key.** A brand admin creates keys in Prism at ⚙ Product settings →
**SDK keys** (pick the environment, then Create), in the Flags console at
`https://flags.spoonity.com/`, or with
[`POST /admin/v1/environments/{env}/keys`](#post-adminv1environmentsenvkeys).
Create one client key per environment for the apps, and a separate server key
per backend service so each can be revoked on its own.

### Admin sessions

The admin API takes a session token for a person's **Spoonity platform
account**: the same email and password they use for the CMS and Links
dashboards. [`POST /auth/v1/login`](#post-authv1login) returns it;
send it as `Authorization: Bearer <token>`. The token is an HS256 JWT, valid
for 24 hours by default, bound to one vendor. Every admin route is then
confined to that vendor's workspace: anything belonging to another brand
answers `404 not_found`, the same as something that does not exist.

The role comes from the person's role at that vendor on the Spoonity
platform:

| Platform role name contains | Flags role | May |
|---|---|---|
| `owner`, `admin`, `administrator` | admin | editor, plus SDK keys, environment create, workspace update |
| `manager`, `editor`, `staff` | editor | viewer, plus create and update flags, save definitions, kill and restore, segments; may also create its own vendor's workspace |
| anything else (`vendor.reporting`, `vendor.accounting`, …) | viewer | every `GET`, plus `POST …/evaluate` (always a dry run) |

A request above the caller's role answers `403 forbidden`.

Accounts with hundreds of brands are supported: the vendor-selection token is accepted up to 64 KB
(it was 8 KB), `/auth/v1/*` bodies up to 96 KB, and the server takes request headers up to 80 KB, so
any proxy in front of Flags must pass headers that large (spoonity-flags #22).

The admin API also accepts Google ID tokens, for Spoonity staff and for
Spoonity's own service accounts (Prism's BFF and, since spoonity-flags #20, the Spoonity MCP server each use one and name the operator
it acts for in `X-Spoonity-Vendor`, `X-Spoonity-User` and `X-Spoonity-Role`).
Those headers are honoured only from an allow-listed Spoonity service
account; from any other caller they are ignored. Neither path is available to
an integrator.

## Conventions

Flags follows its own conventions, which differ from CMS and Links (see
[Conventions](/docs/conventions)).

**Errors** are RFC 7807 problem documents with
`Content-Type: application/problem+json`:

```json
{
  "type": "https://flags.spoonity.com/errors/version_conflict",
  "title": "Version conflict",
  "status": 409,
  "code": "version_conflict",
  "detail": "expectedVersion 0 but the definition is at 1",
  "instance": "/admin/v1/environments/1047166:production/flags/checkout-redesign/definition"
}
```

Branch on `code`, never on `title` or `detail`. Validation failures add
`errors: [{ "path", "message" }]`, one entry per problem. A `429` adds
`retryAfter` (seconds). `internal_error` always reads
`"detail": "unexpected error"`; quote the `x-request-id` response header when
reporting one.

| `code` | Status | When |
|---|---|---|
| `invalid_request` | 400 | Body or query failed validation, unknown field, malformed JSON, a `cursor` the service did not issue |
| `unauthorized` | 401 | Missing, malformed, expired or revoked credential |
| `forbidden` | 403 | Authenticated but not allowed: client key on a server route, role too low, another vendor's workspace create |
| `not_found` | 404 | Unknown (or not yours) workspace, environment, flag, definition, segment, key |
| `conflict` | 409 | Duplicate key or name, segment still referenced by a rule |
| `version_conflict` | 409 | `expectedVersion` did not match the stored definition |
| `payload_too_large` | 413 | Batch or body over the limit |
| `rate_limited` | 429 | Rate limit exceeded |
| `internal_error` | 500 | Unexpected |

**Unknown request fields are rejected** (`400`), so do not send extra
properties. Unknown **response** fields must be ignored: the service adds
fields without a version bump.

**Rate limits.** Every `/sdk/v1` and `/admin/v1` response carries
`RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds until
the token bucket is full again). A `429` also sets `Retry-After`. Default
budgets:

| Bucket | Default | Keyed by |
|---|---|---|
| SDK reads (`definitions`, `memberships`, `segments`, `flags`, `stream`) | 600 per minute | SDK key |
| SDK batches (`impressions`, `events`) | 60 per minute | SDK key |
| `POST /sdk/v1/evaluate` with a server key | 6000 evaluated contexts per minute (a batch of 40 costs 40) | SDK key |
| Concurrent `GET /sdk/v1/stream` connections | 5 | SDK key |
| Admin API | 300 per minute | Signed-in identity |
| `POST /auth/v1/login`, `/select-vendor` | 10 per minute | Client IP |

Honour `Retry-After` and back off with jitter. Do not retry a `4xx` other
than `429`.

**Pagination.** Admin list routes take `?cursor=<opaque>&limit=<1..200>`
(default 50) and answer `{ "items": [ … ], "nextCursor": "…" }`, with
`nextCursor: null` on the last page. Never build a cursor yourself.

**Caching.** `definitions`, `memberships`, `segments/{name}` and
`flags/{flag}` send a strong `ETag` and
`Cache-Control: no-cache, must-revalidate`; send the ETag back in
`If-None-Match` to get a bodiless `304 Not Modified` when nothing changed.
Admin responses are `no-store`.

**Timestamps.** SDK payloads use Unix epoch **milliseconds** (`time`,
`changeNumber`). Admin resources use ISO 8601 with a trailing `Z`
(`2026-09-30T10:39:27.009Z`).

**CORS** is off except for origins Spoonity allow-lists. The SDK API is meant
for native apps and servers, not for arbitrary browser pages.

## Integrating: which path to use

- **A mobile app** uses an SDK with a **client key**. The SDK downloads
  definitions, keeps them fresh over a stream, answers `treatment("flag")`
  synchronously from memory, and reports impressions and events in batches.
  You do not call the SDK API by hand.
- **A backend that wants the same answers without embedding the engine**
  calls [`POST /sdk/v1/evaluate`](#post-sdkv1evaluate) with a **server key**,
  one context or up to 100 per call.
- **A backend that evaluates on every request at volume** can instead poll
  [`GET /sdk/v1/definitions`](#get-sdkv1definitions) and fetch segment lists
  with [`GET /sdk/v1/segments/{name}`](#get-sdkv1segmentsname), then evaluate
  with the `@spoonity/flags-engine` package, which is the same code the SDKs
  and the service run.

### SDKs

| Platform | Package | Install |
|---|---|---|
| iOS (Swift 6, iOS 16+) | `SpoonityFlags` | SwiftPM: `.package(url: "https://github.com/Spoonity/spoonity-flags.git", from: "0.1.0")`, product `SpoonityFlags` |
| Android (Kotlin, JVM) | `com.spoonity:flags` | Gradle, from GitHub Packages Maven (`https://maven.pkg.github.com/Spoonity/spoonity-flags`) |
| React Native / Expo | `@spoonity/flags-react-native` | npm, from GitHub Packages (`@spoonity:registry=https://npm.pkg.github.com`); peer dependency `@react-native-async-storage/async-storage` |

The packages are published from the `Spoonity/spoonity-flags` repository and
need a GitHub token with `read:packages` for an account that can see it. Ask
Spoonity for access if your team builds its own app.

All three share one shape. React Native, for example:

```tsx
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
  asyncStorageAdapter,
  createFlagsClient,
  FlagsProvider,
  useTreatment,
} from "@spoonity/flags-react-native";

export const flags = createFlagsClient({
  clientKey: "sdk_c_REPLACE_WITH_YOUR_CLIENT_KEY",   // one per environment
  baseUrl: "https://flags.spoonity.com",
  storage: asyncStorageAdapter(AsyncStorage),
  bootstrap: { wallet: "on" },                        // used until a definition arrives
  defaultAttributes: { vendorId: "1047166", market: "CA", appVersion: "4.2.1" },
});

flags.setContext("member:10442817");                  // re-key on sign-in and sign-out

// App root
<FlagsProvider client={flags}><RootNavigator /></FlagsProvider>

// Any component
function Checkout() {
  return useTreatment("checkout-redesign") === "on" ? <NewCheckout /> : <OldCheckout />;
}

flags.track("order.completed", 42.5, { channel: "app" });
```

The SDKs fill in `platform`, `osVersion`, `locale` and `country` themselves.
`treatment` never throws and never blocks; before the first sync it answers
from `bootstrap`, and with nothing to answer from it returns `control`. The
client key is environment-scoped, so a staging build must ship the staging
key.

## The flag definition

This is the document the SDK API serves and the admin API stores (contract
type `FlagDefinition`):

```json
{
  "flag": "checkout-redesign",
  "version": 1,
  "changeNumber": 1790764767224,
  "enabled": true,
  "killed": false,
  "treatments": [
    { "name": "on", "config": "{\"variant\":\"v2\",\"steps\":2}" },
    { "name": "off" }
  ],
  "defaultTreatment": "off",
  "trafficAllocation": 100,
  "trafficAllocationSeed": 1534791311,
  "seed": 1040856884,
  "rules": [
    {
      "id": "r-beta",
      "label": "Beta testers always on",
      "conditions": [{ "matcher": "in_segment", "attribute": "key", "value": "beta-testers" }],
      "distribution": [{ "treatment": "on", "percent": 100 }]
    },
    {
      "id": "r-ca-v4",
      "label": "20% of Canadian users on 4.2+",
      "conditions": [
        { "matcher": "equals", "attribute": "country", "value": "CA" },
        { "matcher": "semver_gte", "attribute": "appVersion", "value": "4.2.0" }
      ],
      "distribution": [
        { "treatment": "on", "percent": 20 },
        { "treatment": "off", "percent": 80 }
      ]
    }
  ],
  "defaultRule": [{ "treatment": "off", "percent": 100 }]
}
```

| Field | Type | Notes |
|---|---|---|
| `flag` | string | Flag key, `^[a-z0-9][a-z0-9_-]{0,63}$` |
| `version` | integer | Starts at 1, bumped by every write |
| `changeNumber` | integer | The environment change number of the last write |
| `enabled` | boolean | `false` answers `defaultTreatment` with reason `disabled` |
| `killed` | boolean | `true` answers `defaultTreatment` with reason `killed` |
| `treatments` | array | 1 to 50 of `{ name, config? }`. `name` matches `^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,49}$` and may not be `control`. `config` is a **string** holding JSON (up to 32 KB); the SDK hands it back raw and your app parses it. |
| `defaultTreatment` | string | Must be a declared treatment |
| `trafficAllocation` | integer | 0 to 100. The share of contexts that reach the rules at all; the rest get `defaultTreatment` |
| `trafficAllocationSeed`, `seed` | integer | Bucketing seeds. Generated on first write and kept stable; changing one reshuffles every assignment |
| `rules` | array | Up to 100 of `{ id, label?, conditions (1 to 20), distribution }` |
| `defaultRule` | array | The distribution for contexts that match no rule |

A **distribution** is 1 to 50 `{ treatment, percent }` entries with integer
percents that sum to exactly 100, each naming a declared treatment once.

### Matchers

Every condition is `{ "matcher", "attribute", … }`. All conditions in a rule
must match.

| Matcher | Operand | Matches when the attribute… |
|---|---|---|
| `in_segment`, `not_in_segment` | `value`: segment name (`attribute` is always `key`) | is, or is not, in that segment |
| `equals`, `not_equals` | `value`: string, number or boolean | equals, or does not equal, the value |
| `in_list`, `not_in_list` | `values`: 1 to 5000 scalars | is, or is not, one of the values |
| `starts_with`, `ends_with`, `contains` | `value`: string, 1 to 500 characters | string test (there are no regular-expression matchers) |
| `gt`, `gte`, `lt`, `lte` | `value`: number | numeric comparison |
| `between` | `min`, `max`: numbers, `min` ≤ `max` | is within the range, inclusive |
| `semver_eq`, `semver_gte`, `semver_lte` | `value`: version such as `4.2.0`, `4.2`, `4.2.0-beta.1` | version comparison |
| `semver_between` | `min`, `max`: versions | is within the version range |
| `is_set` | none | is present |
| `is_true`, `is_false` | none | is boolean `true`, or `false` |
| `list_contains_any`, `list_contains_all` | `values`: 1 to 5000 strings | (a string list) contains any, or all, of the values |

Attribute values an app may pass are strings, finite numbers, booleans or
lists of strings. Attribute names are 1 to 100 characters.

### Evaluation order

The first step that produces a result wins:

1. No definition in this environment: `control`, reason `not_found` (no
   `changeNumber`, so no impression is recorded).
2. `enabled: false`: `defaultTreatment`, reason `disabled`.
3. `killed: true`: `defaultTreatment`, reason `killed`.
4. The context's bucket is outside `trafficAllocation`: `defaultTreatment`,
   reason `not_in_traffic_allocation`.
5. The first rule whose conditions all match: a treatment from its
   distribution, reason `rule`, with `ruleId`.
6. Otherwise: a treatment from `defaultRule`, reason `default_rule`.

Bucketing is a MurmurHash3 of the seed and the context key, so the same key
always lands in the same bucket for the same seed, on every SDK and on the
server.

## SDK API

All routes require `Authorization: Bearer <sdk key>` and resolve the
environment from the key.

### GET /sdk/v1/definitions

Every non-archived flag definition in the key's environment, or only what
changed since the change number you last saw.

**Auth:** client or server key. Reads bucket.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `since` | integer | Last `till` you received. Default `0`, meaning the whole environment |

- `since` equal to or above the current change number: `flags` and `removed`
  are empty.
- `since=0`: every non-archived definition, and `removed` is empty.
- Otherwise the service may return only the definitions that changed, and
  lists in `removed` the flags archived or deleted since then. Drop those
  from your cache.
- `segmentsUsed` names every segment referenced by any live rule in the
  environment (not only those in this response), so a client can tell
  whether it needs memberships at all.

**Request example:**

```bash
curl https://flags.spoonity.com/sdk/v1/definitions \
  -H "Authorization: Bearer sdk_c_REPLACE_WITH_YOUR_CLIENT_KEY"
```

**Response example** (`200`, headers trimmed):

```http
HTTP/1.1 200 OK
RateLimit-Limit: 600
RateLimit-Remaining: 599
RateLimit-Reset: 1
ETag: "JNtH0PZGqM-iIb9hAEqEf31xAC9"
Cache-Control: no-cache, must-revalidate
Content-Type: application/json; charset=utf-8
```

```json
{
  "since": 0,
  "till": 1790764642570,
  "flags": [
    {
      "flag": "checkout-redesign",
      "seed": 940250892,
      "rules": [
        {
          "id": "r-beta",
          "label": "Beta testers always on",
          "conditions": [{ "value": "beta-testers", "matcher": "in_segment", "attribute": "key" }],
          "distribution": [{ "percent": 100, "treatment": "on" }]
        },
        {
          "id": "r-ca-v4",
          "label": "20% of Canadian users on 4.2+",
          "conditions": [
            { "value": "CA", "matcher": "equals", "attribute": "country" },
            { "value": "4.2.0", "matcher": "semver_gte", "attribute": "appVersion" }
          ],
          "distribution": [
            { "percent": 20, "treatment": "on" },
            { "percent": 80, "treatment": "off" }
          ]
        }
      ],
      "killed": false,
      "enabled": true,
      "version": 1,
      "treatments": [
        { "name": "on", "config": "{\"variant\":\"v2\",\"steps\":2}" },
        { "name": "off" }
      ],
      "defaultRule": [{ "percent": 100, "treatment": "off" }],
      "changeNumber": 1790764642565,
      "defaultTreatment": "off",
      "trafficAllocation": 100,
      "trafficAllocationSeed": 1738959693
    },
    {
      "flag": "loyalty-banner",
      "seed": 1526300156,
      "rules": [],
      "killed": false,
      "enabled": true,
      "version": 1,
      "treatments": [{ "name": "on" }, { "name": "off" }],
      "defaultRule": [
        { "percent": 50, "treatment": "on" },
        { "percent": 50, "treatment": "off" }
      ],
      "changeNumber": 1790764642570,
      "defaultTreatment": "off",
      "trafficAllocation": 50,
      "trafficAllocationSeed": 184876017
    }
  ],
  "segmentsUsed": ["beta-testers"],
  "removed": []
}
```

Key order inside a definition is not significant. A repeat with
`If-None-Match: "JNtH0PZGqM-iIb9hAEqEf31xAC9"` answers `304` with no body.
Asked with `?since=1790764642570`:

```json
{ "since": 1790764642570, "till": 1790764642570, "flags": [], "segmentsUsed": ["beta-testers"], "removed": [] }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | `since` is not a non-negative integer |
| 401 | unauthorized | `"missing SDK key"`, `"unknown SDK key"` or `"SDK key was revoked"` |
| 429 | rate_limited | Reads bucket exhausted |

### GET /sdk/v1/memberships

The segments one context key belongs to. A client key only ever learns
membership for the key it asks about; segment contents are never exposed to
client keys.

**Auth:** client or server key. Reads bucket. `ETag` supported.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `key` | string | Required. The context key, 1 to 250 characters, URL-encoded |

**Request example:**

```bash
curl "https://flags.spoonity.com/sdk/v1/memberships?key=member:10442817" \
  -H "Authorization: Bearer sdk_c_REPLACE_WITH_YOUR_CLIENT_KEY"
```

**Response example:**

```json
{ "key": "member:10442817", "segments": ["beta-testers"], "till": 1790764767288 }
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | `key` missing or longer than 250 characters |
| 401 | unauthorized | Missing, unknown or revoked key |

### GET /sdk/v1/segments/{name}

A segment's full membership list, or the diff since a change number, for a
backend that evaluates locally.

**Auth:** server key only. Reads bucket. `ETag` supported.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `since` | integer | Default `0`: the whole list in `added`. Later values return the diff |

**Request example:**

```bash
curl https://flags.spoonity.com/sdk/v1/segments/beta-testers \
  -H "Authorization: Bearer sdk_s_REPLACE_WITH_YOUR_SERVER_KEY"
```

**Response example:**

```json
{
  "name": "beta-testers",
  "since": 0,
  "till": 1790764642570,
  "added": ["device:simulator", "member:beta"],
  "removed": []
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | `"this route requires a server SDK key"` |
| 404 | not_found | `no segment "nope" in this environment` |

### GET /sdk/v1/flags/{flag}

One flag's served definition, so a backend can check that a flag exists and
see its treatments without downloading the whole environment.

**Auth:** server key only. Reads bucket. `ETag` supported.

**Request example:**

```bash
curl https://flags.spoonity.com/sdk/v1/flags/loyalty-banner \
  -H "Authorization: Bearer sdk_s_REPLACE_WITH_YOUR_SERVER_KEY"
```

**Response example:**

```json
{
  "till": 1790764642570,
  "definition": {
    "flag": "loyalty-banner",
    "seed": 1526300156,
    "rules": [],
    "killed": false,
    "enabled": true,
    "version": 1,
    "treatments": [{ "name": "on" }, { "name": "off" }],
    "defaultRule": [
      { "percent": 50, "treatment": "on" },
      { "percent": 50, "treatment": "off" }
    ],
    "changeNumber": 1790764642570,
    "defaultTreatment": "off",
    "trafficAllocation": 50,
    "trafficAllocationSeed": 184876017
  }
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | Client key |
| 404 | not_found | Unknown flag, archived, or no definition in this environment |

### POST /sdk/v1/evaluate

Server-side evaluation, for backends that do not embed the engine. Uses the
same engine as the SDKs, so it never disagrees with a device.

**Auth:** server key only. Evaluate bucket, one token per context. A client
key is charged to reads and then refused with `403`.

**Request body, single form:**

| Field | Type | Required | Description |
|---|---|---|---|
| `key` | string | Yes | Context key, 1 to 250 characters |
| `attributes` | object | | Attribute name to string, number, boolean or string list |
| `flags` | string[] | | Up to 500 flag keys. Omitted: every flag in the environment |
| `dryRun` | boolean | | `true` records no impressions. Default `false` |

**Request body, batch form:** `{ "contexts": [{ "key", "attributes"? }, …],
"flags"?, "dryRun"? }` with 1 to 100 contexts, all evaluated against the same
snapshot. The service tells the forms apart by the presence of `contexts`;
sending both `key` and `contexts` is a `400`.

**`dryRun` matters.** Without it the service records one impression per
evaluated flag that has a definition, per context, exactly as if an SDK had
shown the treatment. Leave it off only when you are about to act on the
answer; use `dryRun: true` to preview, test or health-check, or the
impressions summary will over-count exposure.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/sdk/v1/evaluate \
  -H "Authorization: Bearer sdk_s_REPLACE_WITH_YOUR_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "member:01H4Z0K3S6TZ0Q6R8N1M2P3Q4R",
    "attributes": { "country": "CA", "appVersion": "4.2.1" },
    "flags": ["checkout-redesign", "loyalty-banner", "legacy-banner"],
    "dryRun": true
  }'
```

**Response example:**

```json
{
  "key": "member:01H4Z0K3S6TZ0Q6R8N1M2P3Q4R",
  "till": 1790764642570,
  "results": [
    {
      "flag": "checkout-redesign",
      "treatment": "on",
      "reason": "rule",
      "ruleId": "r-ca-v4",
      "config": "{\"variant\":\"v2\",\"steps\":2}",
      "changeNumber": 1790764642565
    },
    { "flag": "loyalty-banner", "treatment": "off", "reason": "default_rule", "changeNumber": 1790764642570 },
    { "flag": "legacy-banner", "treatment": "control", "reason": "not_found" }
  ]
}
```

`reason` is one of `not_found`, `disabled`, `killed`,
`not_in_traffic_allocation`, `rule`, `default_rule`. `ruleId` is present only
for `rule`; `config` only when the chosen treatment declares one.

**Batch request example:**

```bash
curl -X POST https://flags.spoonity.com/sdk/v1/evaluate \
  -H "Authorization: Bearer sdk_s_REPLACE_WITH_YOUR_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contexts": [
      { "key": "member:beta" },
      { "key": "member:01H4Z0K3S6TZ0Q6R8N1M2P3Q4R", "attributes": { "country": "CA", "appVersion": "4.2.1" } }
    ],
    "flags": ["checkout-redesign"],
    "dryRun": true
  }'
```

**Batch response example** (one entry per context, in request order):

```json
{
  "till": 1790764642570,
  "results": [
    {
      "key": "member:beta",
      "evaluations": [
        {
          "flag": "checkout-redesign",
          "treatment": "on",
          "reason": "rule",
          "ruleId": "r-beta",
          "config": "{\"variant\":\"v2\",\"steps\":2}",
          "changeNumber": 1790764642565
        }
      ]
    },
    {
      "key": "member:01H4Z0K3S6TZ0Q6R8N1M2P3Q4R",
      "evaluations": [
        {
          "flag": "checkout-redesign",
          "treatment": "on",
          "reason": "rule",
          "ruleId": "r-ca-v4",
          "config": "{\"variant\":\"v2\",\"steps\":2}",
          "changeNumber": 1790764642565
        }
      ]
    }
  ]
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | Validation failed, for example `{"path":"/key","message":"String must contain at least 1 character(s)"}` or `Unrecognized key(s) in object: 'key'` when both forms are mixed |
| 403 | forbidden | Client key: `"this route requires a server SDK key"` |
| 413 | payload_too_large | More than 100 contexts, or a body over 1 MiB |
| 429 | rate_limited | Evaluate bucket exhausted |

### POST /sdk/v1/impressions

Report which treatment each context was shown. The SDKs do this for you in
batches; call it directly only if you evaluate locally with the engine.

**Auth:** client or server key. Batches bucket.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `impressions` | array | Yes | 1 to 1000 of `{ flag, key, treatment, reason, ruleId?, changeNumber, time, bucketingKey? }`. `changeNumber` is the definition's; `time` is epoch milliseconds |
| `sdk` | string | | Up to 60 characters, for example `swift` |
| `sdkVersion` | string | | Up to 40 characters |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/sdk/v1/impressions \
  -H "Authorization: Bearer sdk_c_REPLACE_WITH_YOUR_CLIENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "impressions": [{
      "flag": "checkout-redesign",
      "key": "member:beta",
      "treatment": "on",
      "reason": "rule",
      "ruleId": "r-beta",
      "changeNumber": 1790764642565,
      "time": 1790764700000
    }],
    "sdk": "swift",
    "sdkVersion": "0.1.0"
  }'
```

**Response example** (`202`):

```json
{ "accepted": 1, "dropped": 0 }
```

`dropped` counts impressions deduplicated by
`(flag, key, treatment, changeNumber, hour)`, or discarded as older than 48
hours or more than 5 minutes in the future. The same batch sent twice answers
`{ "accepted": 0, "dropped": 1 }`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | Any entry invalid rejects the whole batch |
| 413 | payload_too_large | Over 1000 entries or 1 MiB |
| 429 | rate_limited | Batches bucket exhausted |

### POST /sdk/v1/events

Report conversion events for measuring a rollout. Events are never
deduplicated: two identical calls are two events.

**Auth:** client or server key. Batches bucket.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `events` | array | Yes | 1 to 1000 of `{ key, eventType, value?, properties?, time }` |
| `events[].eventType` | string | Yes | `^[a-zA-Z0-9][-_.:a-zA-Z0-9]{0,79}$`, for example `order.completed` |
| `events[].value` | number | | Summed in the events summary |
| `events[].properties` | object | | Up to 30; values are strings (up to 500 characters), numbers, booleans or `null` |
| `events[].time` | integer | Yes | Epoch milliseconds |
| `sdk`, `sdkVersion` | string | | As for impressions |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/sdk/v1/events \
  -H "Authorization: Bearer sdk_c_REPLACE_WITH_YOUR_CLIENT_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [{
      "key": "member:beta",
      "eventType": "order.completed",
      "value": 42.5,
      "properties": { "channel": "app", "loyalty": true },
      "time": 1790764700000
    }],
    "sdk": "kotlin",
    "sdkVersion": "0.1.0"
  }'
```

**Response example** (`202`):

```json
{ "accepted": 1, "dropped": 0 }
```

`dropped` counts events outside the same clock window as impressions.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | Any entry invalid rejects the whole batch, for example `{"path":"/events/0/eventType","message":"Invalid"}` |
| 413 | payload_too_large | Over 1000 entries or 1 MiB |

### GET /sdk/v1/stream

A server-sent event stream that says **when** to refetch. It carries
notifications only, never definitions.

**Auth:** client or server key. Reads bucket, plus at most 5 concurrent
streams per key.

**Request example:**

```bash
curl -N https://flags.spoonity.com/sdk/v1/stream \
  -H "Authorization: Bearer sdk_c_REPLACE_WITH_YOUR_CLIENT_KEY"
```

**Response example** (`200`, `Content-Type: text/event-stream`; a segment
edit and a kill arriving while connected):

```
retry: 5000

event: segments_changed
data: {"till":1790764782730,"segment":"beta-testers"}

event: flags_changed
data: {"till":1790764782750}

: keep-alive
event: heartbeat
data: {"time":1790764812750}
```

- On `flags_changed`, refetch `definitions` with your current `since`.
- On `segments_changed`, refetch `memberships` (client) or `segments/{name}`
  (server). `segment` is present when one segment changed.
- A `heartbeat` arrives every 30 seconds. If nothing arrives for 90 seconds,
  reconnect.
- Reconnect with exponential backoff (1 s to 60 s, full jitter); after three
  failures fall back to polling `definitions` every 60 seconds while retrying
  the stream. `Last-Event-ID` is not used: `since` is the resume token.
- A `401` or `403` closes the stream before any frame. Do not reconnect.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Missing, unknown or revoked key |
| 429 | rate_limited | `"at most 5 concurrent streams per SDK key"` |

## Console sign-in API

`/auth/v1` signs a person in with their Spoonity platform account and returns
the session token the admin API takes. Bodies are snake_case and match the
CMS's `/api/v1/auth/*` routes, so a client written for one works against the
other. Responses are `no-store`.

### POST /auth/v1/login

Sign in with email and password.

**Auth:** none. 10 requests per minute per IP, shared with `select-vendor`.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `email` | string | Yes | Spoonity platform account email |
| `password` | string | Yes | |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/auth/v1/login \
  -H "Content-Type: application/json" \
  -d '{ "email": "owner@brand.example", "password": "REPLACE_WITH_PASSWORD" }'
```

**Response example** (an account linked to one vendor; token shortened):

```json
{
  "success": true,
  "requires_vendor_selection": false,
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6InNlc3Npb24i…",
  "expires_at": "2026-10-01T10:38:55.000Z",
  "vendor": { "id": "1047166", "name": "Breakfast Bonanza" },
  "user": { "id": "9001", "email": "owner@brand.example", "name": "owner@brand.example", "role": "admin" },
  "allowed_vendors": [{ "id": "1047166", "name": "Breakfast Bonanza", "role": "admin" }],
  "identities": [{ "id": "1047166", "name": "Breakfast Bonanza", "role": "admin" }]
}
```

An account linked to several vendors gets a 15-minute selection token
instead, to exchange at `select-vendor`:

```json
{
  "success": true,
  "requires_vendor_selection": true,
  "selection_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6InNlbGVjdCIs…",
  "identities": [
    { "id": "1047166", "name": "Breakfast Bonanza", "role": "editor" },
    { "id": "2000001", "name": "Second Brand", "role": "viewer" }
  ]
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | `"Invalid email or password"` |
| 403 | forbidden | Account linked to no vendor, or vendor list unavailable |
| 429 | rate_limited | Over 10 attempts per minute |
| 500 | internal_error | `"Authentication service unavailable"` |

### POST /auth/v1/select-vendor

Exchange a selection token for a session at one vendor.

**Auth:** none (the selection token is in the body). Same 10 per minute bucket.

**Request body:** `{ "selection_token": "…", "vendor_id": "1047166" }`
(`vendor_id` may be a string or an integer).

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/auth/v1/select-vendor \
  -H "Content-Type: application/json" \
  -d '{ "selection_token": "REPLACE_WITH_SELECTION_TOKEN", "vendor_id": "1047166" }'
```

**Response example:** an `AuthSession`, the same as a one-vendor login
without `success`, `requires_vendor_selection` and `identities` (token
shortened):

```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6InNlc3Npb24i…",
  "expires_at": "2026-10-01T10:46:10.000Z",
  "vendor": { "id": "1047166", "name": "Breakfast Bonanza" },
  "user": { "id": "9002", "email": "multi@brand.example", "name": "multi@brand.example", "role": "editor" },
  "allowed_vendors": [
    { "id": "1047166", "name": "Breakfast Bonanza", "role": "editor" },
    { "id": "2000001", "name": "Second Brand", "role": "viewer" }
  ]
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Selection token expired or invalid |
| 403 | forbidden | `"You do not have access to this vendor."`: `vendor_id` is not one of the account's vendors |

### POST /auth/v1/switch-vendor

Get a session for another vendor the account already belongs to.

**Auth:** session token.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/auth/v1/switch-vendor \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "vendor_id": "2000001" }'
```

**Response example:** an `AuthSession`, as for `select-vendor`, for the new
vendor. The role is the one at that vendor, so the same person can be an
editor at one brand and a viewer at another:

```json
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6InNlc3Npb24i…",
  "expires_at": "2026-10-01T10:46:10.000Z",
  "vendor": { "id": "2000001", "name": "Second Brand" },
  "user": { "id": "9002", "email": "multi@brand.example", "name": "multi@brand.example", "role": "viewer" },
  "allowed_vendors": [
    { "id": "1047166", "name": "Breakfast Bonanza", "role": "editor" },
    { "id": "2000001", "name": "Second Brand", "role": "viewer" }
  ]
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | Missing or expired session |
| 403 | forbidden | `"You do not have access to this vendor. Please log in again."` |

### GET /auth/v1/me

The signed-in person and vendor.

**Auth:** session token.

**Request example:**

```bash
curl https://flags.spoonity.com/auth/v1/me \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "user": { "id": "9001", "email": "owner@brand.example", "name": "owner@brand.example", "role": "admin" },
  "vendor": { "id": "1047166", "name": "Breakfast Bonanza" },
  "allowed_vendors": [{ "id": "1047166", "name": "Breakfast Bonanza", "role": "admin" }],
  "expires_at": "2026-10-01T10:39:26.000Z"
}
```

**Errors:** `401 unauthorized` for a missing or expired session.

### POST /auth/v1/logout

Answers `204`. Tokens are stateless, so this only tells the client to drop
its copy; a token stays valid until `expires_at`.

**Auth:** none.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/auth/v1/logout
```

**Response:** `204 No Content`.

## Admin API

Every route requires a session token except `GET /admin/v1/config`. In paths,
`{ws}` is the workspace id or the vendor id, and `{env}` is the environment
id (`env_01…`) or the pair `<vendorId>:<envKey>` (`1047166:production`; the
colon may be sent as `%3A`). The examples use the pair.

A new brand has no workspace: create it with
[`POST /admin/v1/workspaces`](#post-adminv1workspaces), then create
`production` and `staging` environments. Prism's **Turn on Flags** button
does both.

### GET /admin/v1/config

Public console configuration.

**Auth:** none. If an `Authorization` header is sent, `signedIn` reports
whether it verifies and resolves to a role; a bad token never fails this call.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/config
```

**Response example** (production):

```json
{
  "googleClientId": "",
  "authMode": "identity",
  "version": "spoonity-flags-00017-d8v",
  "allowedDomains": ["spoonity.com"],
  "signedIn": false
}
```

`googleClientId` is deprecated and always `""`.

**Errors:** none in normal operation.

### GET /admin/v1/me

Who the token is and what it may do.

**Auth:** any role.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/me \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "subject": "9001",
  "email": "owner@brand.example",
  "role": "admin",
  "delegated": false,
  "vendorId": "1047166",
  "via": "identity",
  "name": "owner@brand.example",
  "vendorName": "Breakfast Bonanza",
  "allowedVendors": ["1047166"],
  "vendors": [{ "id": "1047166", "name": "Breakfast Bonanza", "role": "admin" }]
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 401 | unauthorized | `"missing bearer token"`, or an invalid or expired one |

### GET /admin/v1/workspaces

The workspaces visible to the caller. A session sees at most one: its
vendor's, or `items: []` when the brand has not turned Flags on.

**Auth:** viewer.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/workspaces \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "items": [
    {
      "id": "ws_01M3RYBNS1RB32K8J13R119Y8X",
      "vendorId": "1047166",
      "name": "Breakfast Bonanza",
      "archived": false,
      "createdAt": "2026-09-30T10:39:27.009Z",
      "updatedAt": "2026-09-30T10:39:27.009Z"
    }
  ],
  "nextCursor": null
}
```

**Errors:** `401 unauthorized`.

### POST /admin/v1/workspaces

Turn Flags on for the signed-in vendor.

**Auth:** editor or admin on a session, and only for the session's own
vendor.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `vendorId` | string | Yes | Must equal the session's vendor |
| `name` | string | Yes | 1 to 120 characters |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/workspaces \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "vendorId": "1047166", "name": "Breakfast Bonanza" }'
```

**Response example** (`201`):

```json
{
  "id": "ws_01M3RYBNS1RB32K8J13R119Y8X",
  "vendorId": "1047166",
  "name": "Breakfast Bonanza",
  "archived": false,
  "createdAt": "2026-09-30T10:39:27.009Z",
  "updatedAt": "2026-09-30T10:39:27.009Z"
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | `"you may only create the workspace for the vendor you are signed in to"`, or viewer role |
| 409 | conflict | `vendor "1047166" already has a workspace` (safe to treat as success on a retry) |

### GET /admin/v1/workspaces/{ws}

One workspace.

**Auth:** viewer.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/workspaces/1047166 \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** a `Workspace`, as in the list above.

**Errors:** `404 not_found` for an unknown workspace or another vendor's.

### PATCH /admin/v1/workspaces/{ws}

Rename or archive the workspace.

**Auth:** admin.

**Request body:** `{ "name"?: string, "archived"?: boolean }`.

**Request example:**

```bash
curl -X PATCH https://flags.spoonity.com/admin/v1/workspaces/1047166 \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Breakfast Bonanza (all markets)" }'
```

**Response example:**

```json
{
  "id": "ws_01M3RYBNS1RB32K8J13R119Y8X",
  "vendorId": "1047166",
  "name": "Breakfast Bonanza (all markets)",
  "archived": false,
  "createdAt": "2026-09-30T10:39:27.009Z",
  "updatedAt": "2026-09-30T10:46:11.216Z"
}
```

**Errors:** `400 invalid_request`, `403 forbidden` (below admin), `404 not_found`.

### GET /admin/v1/workspaces/{ws}/environments

The workspace's environments, with each one's current change number.

**Auth:** viewer. Paginated.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/workspaces/1047166/environments \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "items": [
    {
      "id": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
      "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
      "key": "production",
      "name": "Production",
      "production": true,
      "changeNumber": 1790764767288,
      "createdAt": "2026-09-30T10:39:27.057Z",
      "updatedAt": "2026-09-30T10:39:27.289Z"
    },
    {
      "id": "env_01M3RYBNV4N8ZMPHPZ1RN49T6J",
      "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
      "key": "staging",
      "name": "Staging",
      "production": false,
      "changeNumber": 0,
      "createdAt": "2026-09-30T10:39:27.076Z",
      "updatedAt": "2026-09-30T10:39:27.076Z"
    }
  ],
  "nextCursor": null
}
```

**Errors:** `404 not_found`.

### POST /admin/v1/workspaces/{ws}/environments

Create an environment. There is no update or delete.

**Auth:** admin.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `key` | string | Yes | `^[a-z0-9][a-z0-9_-]{0,63}$`, for example `production` |
| `name` | string | Yes | 1 to 120 characters |
| `production` | boolean | | Default `false` |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/workspaces/1047166/environments \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "key": "production", "name": "Production", "production": true }'
```

**Response example** (`201`; a new environment starts at change number 0):

```json
{
  "id": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
  "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
  "key": "production",
  "name": "Production",
  "production": true,
  "changeNumber": 0,
  "createdAt": "2026-09-30T10:39:27.057Z",
  "updatedAt": "2026-09-30T10:39:27.057Z"
}
```

**Errors:** `403 forbidden` (below admin), `409 conflict` (key already exists).

### GET /admin/v1/environments/{env}

One environment.

**Auth:** viewer.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/environments/1047166:production \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** an `Environment`, as above.

**Errors:** `404 not_found`.

### GET /admin/v1/environments/{env}/keys

The environment's SDK keys. Never includes a secret.

**Auth:** admin. Paginated.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/environments/1047166:production/keys \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "items": [
    {
      "id": "key_01M3RY7W7VWDCDQT5X4TKGJQZZ",
      "environmentId": "env_01M3RY7W7SC8PEGS4QCC2SFFPB",
      "kind": "client",
      "prefix": "sdk_c_fma02m",
      "name": "demo client",
      "lastUsedAt": "2026-09-30T10:37:38.671Z",
      "revokedAt": null,
      "createdAt": "2026-09-30T10:37:22.555Z"
    },
    {
      "id": "key_01M3RY7W7WK51BY3TXJ6GGPETR",
      "environmentId": "env_01M3RY7W7SC8PEGS4QCC2SFFPB",
      "kind": "server",
      "prefix": "sdk_s_d96z8s",
      "name": "demo server",
      "lastUsedAt": "2026-09-30T10:37:52.556Z",
      "revokedAt": null,
      "createdAt": "2026-09-30T10:37:22.556Z"
    }
  ],
  "nextCursor": null
}
```

`prefix` is the first 12 characters of the key, for recognising it.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 403 | forbidden | `role "editor" may not perform this action (need admin or higher)` |
| 404 | not_found | Unknown environment |

### POST /admin/v1/environments/{env}/keys

Create an SDK key. **The only response that ever carries the secret.** Store
it straight away; it cannot be read again.

**Auth:** admin.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `kind` | string | Yes | `client` or `server` |
| `name` | string | Yes | 1 to 120 characters, for your own reference |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/environments/1047166:production/keys \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "kind": "server", "name": "Order service" }'
```

**Response example** (`201`; secret replaced with a sample of the same shape):

```json
{
  "id": "key_01M3RYBP2VCW7ZEVYPMCH4KSV2",
  "environmentId": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
  "kind": "server",
  "prefix": "sdk_s_01h4z0",
  "name": "Order service",
  "lastUsedAt": null,
  "revokedAt": null,
  "createdAt": "2026-09-30T10:39:27.324Z",
  "secret": "sdk_s_01h4z0k3s6tz0q6r8n1m2p3q4r"
}
```

**Errors:** `400 invalid_request`, `403 forbidden` (below admin), `404 not_found`.

### DELETE /admin/v1/environments/{env}/keys/{id}

Revoke a key. It stops working immediately and stays listed with
`revokedAt` set.

**Auth:** admin.

**Request example:**

```bash
curl -X DELETE https://flags.spoonity.com/admin/v1/environments/1047166:production/keys/key_01M3RYBP2VCW7ZEVYPMCH4KSV2 \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response:** `204 No Content`.

To rotate a client key without breaking installed apps, create the new key,
ship it (or push it through remote config), wait for adoption, then revoke
the old one.

**Errors:** `403 forbidden`, `404 not_found` (`no SDK key "…"`).

### GET /admin/v1/workspaces/{ws}/flags

The brand's flags (metadata only; no per-environment status).

**Auth:** viewer. Paginated.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `q` | string | Search |
| `tag` | string | Only flags with this tag |
| `archived` | boolean | `false` for live flags only, `true` for archived only; omit for both |
| `cursor`, `limit` | | Pagination |

**Request example:**

```bash
curl "https://flags.spoonity.com/admin/v1/workspaces/1047166/flags?archived=false&limit=1" \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "items": [
    {
      "key": "checkout-redesign",
      "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
      "name": "Checkout redesign",
      "description": "Two-step checkout",
      "tags": ["checkout"],
      "owner": "mobile@breakfastbonanza.example",
      "archived": false,
      "createdAt": "2026-09-30T10:39:27.111Z",
      "updatedAt": "2026-09-30T10:39:27.111Z"
    }
  ],
  "nextCursor": "Y2hlY2tvdXQtcmVkZXNpZ24"
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | `` `cursor` is not a cursor this service issued `` |
| 404 | not_found | Unknown workspace, or another vendor's (`no workspace "2000001"`) |

### POST /admin/v1/workspaces/{ws}/flags

Create a flag. It has no behaviour until you save a definition in an
environment.

**Auth:** editor.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `key` | string | Yes | `^[a-z0-9][a-z0-9_-]{0,63}$`. What the app passes to `treatment(…)` |
| `name` | string | Yes | 1 to 160 characters |
| `description` | string | | Up to 2000 characters |
| `tags` | string[] | | Up to 20, each 1 to 40 characters |
| `owner` | string | | Free-form owner label (email or team) |

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/workspaces/1047166/flags \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "checkout-redesign",
    "name": "Checkout redesign",
    "description": "Two-step checkout",
    "tags": ["checkout"],
    "owner": "mobile@breakfastbonanza.example"
  }'
```

**Response example** (`201`):

```json
{
  "key": "checkout-redesign",
  "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
  "name": "Checkout redesign",
  "description": "Two-step checkout",
  "tags": ["checkout"],
  "owner": "mobile@breakfastbonanza.example",
  "archived": false,
  "createdAt": "2026-09-30T10:39:27.111Z",
  "updatedAt": "2026-09-30T10:39:27.111Z"
}
```

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | `{"path":"/key","message":"flag key must match ^[a-z0-9][a-z0-9_-]{0,63}$"}` |
| 403 | forbidden | Viewer |
| 409 | conflict | `flag "checkout-redesign" already exists` |

### GET /admin/v1/workspaces/{ws}/flags/{flag}

One flag's metadata.

**Auth:** viewer.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/workspaces/1047166/flags/checkout-redesign \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** a `Flag`, as above.

**Errors:** `404 not_found` (`no flag "…"`).

### PATCH /admin/v1/workspaces/{ws}/flags/{flag}

Update a flag's metadata, or archive it. Archiving removes the flag from
every environment at once: SDKs see it in `removed` (for example
`{"since":1,"till":1790765171243,"flags":[],"segmentsUsed":[],"removed":["f1"]}`)
and fall back to `control`, and its definition routes answer `404`. Setting
`archived: false` brings the stored definitions back unchanged. The change
log records an archive as `flag.archive` and anything else as `flag.update`.

**Auth:** editor.

**Request body:** any of `name`, `description`, `tags`, `owner`, `archived`.

**Request example:**

```bash
curl -X PATCH https://flags.spoonity.com/admin/v1/workspaces/1047166/flags/checkout-redesign \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "tags": ["checkout", "q4"] }'
```

**Response example:**

```json
{
  "key": "checkout-redesign",
  "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
  "name": "Checkout redesign",
  "description": "Two-step checkout",
  "tags": ["checkout", "q4"],
  "owner": "mobile@breakfastbonanza.example",
  "archived": false,
  "createdAt": "2026-09-30T10:39:27.111Z",
  "updatedAt": "2026-09-30T10:39:41.435Z"
}
```

**Errors:** `400 invalid_request`, `403 forbidden`, `404 not_found`.

### GET /admin/v1/environments/{env}/flags/{flag}/definition

A flag's definition in one environment, with who saved it last.

**Auth:** viewer.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/environments/1047166:production/flags/checkout-redesign/definition \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example** (`FlagDefinitionDetail`; the definition is shown in
full [above](#the-flag-definition)):

```json
{
  "definition": { "flag": "checkout-redesign", "version": 1, "changeNumber": 1790764767224, "…": "…" },
  "updatedAt": "2026-09-30T10:39:27.224Z",
  "updatedBy": "owner@brand.example",
  "comment": "first rollout"
}
```

**Errors:** `404 not_found` (`no definition for "…" in this environment`).

### PUT /admin/v1/environments/{env}/flags/{flag}/definition

Create or replace a flag's definition in one environment. Optimistic
concurrency: send the `version` you last read as `expectedVersion`, or `0` to
create.

**Auth:** editor.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `expectedVersion` | integer | Yes | `0` to create; otherwise the current `version` |
| `enabled` | boolean | Yes | |
| `killed` | boolean | | Defaults to the stored value, so an edit never un-kills a flag by accident |
| `treatments` | array | Yes | See [the flag definition](#the-flag-definition) |
| `defaultTreatment` | string | Yes | A declared treatment |
| `trafficAllocation` | integer | | 0 to 100, default `100` |
| `rules` | array | | Default `[]` |
| `defaultRule` | array | Yes | Distribution summing to 100 |
| `seed`, `trafficAllocationSeed` | integer | | Omit to keep the stored seeds. Sending a new value reshuffles every assignment |
| `comment` | string | | Up to 500 characters; recorded in the change log |

**Request example:**

```bash
curl -X PUT https://flags.spoonity.com/admin/v1/environments/1047166:production/flags/checkout-redesign/definition \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "expectedVersion": 0,
    "enabled": true,
    "treatments": [
      { "name": "on", "config": "{\"variant\":\"v2\",\"steps\":2}" },
      { "name": "off" }
    ],
    "defaultTreatment": "off",
    "trafficAllocation": 100,
    "rules": [
      {
        "id": "r-beta",
        "label": "Beta testers always on",
        "conditions": [{ "matcher": "in_segment", "attribute": "key", "value": "beta-testers" }],
        "distribution": [{ "treatment": "on", "percent": 100 }]
      },
      {
        "id": "r-ca-v4",
        "label": "20% of Canadian users on 4.2+",
        "conditions": [
          { "matcher": "equals", "attribute": "country", "value": "CA" },
          { "matcher": "semver_gte", "attribute": "appVersion", "value": "4.2.0" }
        ],
        "distribution": [{ "treatment": "on", "percent": 20 }, { "treatment": "off", "percent": 80 }]
      }
    ],
    "defaultRule": [{ "treatment": "off", "percent": 100 }],
    "comment": "first rollout"
  }'
```

**Response example:** the saved `FlagDefinitionDetail`, with `version: 1`,
the environment's new `changeNumber`, and the service-generated seeds
(`seed: 1040856884`, `trafficAllocationSeed: 1534791311`). Connected SDKs get
`flags_changed` straight away.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | Validation, one entry per problem (below) |
| 404 | not_found | The flag does not exist in the workspace; create it first |
| 409 | version_conflict | `expectedVersion 0 but the definition is at 1`: re-read, re-apply, retry |

A body with a 60% default rule, a treatment named `control` and an undeclared
default treatment answers:

```json
{
  "type": "https://flags.spoonity.com/errors/invalid_request",
  "title": "Invalid request",
  "status": 400,
  "code": "invalid_request",
  "detail": "request failed validation",
  "instance": "/admin/v1/environments/1047166:production/flags/checkout-redesign/definition",
  "errors": [
    { "path": "/defaultRule", "message": "distribution percents must sum to 100, got 60" },
    { "path": "/treatments/1/name", "message": "\"control\" is reserved and may not be declared as a treatment" },
    { "path": "/defaultTreatment", "message": "defaultTreatment \"off\" is not a declared treatment" }
  ]
}
```

A rejected write spends no change number.

### POST /admin/v1/environments/{env}/flags/{flag}/kill

The kill switch: every context gets `defaultTreatment` with reason `killed`,
from the next sync (seconds, for a connected SDK). Rules are kept.

**Auth:** editor. No body.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/environments/1047166:production/flags/checkout-redesign/kill \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** the `FlagDefinitionDetail` with `"killed": true` and
`version` bumped (here from 1 to 2).

**Errors:** `403 forbidden`, `404 not_found`.

### POST /admin/v1/environments/{env}/flags/{flag}/restore

Undo a kill. The rules apply again.

**Auth:** editor. No body.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/environments/1047166:production/flags/checkout-redesign/restore \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** the `FlagDefinitionDetail` with `"killed": false` and
`version` bumped again.

**Errors:** `403 forbidden`, `404 not_found`.

### GET /admin/v1/environments/{env}/flags/{flag}/definition/history

The change-log entries for one flag in one environment, newest first. Each
carries the full definition before and after.

**Auth:** viewer. Paginated.

**Request example:**

```bash
curl "https://flags.spoonity.com/admin/v1/environments/1047166:production/flags/checkout-redesign/definition/history?limit=1" \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example** (`before` and `after` shortened):

```json
{
  "items": [
    {
      "id": "chg_01M3RYBP1SAQ6KE6CD6XNMKG36",
      "environmentId": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
      "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
      "action": "flag.restore",
      "target": "checkout-redesign",
      "actor": "owner@brand.example",
      "actorRole": "admin",
      "actorKind": "user",
      "via": "identity",
      "vendorId": "1047166",
      "comment": null,
      "before": { "flag": "checkout-redesign", "killed": true, "version": 2, "…": "…" },
      "after": { "flag": "checkout-redesign", "killed": false, "version": 3, "…": "…" },
      "changeNumber": 1790764767288,
      "createdAt": "2026-09-30T10:39:27.289Z"
    }
  ],
  "nextCursor": "Y2hnXzAxTTNSWUJQMVNBUTZLRTZDRDZYTk1LRzM2"
}
```

History entries carry no top-level version: read `before.version` and
`after.version`.

**Errors:** `404 not_found`.

### GET /admin/v1/environments/{env}/segments

The environment's segments.

**Auth:** viewer. Paginated.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/environments/1047166:production/segments \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "items": [
    {
      "name": "beta-testers",
      "environmentId": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
      "description": "Staff and friendly members",
      "keyCount": 4,
      "changeNumber": 1790764767186,
      "createdAt": "2026-09-30T10:39:27.144Z",
      "updatedAt": "2026-09-30T10:39:27.187Z"
    }
  ],
  "nextCursor": null
}
```

**Errors:** `404 not_found`.

### POST /admin/v1/environments/{env}/segments

Create an empty segment.

**Auth:** editor.

**Request body:** `{ "name": "<segment name>", "description"?: string }`.
`name` follows the flag-key pattern.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/environments/1047166:production/segments \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "name": "beta-testers", "description": "Staff and friendly members" }'
```

**Response example** (`201`):

```json
{
  "name": "beta-testers",
  "environmentId": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
  "description": "Staff and friendly members",
  "keyCount": 0,
  "changeNumber": 1790764767143,
  "createdAt": "2026-09-30T10:39:27.144Z",
  "updatedAt": "2026-09-30T10:39:27.144Z"
}
```

**Errors:** `400 invalid_request`, `403 forbidden`, `409 conflict` (`segment "…" already exists`).

### GET /admin/v1/environments/{env}/segments/{name}

One segment.

**Auth:** viewer.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/environments/1047166:production/segments/beta-testers \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** a `Segment`, as above.

**Errors:** `404 not_found` (`no segment "…"`).

### DELETE /admin/v1/environments/{env}/segments/{name}

Delete a segment. Refused while any live definition in the environment still
uses it.

**Auth:** editor.

**Request example:**

```bash
curl -X DELETE https://flags.spoonity.com/admin/v1/environments/1047166:production/segments/beta-testers \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response:** `204 No Content`.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 404 | not_found | Unknown segment |
| 409 | conflict | `segment "beta-testers" is still referenced by checkout-redesign` |

### GET /admin/v1/environments/{env}/segments/{name}/keys

The segment's member keys.

**Auth:** viewer. Paginated.

**Request example:**

```bash
curl https://flags.spoonity.com/admin/v1/environments/1047166:production/segments/beta-testers/keys \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "items": ["member:10442817", "member:10442818", "member:10442819", "member:10442820"],
  "nextCursor": null
}
```

**Errors:** `404 not_found`.

### PATCH /admin/v1/environments/{env}/segments/{name}/keys

Add or remove member keys, or replace the whole list.

**Auth:** editor.

**Request body:**

| Field | Type | Required | Description |
|---|---|---|---|
| `add` | string[] | | Up to 50 000 keys |
| `remove` | string[] | | Up to 50 000 keys |
| `replace` | boolean | | `true` makes `add` the entire membership |

**Request example:**

```bash
curl -X PATCH https://flags.spoonity.com/admin/v1/environments/1047166:production/segments/beta-testers/keys \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "add": ["member:10442817", "member:10442818"] }'
```

**Response example:** the updated `Segment`:

```json
{
  "name": "beta-testers",
  "environmentId": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
  "description": "Staff and friendly members",
  "keyCount": 2,
  "changeNumber": 1790764767163,
  "createdAt": "2026-09-30T10:39:27.144Z",
  "updatedAt": "2026-09-30T10:39:27.165Z"
}
```

Each call is one change number and one `segments_changed` event. A replace
split across several calls is visible part-filled to SDKs between calls.

**Errors:** `400 invalid_request`, `403 forbidden`, `404 not_found`.

### POST /admin/v1/environments/{env}/segments/{name}/import

Bulk import keys, as CSV or JSON.

**Auth:** editor.

**Request body**, one of:

- `Content-Type: text/csv` (or `text/plain`): one key per line; a leading
  `key` header line is ignored, blank lines are skipped, only the first
  comma-separated column is read. Add `?replace=true` to make the file the
  whole membership.
- `Content-Type: application/json`: `{ "keys": ["…"], "mode": "add" }` with 1
  to 50 000 keys; `mode` is `add` (default) or `replace`. Duplicates and
  surrounding whitespace are collapsed.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/environments/1047166:production/segments/beta-testers/import \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: text/csv" \
  --data-binary $'key\nmember:10442819\nmember:10442820\n'
```

**Response example:** the updated `Segment`, here with `"keyCount": 4`.

**Errors:** `400 invalid_request` (including `"the import contained no keys"`),
`403 forbidden`, `404 not_found`, `413 payload_too_large`.

### GET /admin/v1/environments/{env}/changes

The environment's change log: every write, with actor and the documents
before and after.

**Auth:** viewer. Paginated.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `action` | string | Exact match: `flag.create`, `flag.update`, `flag.archive`, `flag.definition.update`, `flag.kill`, `flag.restore`, `segment.create`, `segment.update`, `segment.delete`, `segment.keys.update`, `sdk_key.create`, `sdk_key.revoke`, `environment.create`, `environment.update`, `workspace.create`, `workspace.update` |
| `target` | string | Exact match on the flag key, segment name or key id |
| `actor` | string | Exact match, case-insensitive |
| `from`, `to` | ISO 8601 | Time range |

**Request example:**

```bash
curl "https://flags.spoonity.com/admin/v1/environments/1047166:production/changes?action=flag.kill" \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example** (`before` and `after` shortened):

```json
{
  "items": [
    {
      "id": "chg_01M3RYBP183J3TXFEFQ5GX1FS1",
      "environmentId": "env_01M3RYBNTHYW5RNP2M5KD0Q3MY",
      "workspaceId": "ws_01M3RYBNS1RB32K8J13R119Y8X",
      "action": "flag.kill",
      "target": "checkout-redesign",
      "actor": "owner@brand.example",
      "actorRole": "admin",
      "actorKind": "user",
      "via": "identity",
      "vendorId": "1047166",
      "comment": null,
      "before": { "flag": "checkout-redesign", "killed": false, "version": 1, "…": "…" },
      "after": { "flag": "checkout-redesign", "killed": true, "version": 2, "…": "…" },
      "changeNumber": 1790764767270,
      "createdAt": "2026-09-30T10:39:27.272Z"
    }
  ],
  "nextCursor": null
}
```

`actorKind` is `user` (a person), `service` (a Spoonity service account acting
as itself) or `delegated` (a Spoonity service, such as Prism, acting for the
person named in `actor`; `via` then names the service account). A
`sdk_key.create` entry never contains the secret.

**Errors:** `400 invalid_request` (`` `from` must be an ISO-8601 timestamp ``), `404 not_found`.

### GET /admin/v1/workspaces/{ws}/changes

The same log across the whole workspace, including workspace-level changes
(flag create, update and archive). Same query parameters and response.

**Auth:** viewer. Paginated.

**Request example:**

```bash
curl "https://flags.spoonity.com/admin/v1/workspaces/1047166/changes?target=checkout-redesign" \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:** a page of `ChangeEntry`, as above. Workspace-level
entries have `"environmentId": null`.

**Errors:** `400 invalid_request`, `404 not_found`.

### GET /admin/v1/environments/{env}/impressions/summary

Hourly impression counts for one flag, by treatment and reason.

**Auth:** viewer.

**Query parameters:**

| Name | Type | Description |
|---|---|---|
| `flag` | string | Required |
| `from`, `to` | ISO 8601 | Default: the last 24 hours. At most 31 days |

**Request example:**

```bash
curl "https://flags.spoonity.com/admin/v1/environments/1047166:production/impressions/summary?flag=checkout-redesign" \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "flag": "checkout-redesign",
  "from": "2026-09-29T10:39:41.340Z",
  "to": "2026-09-30T10:39:41.340Z",
  "total": 2,
  "buckets": [
    { "hour": "2026-09-30T10:00:00.000Z", "treatment": "off", "reason": "default_rule", "count": 1 },
    { "hour": "2026-09-30T10:00:00.000Z", "treatment": "on", "reason": "rule", "count": 1 }
  ]
}
```

Buckets are UTC hours; hours with no data are omitted.

**Errors:**

| Status | Code | Meaning |
|---|---|---|
| 400 | invalid_request | `` `flag` is required ``, or `the maximum range is 31 days` |
| 404 | not_found | Unknown environment |

### GET /admin/v1/environments/{env}/events/summary

Hourly event counts and value sums.

**Auth:** viewer.

**Query parameters:** `eventType` (optional filter), `from`, `to` (as for
impressions).

**Request example:**

```bash
curl "https://flags.spoonity.com/admin/v1/environments/1047166:production/events/summary?eventType=order.completed" \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN"
```

**Response example:**

```json
{
  "from": "2026-09-29T10:39:41.369Z",
  "to": "2026-09-30T10:39:41.369Z",
  "total": 2,
  "buckets": [
    { "hour": "2026-09-30T10:00:00.000Z", "eventType": "order.completed", "count": 2, "valueSum": 60.5 }
  ]
}
```

Events are not joined to treatments here; the summary counts every event of
the type in the environment.

**Errors:** `400 invalid_request`, `404 not_found`.

### POST /admin/v1/environments/{env}/evaluate

The debugger: evaluate a context against the environment as it stands. Always
a dry run; records no impressions.

**Auth:** viewer.

**Request body:** `{ "key": "…", "attributes"?: {…}, "flags"?: ["…"] }`.

**Request example:**

```bash
curl -X POST https://flags.spoonity.com/admin/v1/environments/1047166:production/evaluate \
  -H "Authorization: Bearer REPLACE_WITH_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{ "key": "member:10442817", "flags": ["checkout-redesign"] }'
```

**Response example** (same shape as
[`POST /sdk/v1/evaluate`](#post-sdkv1evaluate)):

```json
{
  "key": "member:10442817",
  "till": 1790764767288,
  "results": [
    {
      "flag": "checkout-redesign",
      "treatment": "on",
      "reason": "rule",
      "ruleId": "r-beta",
      "config": "{\"variant\":\"v2\",\"steps\":2}",
      "changeNumber": 1790764767288
    }
  ]
}
```

**Errors:** `400 invalid_request`, `404 not_found`.

## Operational endpoints

No authentication.

| Route | Response |
|---|---|
| `GET /health` | `200 {"status":"ok"}`, reaching nothing external |
| `GET /ready` | `200 {"ready":true,"store":"postgres","version":"…"}`, or `503` when the store is unusable |
| `GET /version` | `200 {"name":"spoonity-flags","version":"spoonity-flags-00017-d8v"}` |
| `GET /openapi.json` | The OpenAPI 3.1 document, also at [/docs/openapi/flags.yaml](openapi/flags.yaml) |

## Managing flags in Prism

Brand operators usually manage Flags from Prism rather than this API: Studio
→ **Flags** (flags, definitions and the rule builder, kill and restore,
history), **Flag audiences** (segments, including a sync from a Customers
segment), **Flag changes** and **Evaluate**; Reporting → Analytics → **Flag
results**; and ⚙ Product settings → **SDK keys** and **Flag environments**.
Prism calls this same admin API on the operator's behalf, scoped to the
brand they are working in, with their Prism role at that brand
(`viewer`, `editor`, `admin`) applied the same way as the table in
[Admin sessions](#admin-sessions). Prism's own `/api/flags/*` proxy is
session-authenticated and not an integration surface; see
[Prism](/docs/prism).

CMS content experiments can hand variant assignment to a Flags flag; see
[CMS](/docs/cms).

## See also

- [Conventions](/docs/conventions): how Flags' errors, pagination and rate
  limits compare with the other services
- [Authentication](/docs/authentication): every credential on the platform
- [OpenAPI specification](openapi/flags.yaml)
- [CMS](/docs/cms) · [Prism](/docs/prism)
