API Reference

Complete reference for the Bandit REST API. Integrate treatment assignments, event tracking, and experiment management into your application.

Base URL:https://runbandit.comPROD

Response Format

All endpoints return a consistent JSON envelope:

{
  "success": true,
  "data": { ... },
  "error": "...",
  "timestamp": "2026-12-05T19:06:27.486Z"
}

Authentication

Each endpoint lists the credentials it accepts:

api-keyPass your API key via the Authorization: Bearer <key> header or x-api-key header. Used by the SDK for assignment and event endpoints. Keys belong to one environment: a key from the development dashboard works only against the development base URL, and a production key only against production.
publishable-keyAlso accepts the publishable key, which is safe in page source. Browser requests must come from an origin on the key's allowlist when it has one, or get a 403.
sessionAuthenticated via Clerk session cookie. Used by the dashboard.
adminRequires the user to have the admin role within the company.

Limits & Quotas

Volume is not metered, but each account has a per-minute request limit on the SDK routes so a runaway integration can't flood it. Individual requests are also bounded by payload-size and batch-size limits.

Rate limits

Up to 6,000 requests a minute per account for serving (/assignments), and another 6,000 for tracking (/events, /events/batch, /exposures, funnel rewards). Counted per Cloudflare location, so the effective ceiling is higher for global traffic. Over the limit returns 429 with a Retry-After header in seconds.

Idempotent retries

Send an Idempotency-Key header (1 to 255 characters, unique per logical request) on POST /events, /events/batch, /exposures and /funnels/:id/reward. A retry with the same key within 24 hours returns the first successful response, marked Idempotent-Replayed: true, and records nothing twice. A retry while the first is still running returns 409. Errors are not kept, so a retry after one runs again. The JavaScript SDK sends one key per event batch.

Request size

  • POST /assignments and POST /events: max body size 100 KB. Over the limit returns 413.
  • POST /events/batch: up to 1,000 events per request. Larger batches must be split client-side.

Monthly usage

There is no monthly event quota. Visitors and events are unmetered; only the request limits above apply.

Recommended client practices

  • Use POST /events/batch for high-volume tracking instead of one request per event.
  • The JavaScript SDK batches events automatically — prefer it over hand-rolled fetches.
  • On 429, wait for the seconds in Retry-After before retrying. Retry on 500 with exponential backoff, reusing the same Idempotency-Key. Do not retry on 400 / 401 / 413 — those are caller errors.

Assignments

Get treatment assignments for users in experiments

POST/api/assignments

Create assignment

Request a treatment assignment for a user in an experiment. The bandit algorithm selects the optimal treatment based on historical performance. If the user already has a cached assignment, it is returned instead. When the experiment belongs to a funnel, `funnelId` names it, so the caller can reward the funnel with `POST /funnels/{funnelId}/reward`. `trialOn` says when this experiment counts a trial: "served" (now) or "exposure" (once the visitor sees it, so report it with `POST /api/exposures`). A completed experiment with a winner returns the winner, and crawler requests and expired trials return the best-performing treatment; those responses carry no `trialOn`, `confidence` or `probabilityBest`, and a crawler response also sets `crawler: true`. A request body that fails validation returns 500 with the validation message.

Auth:api-keypublishable-key

Request Body

NameTypeRequiredDescription
experimentIdstringrequiredID of the experiment to assign
userIdstringrequiredUnique identifier for the user
contextRecord<string, string | number | boolean>optionalOptional context for contextual bandit algorithms (e.g. device type, location)
sessionIdstringoptionalSession ID for event attribution (auto-generated by SDK)
pageUrlstringoptionalAddress of the page the experiment runs on, up to 2048 characters, starting with http:// or https://. Used to capture the page for drafting new treatments; prefetch and crawler requests are ignored

Response data

NameTypeRequiredDescription
assignmentIdstringrequiredPass it to events and exposures to attribute them to this assignment
treatmentIdstringrequiredEmpty when a bot is left on the page's own copy
treatment{ name: string; config: unknown }optionalThe served treatment, absent when it was deleted or when a bot is left on the page's own copy
confidencenumberoptional
probabilityBestnumberoptionalChance this treatment is the best, for Thompson sampling
funnelIdstringoptionalThe funnel the experiment belongs to
trialOn"served" | "exposure"optionalWhen this experiment counts a trial
crawlertrueoptionalSet when the request came from a crawler

Responses

200Assignment returned successfully
400Request body is not valid JSON or fails validation, experiment is not active, has no treatments, or is served via its bundle, not directly
401Invalid or missing API key
403Origin not allowed for this publishable key, or the demo company
404Experiment not found
413Request payload exceeds maximum size of 100KB
429Rate limit exceeded for this account
500Unexpected server error

Example

Request

{
  "experimentId": "exp_abc123",
  "userId": "user_42",
  "context": {
    "deviceType": "mobile",
    "country": "US"
  }
}

Response

{
  "success": true,
  "data": {
    "assignmentId": "asgn_xyz789",
    "treatmentId": "trt_def456",
    "treatment": {
      "name": "Headline B",
      "config": {
        "content": "Start your free trial today"
      }
    },
    "confidence": 0.87,
    "probabilityBest": 0.81,
    "funnelId": "fnl_abc123",
    "trialOn": "served"
  },
  "timestamp": "2026-01-15T10:30:00.000Z"
}
GET/api/assignments/:experimentId

Get assignment

Retrieve a treatment assignment for a user via query parameters. Functionally equivalent to the POST endpoint but useful for simple GET-based integrations. The response, including its errors, is the POST response; sessionId and pageUrl cannot be sent.

Auth:api-keypublishable-key

Path Parameters

NameTypeRequiredDescription
experimentIdstringrequiredID of the experiment

Query Parameters

NameTypeRequiredDescription
userIdstringrequiredUnique identifier for the user
contextstringoptionalJSON-encoded context object for contextual bandits, up to 10,000 characters

Response data

NameTypeRequiredDescription
assignmentIdstringrequiredPass it to events and exposures to attribute them to this assignment
treatmentIdstringrequiredEmpty when a bot is left on the page's own copy
treatment{ name: string; config: unknown }optionalThe served treatment, absent when it was deleted or when a bot is left on the page's own copy
confidencenumberoptional
probabilityBestnumberoptionalChance this treatment is the best, for Thompson sampling
funnelIdstringoptionalThe funnel the experiment belongs to
trialOn"served" | "exposure"optionalWhen this experiment counts a trial
crawlertrueoptionalSet when the request came from a crawler

Responses

200Assignment returned successfully
400Missing userId, context over 10,000 characters or not valid JSON, or experiment not active
401Invalid or missing API key
403Origin not allowed for this publishable key, or the demo company
404Experiment not found
429Rate limit exceeded for this account
500Unexpected server error

Events

Track events, report exposures and forward events from a customer data platform

POST/api/events

Track event

Track a single named event with optional value and metadata. Events are free-form and land in the event log. An event with cost or lineItems is an order and pays the funnels and campaigns of its visitor; any other event credits nothing. Orders need the secret key: a publishable key sending cost or lineItems gets 403 (send orders from your server, or use POST /api/orders). Funnel conversions come from convert(), funnel goals and source events. An event named "$exposure" with an assignmentId reports an exposure instead of a conversion, the same as POST /api/exposures. A body of the form { events: [...] } is handled as a batch, exactly like POST /api/events/batch. Requests from crawlers return 200 with data { crawler: true, recorded: 0 } and record nothing. Requires API key authentication. Send an Idempotency-Key header to make a retry safe.

Auth:api-keypublishable-key

Request Body

NameTypeRequiredDescription
namestringrequiredFree-form event name (e.g. "purchase", "signup", "button_click"). The name does not decide credit.
categorystringoptionalOptional category to group related events
sessionIdstringrequiredSession identifier. Used for attribution only when neither assignmentId nor userId is set
userIdstringoptionalResolves to this visitor instead of the session's. Server-side callers sharing one session ID must set it per event
assignmentIdstringoptionalThe assignmentId returned by /api/assignments. Resolves the visitor and scope from exactly that assignment and takes precedence over userId and sessionId
valuenumberoptionalNumeric value for the event (e.g. revenue amount). On an order, a `count` funnel credits 1 whatever is sent
costnumberoptionalWhat the order cost you, in the same currency as value. An event with cost or lineItems is an order: it pays the funnels and campaigns of its visitor by their payout unit (a `margin` funnel gets value - cost in dollars, negative when sold below cost). Without a cost it pays no margin
lineItemsArray<{ id?: string; quantity?: number; price: number; discount?: number; unitCost?: number }>optionalPer-line prices and unit costs instead of value and cost, up to 500 lines. Margin is known only when every line has a unitCost
metadataRecord<string, unknown>optionalArbitrary key-value metadata to attach to the event

Response data

NameTypeRequiredDescription
processednumberrequiredEvents that were not exposures
rewardednumberrequiredFunnel and campaign rewards the events paid
exposednumberoptionalNew exposures from "$exposure" events; present only when the request had any

Responses

201Event tracked successfully
400Invalid request body or validation error
401Invalid or missing API key
403Origin not allowed for this publishable key, a publishable key sending an order (cost or lineItems), or the demo company
409A request with the same Idempotency-Key is still being processed
413Request payload exceeds maximum size of 100KB
429Rate limit exceeded for this account
500Server failure; safe to retry

Example

Request

{
  "name": "purchase",
  "category": "conversion",
  "sessionId": "sess_abc123",
  "value": 29.99,
  "metadata": {
    "product": "premium-plan",
    "coupon": "SAVE10"
  }
}

Response

{
  "success": true,
  "data": {
    "processed": 1,
    "rewarded": 0
  },
  "timestamp": "2026-01-15T10:30:00.000Z"
}
GET/api/events/:experimentId

List events

Check that an experiment exists and belongs to your company. Raw events live in the event log, not behind this API, so data is always an empty array and any query parameters are ignored. Requires the secret API key.

Auth:api-key

Path Parameters

NameTypeRequiredDescription
experimentIdstringrequiredID of the experiment

Responses

200Experiment found; data is an empty array
401Invalid or missing API key
403The demo company
404Experiment not found
500Unexpected server error
POST/api/events/batch

Track events (batch)

Track multiple events in a single request for better performance and reduced network overhead. Accepts 1-1000 events per batch. The SDK automatically batches events — prefer it over hand-rolled batch requests. An event named "$exposure" with an assignmentId reports an exposure instead of a conversion, the same as POST /api/exposures. Requests from crawlers return 200 with data { crawler: true, recorded: 0 } and record nothing. Requires API key authentication; an event with cost or lineItems needs the secret key, and a publishable key sending one gets 403 for the whole batch. Send an Idempotency-Key header to make a retry safe. The batch succeeds or fails as a whole: a 4xx means the batch is malformed and retrying it will fail again; a 500 means a server failure, and the whole batch is safe to resend with the same Idempotency-Key (exposures are recorded first and are idempotent, and orders are paid in one step after them).

Auth:api-keypublishable-key

Request Body

NameTypeRequiredDescription
eventsArray<{ name: string; category?: string; sessionId: string; userId?: string; assignmentId?: string; value?: number; cost?: number; lineItems?: Array<{ id?: string; quantity?: number; price: number; discount?: number; unitCost?: number }>; metadata?: Record<string, unknown> }>requiredArray of 1-1000 event objects. Each event has: name (required string), category (optional string), sessionId (required string), assignmentId (optional string), userId (optional string), value (optional number), cost (optional number), lineItems (optional array), metadata (optional object).

Response data

NameTypeRequiredDescription
processednumberrequiredEvents that were not exposures
rewardednumberrequiredFunnel and campaign rewards the events paid
exposednumberoptionalNew exposures from "$exposure" events; present only when the request had any

Responses

201Batch tracked successfully
400Invalid request body, validation error, or batch exceeds 1000 events
401Invalid or missing API key
403Origin not allowed for this publishable key, a publishable key sending an order (cost or lineItems), or the demo company
409A request with the same Idempotency-Key is still being processed
429Rate limit exceeded for this account
500Server failure; safe to retry

Example

Request

{
  "events": [
    {
      "name": "page_view",
      "category": "engagement",
      "sessionId": "sess_abc123",
      "metadata": {
        "page": "/pricing"
      }
    },
    {
      "name": "button_click",
      "category": "interaction",
      "sessionId": "sess_abc123",
      "metadata": {
        "button": "cta-primary"
      }
    },
    {
      "name": "purchase",
      "category": "conversion",
      "sessionId": "sess_abc123",
      "value": 49.99,
      "metadata": {
        "product": "pro-plan"
      }
    }
  ]
}

Response

{
  "success": true,
  "data": {
    "processed": 3,
    "rewarded": 0
  },
  "timestamp": "2026-01-15T10:30:00.000Z"
}
POST/api/exposures

Report exposures

Report that visitors actually saw the treatment they were served. An exposure is idempotent per assignment: only the first report counts. For an experiment whose trial rule is "exposure" (every picker experiment by default, or any experiment created with trialOn: "exposure"), the first exposure is what counts as a trial. For a "served" experiment it is tracked beside the trial. The SDK sends these for you through client.exposed() and client.observeExposure(). You can also send a "$exposure" event with an assignmentId to /api/events or /api/events/batch. Requests from crawlers return 200 with data { crawler: true, recorded: 0 } and record nothing. Requires API key authentication. Send an Idempotency-Key header to make a retry safe.

Auth:api-keypublishable-key

Request Body

NameTypeRequiredDescription
exposuresArray<{ assignmentId: string; exposedAt?: number }>requiredArray of 1-1000 exposures. Each has: assignmentId (required string, the assignmentId returned by /api/assignments or your clientAssignmentId) and exposedAt (optional number, epoch milliseconds, defaults to now).

Response data

NameTypeRequiredDescription
recordednumberrequiredExposures that were new

Responses

201Exposures processed. data.recorded counts the ones that were new.
400Invalid request body or more than 1000 exposures
401Invalid or missing API key
403Origin not allowed for this publishable key, or the demo company
409A request with the same Idempotency-Key is still being processed
429Rate limit exceeded for this account
500Server failure; safe to retry

Example

Request

{
  "exposures": [
    {
      "assignmentId": "k57abc123def456",
      "exposedAt": 1768473000000
    }
  ]
}

Response

{
  "success": true,
  "data": {
    "recorded": 1
  },
  "timestamp": "2026-01-15T10:30:00.000Z"
}
POST/api/sources/segment

Receive Segment-spec events from a CDP

Accepts events shaped like the Segment spec, so Segment (Webhooks Actions destination), RudderStack (Webhook destination) and PostHog (HTTP webhook destination) can forward data they already collect. A track is stored once per messageId and resolved to a visitor through the CDP alias join, then the identified user ID; one that resolves to nobody is kept as unmatched. An identify joins userId to the visitor and records string, number and boolean traits as visitor labels. page and unknown event types are ignored. Tracks do not credit rewards yet. Requires the secret key; publishable keys are refused. Do not rely on Segment's X-Signature header, which signs only the first event of a batch.

Auth:api-key

Query Parameters

NameTypeRequiredDescription
source"segment" | "rudderstack" | "posthog"optionalThe sending platform: segment (default), rudderstack or posthog. It picks which anonymous ID alias namespace is read.

Request Body

NameTypeRequiredDescription
batchArray<unknown>optionalUp to 1000 events. Omit it and send one event as the body instead.
typestringoptionalOn a single event or each batch entry: track, identify, or anything else (ignored).
messageIdstringoptionalRequired on a track. A message delivered again never stores twice.
eventstringoptionalRequired on a track: the event name.
propertiesRecord<string, unknown>optionalTrack properties, stored as received.
anonymousIdstringoptionalThe platform anonymous ID, resolved through the visitor alias.
userIdstringoptionalThe identified user ID, used when the anonymous ID does not resolve.
traitsRecord<string, unknown>optionalOn an identify: traits recorded as visitor labels, up to 20.

Response data

NameTypeRequiredDescription
acceptednumberrequiredEvents stored or applied
duplicatesnumberrequiredTracks already stored under the same messageId
unmatchednumberrequiredAccepted events that resolved to no visitor
ignorednumberrequiredEvents skipped: page, unknown type, or failing validation

Responses

200Counts of accepted, duplicates, unmatched and ignored events
400Invalid request body or source
401Invalid or missing API key
403A publishable key, or the demo company
413Request payload exceeds 5MB
500Failed to ingest events, retry later

Example

Request

{
  "batch": [
    {
      "type": "track",
      "messageId": "ajs-next-1d2c9a",
      "event": "Order Completed",
      "anonymousId": "7d3c9e55-1b0a-4f2c-8a46-5e7d0f3b9c21",
      "properties": {
        "revenue": 59.9,
        "currency": "USD"
      }
    }
  ]
}

Response

{
  "success": true,
  "data": {
    "accepted": 1,
    "duplicates": 0,
    "unmatched": 0,
    "ignored": 0
  },
  "timestamp": "2026-11-06T19:30:00.000Z"
}
POST/api/sources/shopify

Receive a Shopify customer-events pixel event

Records one checkout or cart event from Bandit's Shopify customer-events pixel. The event is stored once per id, and a funnel whose goal is an event of that name is credited, with the order total when the goal reads one. Requires a publishable key. The pixel runs in Shopify's sandbox with no usable origin, so allowed origins are not checked; a secret key is refused. A request body over 10KB is refused. A GET answers 405.

Auth:publishable-key

Request Body

NameTypeRequiredDescription
visitorIdstringrequiredThe Bandit visitor ID the pixel read from the storefront
event"checkout_completed" | "checkout_started" | "payment_info_submitted" | "product_added_to_cart"requiredThe Shopify event name; any other is refused
idstringrequiredShopify's event ID; sending it again is a duplicate
orderIdstringoptionalShopify order ID
checkoutTokenstringoptionalShopify checkout token
totalnumberoptionalOrder or cart total
currencystringoptionalCurrency code of total

Response data

NameTypeRequiredDescription
acceptednumberrequired1 when the event was stored, 0 for a duplicate
duplicatesnumberrequired1 when the id was already stored
creditednumberrequiredFunnel rewards credited by this event

Responses

200Event stored or recognized as a duplicate
400Body is not JSON, or fails validation: an unknown event name or a missing visitorId or id
401Missing, invalid or inactive API key
403A secret key, or the demo company
413Request body over 10KB
500Failed to record the event, retry later

Example

Request

{
  "visitorId": "visitor-1",
  "event": "checkout_completed",
  "id": "e1",
  "orderId": "gid://shopify/OrderIdentity/1",
  "total": 42.5,
  "currency": "USD"
}

Response

{
  "success": true,
  "data": {
    "accepted": 1,
    "duplicates": 0,
    "credited": 1
  },
  "timestamp": "2026-11-18T10:30:00.000Z"
}

Experiments

Create and manage experiments

GET/api/experiments

List experiments

Retrieve all experiments belonging to the authenticated company, except archived ones. Returns experiments with their treatments.

Auth:api-keypat

Responses

200Experiments returned successfully
401Missing or invalid credentials
500Failed to list experiments
POST/api/experiments

Create experiment

Create a new experiment in DRAFT status inside a funnel or a campaign. Optionally include initial treatments. The experiment must be activated separately via PATCH after adding at least one treatment. Learning settings are not per experiment: forgetting, credit and serve by visitor belong to the parent funnel or campaign (Funnel modes).

Auth:api-keypat

Request Body

NameTypeRequiredDescription
namestringrequiredHuman-readable name for the experiment
funnelIdstringoptionalFunnel the experiment joins. Exactly one of funnelId or campaignId is required
campaignIdstringoptionalCampaign the experiment joins as a new slot. Exactly one of funnelId or campaignId is required
descriptionstringoptionalDescription of the experiment goals
statusstringoptionalInitial status: draft, active, paused, completed or archived (default: draft)
contentTypestringrequiredContent type of treatments, for example plain_text
contentSubtypestringoptionalContent subtype (default: plain_text)
assignmentTtlnumberoptionalAssignment cache TTL in seconds (default: 86400 = 24 hours)
trialOn"served" | "exposure"optionalWhen the bandit counts a trial. "served" counts one when the treatment is served. "exposure" counts one when the visitor actually sees it, reported with POST /api/exposures. Defaults to "served", and to "exposure" for point-and-click picker experiments. Fixed at creation.
informedPriorbooleanoptionalAsk for an informed prior; only legacy standalone experiments can use it
treatmentsArray<{ name: string; description?: string; config: unknown; weight: number }>optionalOptional initial treatments to create with the experiment

Responses

201Experiment created in DRAFT status. `data.health` is the parent funnel model health after the change (see GET /api/funnels/:id/health)
400Body is not valid JSON or fails validation, neither or both of funnelId and campaignId given, trialOn is not "served" or "exposure", status is not draft, active, paused, completed or archived, Convex rejects an argument, or the body asks for a per-step algorithm (contextual_*), forgetting (discounted or sliding_window) or posterior (other than normal_gamma), which are set on the parent funnel or campaign (Funnel modes). The defaults released CLIs send (thompson_sampling, { mode: "none" }, normal_gamma) are accepted and ignored
401Missing or invalid credentials
404The funnel or campaign does not exist or belongs to another company
409Created as active with no treatments
500Creation failed on the server

Example

Request

{
  "name": "Homepage Headline Test",
  "funnelId": "k17a2b3c4d5e6f7g8h9j0",
  "description": "Test different headlines on the landing page",
  "contentType": "plain_text",
  "treatments": [
    {
      "name": "Control",
      "config": {
        "content": "Welcome to our platform"
      },
      "weight": 1
    },
    {
      "name": "Urgency",
      "config": {
        "content": "Limited time offer - start free today!"
      },
      "weight": 1
    }
  ]
}

Response

{
  "success": true,
  "data": {
    "id": "exp_abc123",
    "name": "Homepage Headline Test",
    "algorithm": "thompson_sampling",
    "status": "draft",
    "treatments": [
      "..."
    ]
  },
  "timestamp": "2026-01-15T10:00:00.000Z"
}
GET/api/experiments/:id

Get experiment

Retrieve a single experiment by ID or by name (an id containing a hyphen is looked up as a name), including all associated treatments and their configurations.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID or name of the experiment

Responses

200Experiment returned successfully
401Missing or invalid credentials
404Experiment not found
500Failed to get experiment
PATCH/api/experiments/:id

Update experiment

Update experiment properties including name, description, status, and TTL. To activate an experiment, set status to active. Activation requires at least one treatment. Learning settings are not per experiment: forgetting, credit and serve by visitor belong to the parent funnel or campaign (Funnel modes).

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the experiment to update

Request Body

NameTypeRequiredDescription
namestringoptionalUpdated name
descriptionstringoptionalUpdated description
statusstringoptionalNew status: draft, active, paused, completed, or archived
contentTypestringoptionalUpdated content type
contentSubtypestringoptionalUpdated content subtype
assignmentTtlnumberoptionalUpdated assignment TTL in seconds
endAtnumberoptionalScheduled end of the experiment, in milliseconds since the Unix epoch
trialOn"served" | "exposure"optionalRejected with 400 unless it equals the current rule, which is fixed at creation

Responses

200Experiment updated successfully
400Body is not valid JSON or fails validation, Convex rejects an argument, status is not draft, active, paused, completed or archived, the placement would change the content kind, the body asks for a per-step algorithm, forgetting or posterior (set on the parent funnel or campaign, Funnel modes; the released CLI defaults are accepted and ignored), or the experiment counting rule (trialOn) changed after creation
401Missing or invalid credentials
404Experiment not found, or it belongs to another company
409Activation with no treatments, or the placement is already used by another active experiment
500Update failed on the server

Treatments

List, add, edit and close the treatments of an experiment, the versions of the thing it tests

GET/api/treatments

List treatments

Retrieve every treatment of one experiment, closed ones included.

Auth:api-keypat

Query Parameters

NameTypeRequiredDescription
experimentIdstringrequiredID of the experiment whose treatments to list

Responses

200The experiment treatments
400experimentId is missing, or a PAT request has no x-company-id header
401Missing or invalid credentials
403The token has no access to the company, or the demo company
500Listing failed on the server. An experiment that does not exist or belongs to another company returns an empty list
POST/api/treatments

Create treatment

Add a treatment to an experiment of the authenticated company. The treatment's content goes in config, validated against the experiment's placement.

Auth:api-keypat

Request Body

NameTypeRequiredDescription
experimentIdstringrequiredID of the experiment to add the treatment to
namestringrequiredTreatment name
descriptionstringoptionalOptional description
configunknownoptionalTreatment content, for example { content: "Welcome" } (default: {})
weightnumberoptionalRelative traffic weight (default: 1)

Response data

NameTypeRequiredDescription
_idstringrequiredTreatment ID
_creationTimenumberrequiredCreation time, in milliseconds since the Unix epoch
experimentIdstringrequiredThe experiment this treatment belongs to
companyIdstringrequired
namestringrequired
descriptionstringoptional
configunknownrequiredTreatment content, for example { content: "Welcome" }
weightnumberrequiredRelative traffic weight
closedAtnumberoptionalWhen the treatment was closed; absent while it serves

Responses

201Treatment created
400Body is not valid JSON or fails validation, a PAT request has no x-company-id header, the config does not fit the experiment placement, or Convex rejects an argument
401Missing or invalid credentials
403The token has no access to the company, or the demo company
404The experiment does not exist or belongs to another company
500Creation failed on the server

Example

Request

{
  "experimentId": "k17a2b3c4d5e6f7g8h9j0",
  "name": "Benefit-led",
  "config": {
    "content": "Ship twice as fast"
  },
  "weight": 1
}
PATCH/api/treatments/:id

Update treatment

Change the name, description, content or weight of a treatment. Set closed to true to stop serving it while keeping its history, or false to serve it again. Fields left out stay as they are.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the treatment

Request Body

NameTypeRequiredDescription
namestringoptionalUpdated name
descriptionstringoptionalUpdated description
configunknownoptionalUpdated content
weightnumberoptionalUpdated relative traffic weight
closedbooleanoptionaltrue closes the treatment, false reopens it

Response data

NameTypeRequiredDescription
_idstringrequiredTreatment ID
_creationTimenumberrequiredCreation time, in milliseconds since the Unix epoch
experimentIdstringrequiredThe experiment this treatment belongs to
companyIdstringrequired
namestringrequired
descriptionstringoptional
configunknownrequiredTreatment content, for example { content: "Welcome" }
weightnumberrequiredRelative traffic weight
closedAtnumberoptionalWhen the treatment was closed; absent while it serves

Responses

200Treatment updated; returns the stored treatment
400Body is not valid JSON or fails validation, a PAT request has no x-company-id header, or Convex rejects an argument
401Missing or invalid credentials
403The token has no access to the company, or the demo company
404The treatment does not exist or belongs to another company
409Closing the last open treatment, or closing a treatment in a campaign
500Update failed on the server

Funnels

Create and manage multi-step experiment funnels

GET/api/funnels

List funnels

Retrieve all funnels belonging to the authenticated company. Each funnel links multiple experiments into a sequential conversion path.

Auth:api-keypat

Responses

200Funnels returned successfully
401Missing or invalid credentials
POST/api/funnels

Create funnel

Create a new funnel, optionally linking existing experiments into a multi-step conversion path. Omit `experimentIds` to create an empty funnel, then create experiments inside it with `POST /experiments` and its `funnelId`.

Auth:api-keypat

Request Body

NameTypeRequiredDescription
namestringrequiredHuman-readable name for the funnel
descriptionstringoptionalDescription of the funnel goals
experimentIdsArray<string>optionalOrdered list of existing experiment IDs that form the funnel steps. Defaults to none.
inactivityTimeoutMsnumberoptionalMilliseconds a visitor can be idle before resolving to a $0 outcome
revisionWindowMsnumberoptionalMilliseconds after resolution in which a real reward still replaces the $0
payoutUnit"count" | "revenue" | "margin"optionalHow a conversion is scored: `count` (default) credits 1 per conversion and ignores any value sent, for goals with no price like a booked demo call; `revenue` credits the order value sent with the reward; `margin` credits contribution margin (revenue minus cost) from orders sent to `POST /api/orders`, negative below cost. Changed behaviour: before `payoutUnit` existed every funnel credited the value sent; a new funnel now defaults to `count`, so a script that sends revenue must pass `payoutUnit: "revenue"` or each reward is stored as 1

Responses

201Funnel created successfully
400Validation error (e.g. missing name, or a non-positive inactivityTimeoutMs or revisionWindowMs)
401Missing or invalid credentials
404An experiment in experimentIds does not exist or belongs to another company
409An experiment in experimentIds is already in a funnel
500Creation failed on the server

Example

Request

{
  "name": "Onboarding Flow",
  "description": "Test headline → CTA → pricing across the onboarding funnel",
  "experimentIds": [
    "exp_headline",
    "exp_cta",
    "exp_pricing"
  ]
}

Response

{
  "success": true,
  "data": {
    "id": "fnl_abc123",
    "name": "Onboarding Flow",
    "description": "Test headline → CTA → pricing across the onboarding funnel",
    "experimentIds": [
      "exp_headline",
      "exp_cta",
      "exp_pricing"
    ],
    "status": "draft"
  },
  "timestamp": "2026-01-15T12:00:00.000Z"
}
GET/api/funnels/:id

Get funnel

Retrieve a single funnel by ID, including details about its linked experiments and their current status, and `health`, the same object as GET /api/funnels/:id/health.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the funnel

Responses

200Funnel returned successfully
401Missing or invalid credentials
404Funnel not found
PUT/api/funnels/:id

Update funnel

Update funnel properties such as name, description, or status. `forgetting` sets how the funnel weighs old visitors and needs an admin token or a secret key; every model, fair credit and serve by visitor included, then learns from the forgotten data.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the funnel to update

Request Body

NameTypeRequiredDescription
namestringoptionalUpdated name
descriptionstringoptionalUpdated description
status"draft" | "active" | "paused" | "completed"optionalNew status: draft, active, paused, or completed
inactivityTimeoutMsnumberoptionalMilliseconds a visitor can be idle before resolving to a $0 outcome
revisionWindowMsnumberoptionalMilliseconds after resolution in which a real reward still replaces the $0
forgetting{ mode: "none" } | { mode: "discounted"; halfLifeMs?: number } | { mode: "sliding_window"; windowMs?: number } | nulloptionalForgetting mode, or null for stationary: { "mode": "discounted", "halfLifeMs"?: number } (default 7 days), { "mode": "sliding_window", "windowMs"?: number } (default 14 days), or { "mode": "none" }. Spans run from 7 to 90 days. Only days older than the funnel inactivity timeout count, and the window or half-life is measured back from the newest settled day. Needs an admin token or a secret key.
thinDataFallbackbooleanoptionalDefault true. Under forgetting, check the kept data against the fair credit, interaction and serve-by-visitor minimums on each serve; below them, serve per-step credit (and the same treatment for every visitor) until the data grows back. The stored modes do not change. Needs an admin token or a secret key.
fallbackPriorityArray<"forgetting" | "credit" | "serveByVisitor">optionalDefault ["forgetting", "credit", "serveByVisitor"]. With thinDataFallback on, the order to keep modes in when the kept data is too thin. A mode ranked above forgetting keeps running by pausing forgetting for the whole funnel (every model learns from full history); a mode ranked below forgetting falls back to per-step credit or the same treatment for everyone. Needs an admin token or a secret key.
contextualHistoryDaysnumberoptionalDefault 60, from 14 to 598. Under forgetting, serve by visitor learns from at most this many settled days, which bounds each serving read. Needs an admin token or a secret key.

Responses

200Funnel updated successfully
400Validation error (e.g. a non-positive inactivityTimeoutMs or revisionWindowMs)
401Missing or invalid credentials
403Changing forgetting needs an admin
404Funnel not found, or it belongs to another company
500Update failed on the server
DELETE/api/funnels/:id

Delete funnel

Delete a funnel. This does not delete the linked experiments, only the funnel grouping.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the funnel to delete

Responses

200Funnel deleted successfully
401Missing or invalid credentials
404Funnel not found, or it belongs to another company
409The funnel is the Shopify store funnel, which cannot be deleted
500Deletion failed on the server
GET/api/funnels/:id/health

Get funnel model health

How much model detail the funnel data supports. `capacity` is the effective sample in visitors (all visitors when stationary; settled visitors per day times half-life / ln 2, or times the window, under forgetting). `bars` has one entry per active model (factored, fair_credit, interactions per pair, serve_by_visitor for the most demanding step) with the ideal need for a confident pick (`load` in visitors, `share` of capacity: 2 × (2 × payout sd / gap between the two leading treatments)² per treatment, the gap floored at 0.2 sd, scaled by the estimates each model makes), the enablement minimum (`minimum`, `minimumShare`, the binding `gate`), a `reason` with the numbers, and the `fallback` that applies when the minimum is past capacity. `idealByModel` gives the ideal of every model, whether it is on or not. `zone` (comfortable when the ideal fits, tight when only the minimum fits, overloaded when the minimum does not) and `score` (0 to 100) come from the worst bar; factored is the floor and never lowers them. `stillLearning` is true when even the factored ideal needs more visitors. `recommendations` (close_treatment, remove_experiment, drop_attribute, lengthen_forgetting) list ways to cut load when the zone is tight or overloaded, best first, with `loadFreed` and `shareAfter`. `attributes` gives, per serve-by-visitor step, the attribute values the data supports and the number used.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the funnel

Responses

200Health returned
401Missing or invalid credentials
404Funnel not found
POST/api/funnels/:id/reward

Record funnel reward

Record a reward (conversion value) for a user who completed the funnel. Updates the bandit algorithm state for all experiments in the funnel based on the treatments the user was assigned. Each user can only have one reward per funnel. Honors the `Idempotency-Key` header.

Auth:api-keypublishable-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the funnel

Request Body

NameTypeRequiredDescription
userIdstringrequiredID of the user who completed the funnel
valuenumberoptionalOrder value (>= 0). Used only when the funnel `payoutUnit` is `revenue` or `margin`; a `count` funnel credits 1 whatever is sent. For margin from revenue and cost, send the order to POST /api/orders instead

Response data

NameTypeRequiredDescription
funnelIdstringrequiredID of the funnel
userIdstringrequiredThe canonical user ID the reward was recorded under
valuenumberrequiredThe value credited under the funnel payoutUnit

Responses

200Reward recorded and algorithm state updated
400Request body is not valid JSON or fails validation
401Invalid or missing API key
404Funnel not found or no assignments found for this user
409Reward already recorded for this user in this funnel, or an identical Idempotency-Key request is still in flight
429Rate limit exceeded
500Internal error recording reward

Example

Request

{
  "userId": "user_42",
  "value": 49.99
}

Response

{
  "success": true,
  "data": {
    "funnelId": "fnl_abc123",
    "userId": "user_42",
    "value": 49.99
  },
  "timestamp": "2026-01-15T14:00:00.000Z"
}

Identity

Link anonymous user IDs to identified users (email, account ID) with attribution

POST/api/aliases

Alias a visitor to its CDP anonymous IDs

Join the anonymous ID a customer data platform (Segment, RudderStack, PostHog) assigned to a browser to the Bandit visitor, so events forwarded from that platform credit the right visitor. The SDK and the site script send this for you when they find a platform ID in the page cookies or localStorage. Sending the same alias again changes nothing; if the same platform ID is sent for a different visitor, the latest visitor wins. Requires API key authentication; a publishable key may write aliases because they only create joins, never rewards.

Auth:api-keypublishable-keypat

Request Body

NameTypeRequiredDescription
visitorIdstringrequiredThe same visitor ID you pass to getAssignment()
aliasesArray<{ source: "segment" | "rudderstack" | "posthog"; externalId: string }>requiredOne to three aliases. externalId is the platform anonymous ID, up to 256 characters.

Response data

NameTypeRequiredDescription
receivednumberrequiredAliases in the request
changednumberrequiredNew or re-pointed aliases

Responses

201Aliases recorded; changed counts the new or re-pointed ones
400Invalid request body or validation error
401Invalid or missing API key
403Origin not allowed for this publishable key
500Server failure; safe to retry

Example

Request

{
  "visitorId": "9f1c2f0e-6c1d-4b7a-9d55-0c8f6a3b2e11",
  "aliases": [
    {
      "source": "segment",
      "externalId": "7d3c9e55-1b0a-4f2c-8a46-5e7d0f3b9c21"
    }
  ]
}

Response

{
  "success": true,
  "data": {
    "received": 1,
    "changed": 1
  },
  "timestamp": "2026-11-06T19:30:00.000Z"
}
POST/api/arrivals

Record how a visitor arrived

Record the UTM tags, ad click ID, and external referrer host a visitor landed with. The SDK and the site and storefront scripts send this for you. A tagged landing or an external referrer replaces the visitor's current arrival; a direct landing keeps it until 30 days after it started. Values are trimmed, lowercased, spaces and underscores become dashes, at most 40 characters. Requires API key authentication. Unknown keys in touch are rejected, and a request body over 10KB is refused.

Auth:api-keypublishable-keypat

Request Body

NameTypeRequiredDescription
userIdstringrequiredThe same user ID you pass to getAssignment()
touch{ utmSource?: string; utmMedium?: string; utmCampaign?: string; utmContent?: string; trackingParam?: string; klaviyoExchangeId?: string; referrerHost?: string }requiredRaw values from the landing URL and referrer. An empty object is a direct visit. Each value is at most 200 characters, trackingParam 40, referrerHost 255.

Response data

NameTypeRequiredDescription
recordedbooleanrequiredFalse when a direct visit kept the current arrival
arrival{ source?: string; medium?: string; campaign?: string; content?: string; referrerHost?: string; channel?: "ad" | "email" | "social" | "search" | "referral" | "direct" }optionalThe recorded arrival, absent when recorded is false

Responses

201Touch received; recorded is false when a direct visit kept the current arrival
400Invalid request body or validation error
401Invalid or missing API key
413Request body over 10KB
500Server failure; safe to retry

Example

Request

{
  "userId": "user-123",
  "touch": {
    "utmSource": "Facebook",
    "utmCampaign": "Mothers_Day"
  }
}

Response

{
  "success": true,
  "data": {
    "recorded": true,
    "arrival": {
      "source": "facebook",
      "campaign": "mothers-day",
      "channel": "social"
    }
  },
  "timestamp": "2026-01-15T10:30:00.000Z"
}
POST/api/identify

Link anonymous user to identified user

Link an anonymous user ID to a durable identity (email, account ID). All historical assignments and events for the anonymous ID are re-attributed to the identified user. Future calls to getAssignment() with either ID will resolve to the same assignment. Accepts the secret key, a publishable key (origin allowlist applies), or an admin personal access token with x-company-id.

Auth:api-keypublishable-keypat

Request Body

NameTypeRequiredDescription
anonymousIdstringrequiredTemporary or anonymous user ID (e.g., crypto.randomUUID())
identifiedUserIdstringrequiredPermanent user ID (e.g., email, database ID)
emailstringoptionalThe visitor email, a valid address of at most 320 characters. Never stored. When the company has connected Klaviyo, it is used once to look up the Klaviyo profile and link its ID to this visitor.
mergeReason"user_signup" | "email_verification" | "social_login" | "account_recovery" | "manual"optionalWhy the identification is happening: user_signup, email_verification, social_login, account_recovery, or manual (default: manual)

Response data

NameTypeRequiredDescription
anonymousIdstringrequired
identifiedUserIdstringrequired
alreadyMappedbooleanrequiredTrue when this anonymous ID was already linked to the identified user

Responses

200User identity linked successfully
400Invalid request body or validation error
401Missing or invalid API key
403Origin not allowed for this publishable key, or PAT user is not an admin
409User already identified with a different canonical ID
500Server failure; safe to retry

Example

Request

{
  "anonymousId": "anon_550e8400-e29b-41d4-a716-446655440000",
  "identifiedUserId": "user@example.com",
  "mergeReason": "user_signup"
}

Response

{
  "success": true,
  "data": {
    "anonymousId": "anon_550e8400-e29b-41d4-a716-446655440000",
    "identifiedUserId": "user@example.com",
    "alreadyMapped": false
  },
  "timestamp": "2026-08-26T19:30:00.000Z"
}
POST/api/labels

Label a visitor

Record what a visitor told you about themselves (a survey answer, a signup field). Questions are free-form short keys; the latest answer to a question replaces the earlier one. Audiences use these answers to describe who is in each discovered group. Requires API key authentication. A request body over 100KB is refused.

Auth:api-keypublishable-keypat

Request Body

NameTypeRequiredDescription
userIdstringrequiredThe same user ID you pass to getAssignment()
labelsRecord<string, string | boolean>requiredQuestion to answer, one to 20 per call. Questions are trimmed, lowercased, at most 40 characters. Answers are trimmed, lowercased, at most 40 characters; booleans are stored as "true" or "false".

Response data

NameTypeRequiredDescription
recordednumberrequiredLabels stored; entries that normalize to nothing are skipped

Responses

201Labels recorded (invalid entries are skipped)
400Invalid request body or validation error
401Invalid or missing API key
413Request body over 100KB
500Server failure; safe to retry

Example

Request

{
  "userId": "user-123",
  "labels": {
    "role": "founder",
    "team_size": "2-10"
  }
}

Response

{
  "success": true,
  "data": {
    "recorded": 2
  },
  "timestamp": "2026-01-15T10:30:00.000Z"
}

Campaigns

Create and manage campaigns, which hold experiments and learn from one reward per visitor

GET/api/campaigns

List campaigns

Retrieve all campaigns belonging to the authenticated company.

Auth:api-keypat

Responses

200Campaigns returned successfully
401Missing or invalid credentials
POST/api/campaigns

Create campaign bundle

Create an empty bundle: the shared learning state (one payout unit, one reward per visitor) that an email campaign's experiments learn into. It does not create or send an email campaign, and the returned `_id` is a bundle ID, so `POST /experiments` does not accept it as `campaignId`. Create email campaigns at /emails in the dashboard and pass that campaign's ID.

Auth:api-keypat

Request Body

NameTypeRequiredDescription
namestringrequiredHuman-readable name for the campaign
descriptionstringoptionalDescription of the campaign goals
payoutUnit"count" | "revenue" | "margin"optionalHow a conversion is scored: `count` (default) credits 1 per conversion and ignores any value sent, for goals with no price like a booked demo call; `revenue` credits the order value sent with the reward; `margin` credits contribution margin (revenue minus cost) from orders sent to `POST /api/orders`, negative below cost. Changed behaviour: before `payoutUnit` existed every campaign credited the value sent; a new campaign now defaults to `count`, so a script that sends revenue must pass `payoutUnit: "revenue"` or each reward is stored as 1

Responses

201Campaign created successfully
400Validation error (e.g. missing name)
401Missing or invalid credentials
500Creation failed on the server

Example

Request

{
  "name": "Spring Launch",
  "description": "Headline and CTA for the spring launch"
}

Response

{
  "success": true,
  "data": {
    "_id": "cmp_abc123",
    "name": "Spring Launch",
    "description": "Headline and CTA for the spring launch",
    "status": "draft"
  },
  "timestamp": "2026-01-15T12:00:00.000Z"
}
PATCH/api/campaigns/:id

Advance an email campaign

Move an email campaign forward. `sending` records the tracked destination links (fixed once sending starts) and unlocks `/email/render` and `/email/plan`. `sent` marks the send finished so the campaign can be folded up. Status only moves forward.

Auth:api-keypat

Path Parameters

NameTypeRequiredDescription
idstringrequiredID of the email campaign

Request Body

NameTypeRequiredDescription
status"sending" | "sent"required`sending` or `sent`
linksArray<string>optionalWith `sending`: http(s) destination URLs to tag for click attribution, up to 500. May be empty. Ignored with `sent`.

Responses

200Campaign advanced
400Invalid body or invalid link
401Missing or invalid credentials
404Campaign not found, or it belongs to another company
409The status cannot move backward or stay the same
500Update failed on the server

Example

Request

{
  "status": "sending",
  "links": [
    "https://example.com/sale"
  ]
}

Response

{
  "success": true,
  "data": {
    "campaignId": "cmp_abc123",
    "status": "sending"
  },
  "timestamp": "2026-01-15T12:00:00.000Z"
}

Orders

Send orders with revenue and cost from any store. Each order pays the funnels and campaigns its visitor is in, by their payout unit, so a margin funnel learns from contribution margin

POST/api/orders

Record order

Record an order. The order is that visitor's funnel or campaign payout, scored by its `payoutUnit`: `count` credits 1, `revenue` credits net revenue, `margin` credits revenue minus cost minus discounts plus net shipping, negative when the order sold below cost, and waits until cost is known. Payouts are in dollars (an order of 120 with cost 45.50 pays a margin funnel 74.50). Send either `lines` or `revenue`, never both, and with `lines` send each line its own `unitCost` instead of an order `cost`. The order id is the idempotency key, across this API and the Shopify webhook: sending the same id again is a no-op, except that an order stored without a known cost is recomputed and its margin payouts credited once when you send it again with costs. Requires a secret API key.

Auth:api-key

Request Body

NameTypeRequiredDescription
orderIdstringrequiredYour order id, at most 200 characters. Unique per company
assignmentIdstringoptionalThe assignmentId (or clientAssignmentId) the visitor was served. Pays that assignment's funnel or campaign. Takes precedence over userId
userIdstringoptionalThe visitor's user id. Pays every funnel and campaign the visitor (or a linked identity) has assignments in
currencystringoptionalISO currency code, three letters. Defaults to USD
linesArray<{ id?: string; quantity?: number; price: number; discount?: number; unitCost?: number }>optionalLine items, one to 500: unit price, quantity (default 1), the discount on the whole line, and unit cost. Margin is known only when every line has a unitCost
revenuenumberoptionalOrder revenue after discounts, when you send no lines
costnumberoptionalTotal cost of goods, with revenue. Omit when unknown and send the order again once you know it
shippingnumberoptionalShipping the customer paid
shippingCostnumberoptionalWhat the shipping cost you. Shipping counts toward margin only when this is sent

Response data

NameTypeRequiredDescription
orderIdstringrequiredThe order id you sent
creditedbooleanrequiredWhether any funnel or campaign was paid by this call
marginMinornumberrequiredContribution margin in minor currency units (cents)
marginKnownbooleanrequiredFalse while the order waits for its cost
duplicatebooleanrequiredTrue when the order id was already recorded

Responses

201Order recorded
200Order already recorded (duplicate), or a stored uncosted order was resolved
400Validation error
401Missing API key
403Publishable keys cannot record orders
500Server failure; safe to retry

Example

Request

{
  "orderId": "1042",
  "assignmentId": "k57c2f0e3q9m",
  "lines": [
    {
      "id": "mug",
      "quantity": 2,
      "price": 24,
      "unitCost": 9.5
    }
  ],
  "shipping": 6,
  "shippingCost": 4.25
}

Response

{
  "success": true,
  "data": {
    "orderId": "1042",
    "credited": true,
    "marginMinor": 3075,
    "marginKnown": true,
    "duplicate": false
  },
  "timestamp": "2026-11-02T12:00:00.000Z"
}
POST/api/orders/:id/refunds

Record refund

Record a refund on an order sent to POST /api/orders. A funnel or campaign payout is revised down: a `revenue` payout by the amount refunded, a `margin` payout by the margin share of the revenue refunded plus refunded shipping, a `count` payout not at all; the original value stays on the reward as `grossValue`. Refunds are capped in total at the original payout. A refundId already applied is a no-op. Requires a secret API key.

Auth:api-key

Path Parameters

NameTypeRequiredDescription
idstringrequiredThe orderId sent to POST /api/orders

Request Body

NameTypeRequiredDescription
refundIdstringrequiredYour refund id, at most 200 characters. A retry with the same id is ignored
amountnumberrequiredRevenue refunded, after discounts
shippingnumberoptionalShipping refunded

Response data

NameTypeRequiredDescription
orderIdstringrequiredThe order id from the path
appliedbooleanrequiredFalse when the refundId was already applied, the order was not sent through this API, or no payout needed revising
refundedMinornumberrequiredMargin refunded by this call in minor currency units (cents); 0 when not applied

Responses

200Refund applied, or ignored as a duplicate (applied: false)
400Validation error
401Missing API key
403Publishable keys cannot record refunds
404Order not found
500Server failure; safe to retry

Example

Request

{
  "refundId": "r-77",
  "amount": 24
}

Response

{
  "success": true,
  "data": {
    "orderId": "1042",
    "applied": true,
    "refundedMinor": 1538
  },
  "timestamp": "2026-11-02T12:00:00.000Z"
}

Pick sessions

The short-lived session behind the point-and-click experiment picker. The dashboard opens one and hands its bpick_ token to the picker on the customer site, which uses it as a bearer token

GET/api/pick/integrations

List events received from each integration

For the picker goal step. Returns, for each built integration (segment, rudderstack, posthog, shopify), the event names received from it with count and last seen, and whether any carried a value. Also returns the planned integrations this company already asked for. Scoped to the session company.

Auth:pick-token

Response data

NameTypeRequiredDescription
requestedArray<string>requiredPlanned integration ids this company already asked for
events{ segment: { sampled: number; names: Array<{ event: string; count: number; lastSeenAt: number; carriesValue: boolean }> }; rudderstack: { sampled: number; names: Array<{ event: string; count: number; lastSeenAt: number; carriesValue: boolean }> }; posthog: { sampled: number; names: Array<{ event: string; count: number; lastSeenAt: number; carriesValue: boolean }> }; shopify: { sampled: number; names: Array<{ event: string; count: number; lastSeenAt: number; carriesValue: boolean }> } }required

Responses

200Received events by source, and the integration ids already requested
401Missing, unknown, or expired pick token

Example

Response

{
  "success": true,
  "data": {
    "requested": [
      "stripe"
    ],
    "events": {
      "segment": {
        "sampled": 3,
        "names": [
          {
            "event": "Order Completed",
            "count": 3,
            "lastSeenAt": 1790000000000,
            "carriesValue": true
          }
        ]
      },
      "rudderstack": {
        "sampled": 0,
        "names": []
      },
      "posthog": {
        "sampled": 0,
        "names": []
      },
      "shopify": {
        "sampled": 0,
        "names": []
      }
    }
  }
}
POST/api/pick/integrations

Request a planned integration

Records that this company wants a connector that is not built yet, so it can be told when it ships. One row per company and integration, a repeat call only refreshes it. It never creates a goal.

Auth:pick-token

Request Body

NameTypeRequiredDescription
integrationstringrequiredThe id of a planned integration, like stripe or calendly

Response data

NameTypeRequiredDescription
integrationstringrequired
requestedtruerequired

Responses

200The request is recorded
400The id is not a planned integration
401Missing, unknown, or expired pick token

Example

Request

{
  "integration": "stripe"
}

Response

{
  "success": true,
  "data": {
    "integration": "stripe",
    "requested": true
  }
}
POST/api/pick/next

Open a new pick session after Start

Lets the visitor pick another element on the same site without going back to the dashboard. Ends the started session and returns a fresh token with an empty draft for the same funnel. The new session expires at the same hard limit as the first one, never later.

Auth:pick-token

Response data

NameTypeRequiredDescription
tokenstringrequiredThe new bpick_ token
expiresAtnumberrequiredWhen the new session ends, in milliseconds since the epoch

Responses

200The new pick token and when it expires
400This session has not started its experiment yet
401Missing, unknown, or expired pick token

Example

Response

{
  "success": true,
  "data": {
    "token": "bpick_3f9a1c0d5e7b24681a3c5e7f9b0d2f4a6c8e0b1d3f5a7c9e",
    "expiresAt": 1790000000000
  }
}
GET/api/pick/session

Get the pick session state

Returns the draft the visitor is building, the funnel goal, and the experiment id once Start has run. The site script also calls this from the customer site to check that a token is still valid, so it allows any origin. Every call needs the pick token as a bearer token.

Auth:pick-token

Response data

NameTypeRequiredDescription
funnelIdstringrequired
payoutUnit"count" | "revenue" | "margin"required
siteHoststringrequired
expiresAtnumberrequiredWhen the session ends, in milliseconds since the epoch
draft{ target?: { page: string; selector: string; tag: string; kind: "text" | "image" | "order"; original: string }; alternatives: Array<string>; goal?: { kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" } }required
funnelGoal{ kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" } | nullrequiredThe goal already saved on the funnel, or null
experimentIdstring | nullrequiredSet once Start has run
runningExperimentsnumberrequired

Responses

200The session state
401Missing, unknown, or expired pick token

Example

Response

{
  "success": true,
  "data": {
    "funnelId": "k17abc123",
    "payoutUnit": "count",
    "siteHost": "example.com",
    "expiresAt": 1790000000000,
    "draft": {
      "target": {
        "page": "/",
        "selector": "main > h1",
        "tag": "h1",
        "kind": "text",
        "original": "Grow your business"
      },
      "alternatives": [
        "Double your sales"
      ]
    },
    "funnelGoal": null,
    "experimentId": null,
    "runningExperiments": 0
  }
}
PUT/api/pick/session

Save the pick draft

Each field you send replaces that part of the draft. Picking a different element (a different selector or kind) clears the alternatives. Every save extends the session by 30 minutes, up to 2 hours after it opened. Returns the whole new state.

Auth:pick-token

Request Body

NameTypeRequiredDescription
target{ page: string; selector: string; tag: string; kind: "text" | "image" | "order"; original: string }optionalThe picked element: page, selector, tag, kind (text, image or order), original
alternativesArray<string>optionalThe options to try against the original. Up to 20 are accepted here and a draft that keeps more than 5 is rejected with a message the visitor can read. Image options are https URLs
goal{ kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" }optionalWhat counts as a win: a page visit ({ kind: "page", page }) or a click ({ kind: "click", page, selector, tag, label }), or an integration event ({ kind: "event", event, valueProperty?, source? })

Response data

NameTypeRequiredDescription
funnelIdstringrequired
payoutUnit"count" | "revenue" | "margin"required
siteHoststringrequired
expiresAtnumberrequiredWhen the session ends, in milliseconds since the epoch
draft{ target?: { page: string; selector: string; tag: string; kind: "text" | "image" | "order"; original: string }; alternatives: Array<string>; goal?: { kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" } }required
funnelGoal{ kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" } | nullrequiredThe goal already saved on the funnel, or null
experimentIdstring | nullrequiredSet once Start has run
runningExperimentsnumberrequired

Responses

200The new session state
400A field is invalid, with a message the visitor can read
401Missing, unknown, or expired pick token
410The experiment has already started, so the draft is closed

Example

Request

{
  "alternatives": [
    "Double your sales"
  ]
}

Response

{
  "success": true,
  "data": {
    "funnelId": "k17abc123",
    "payoutUnit": "count",
    "siteHost": "example.com",
    "expiresAt": 1790000000000,
    "draft": {
      "target": {
        "page": "/",
        "selector": "main > h1",
        "tag": "h1",
        "kind": "text",
        "original": "Grow your business"
      },
      "alternatives": [
        "Double your sales"
      ]
    },
    "funnelGoal": null,
    "experimentId": null,
    "runningExperiments": 0
  }
}
POST/api/pick/start

Start the picked experiment

Creates the experiment as active in the setup funnel, with the original as Control and each alternative as an option, and saves the draft goal on the funnel. Safe to repeat: a second call returns the same experiment. Needs an element, at least one alternative, and a goal on the draft or the funnel.

Auth:pick-token

Response data

NameTypeRequiredDescription
experimentIdstringrequired
state{ funnelId: string; payoutUnit: "count" | "revenue" | "margin"; siteHost: string; expiresAt: number; draft: { target?: { page: string; selector: string; tag: string; kind: "text" | "image" | "order"; original: string }; alternatives: Array<string>; goal?: { kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" } }; funnelGoal: { kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: "segment" | "rudderstack" | "posthog" | "shopify" } | null; experimentId: string | null; runningExperiments: number }required

Responses

200The experiment id and the session state
400The draft is missing an element, an alternative, or a goal
401Missing, unknown, or expired pick token
409An active experiment already tests that element on that page

Example

Response

{
  "success": true,
  "data": {
    "experimentId": "jx7def456",
    "state": {
      "funnelId": "k17abc123",
      "payoutUnit": "count",
      "siteHost": "example.com",
      "expiresAt": 1790000000000,
      "draft": {
        "target": {
          "page": "/",
          "selector": "main > h1",
          "tag": "h1",
          "kind": "text",
          "original": "Grow your business"
        },
        "alternatives": [
          "Double your sales"
        ],
        "goal": {
          "kind": "page",
          "page": "/thank-you"
        }
      },
      "funnelGoal": {
        "kind": "page",
        "page": "/thank-you"
      },
      "experimentId": "jx7def456",
      "runningExperiments": 1
    }
  }
}
POST/api/pick/upload

Get a signed URL to upload an image alternative

Returns a short-lived URL to PUT an image file to, and the public URL to use as the alternative once the upload finishes. Images only, up to 10MB. The file is stored under the session company.

Auth:pick-token

Request Body

NameTypeRequiredDescription
filenamestringrequiredFile name with an extension, like hero.png
contentTypestringrequiredMIME type, which must start with image/
sizenumberrequiredFile size in bytes

Response data

NameTypeRequiredDescription
uploadUrlstringrequiredShort-lived URL to PUT the file to
publicUrlstringrequiredThe URL to use as the alternative once the upload finishes
keystringrequiredThe storage key

Responses

200The upload URL, the public URL, and the storage key
400Not an image, too large, or missing an extension
401Missing, unknown, or expired pick token
503Upload storage is not configured

Example

Request

{
  "filename": "hero.png",
  "contentType": "image/png",
  "size": 48211
}

Response

{
  "success": true,
  "data": {
    "uploadUrl": "https://account.r2.cloudflarestorage.com/bucket/companies/k1/abc.png?X-Amz-Signature=...",
    "publicUrl": "https://assets.runbandit.com/companies/k1/abc.png",
    "key": "companies/k1/abc.png"
  }
}

Setup

Check how far a company is through installing Bandit and launching its first experiment

GET/api/setup/status

Get setup progress

Returns the ordered setup stages (funnel_created, sdk_seen, experiment_created, treatments_added, experiment_started, serving, conversion_tracked), whether each one is done, and the instruction for the first stage that is not. `bandit doctor` prints this after a line confirming the CLI is linked.

Auth:pat

Response data

NameTypeRequiredDescription
stagesArray<{ id: "funnel_created" | "sdk_seen" | "experiment_created" | "treatments_added" | "experiment_started" | "serving" | "conversion_tracked"; label: string; done: boolean; instruction: string }>required
currentStageId"funnel_created" | "sdk_seen" | "experiment_created" | "treatments_added" | "experiment_started" | "serving" | "conversion_tracked" | nullrequiredThe first stage that is not done, or null when setup is complete
completebooleanrequired
domainstring | nullrequiredThe saved site address, or null
setup{ goal?: string; stack: string; funnelId?: string; conversionPath?: string } | nullrequiredThe platform and setup funnel chosen on /setup, or null
funnelGoal{ kind: "page"; page: string } | { kind: "click"; page: string; selector: string; tag: string; label: string } | { kind: "event"; event: string; valueProperty?: string; source?: string } | nullrequiredThe setup funnel goal, null until one is set
seenHostsArray<string>requiredHosts the script has been seen on
siteOriginstring | nullrequiredThe origin of the site as last seen with the script, null until a visit on the saved domain arrives
lastSeenOriginstring | nullrequiredThe origin of the most recent visit on any host, or null
runningExperimentsnumberrequiredExperiments that are parented and active
shopifyPixelOutdatedbooleanrequiredTrue when a Shopify theme setup has rewards but its purchase pixel has never reported

Responses

200Stages, the current stage id, whether setup is complete, the setup funnel goal (null until one is set), the origin of the site as last seen with the script (null until a visit on the saved domain arrives), and how many experiments are running (parented and active)
401Missing or invalid token
404Company not found, or the company is a demo company

Example

Response

{
  "success": true,
  "data": {
    "stages": [
      {
        "id": "funnel_created",
        "label": "Site saved",
        "done": true,
        "instruction": "Choose your platform and enter your site address on /setup, which saves your site and creates your setup funnel."
      }
    ],
    "currentStageId": "sdk_seen",
    "complete": false,
    "domain": "example.com",
    "setup": {
      "stack": "webflow",
      "funnelId": "k17abc123"
    },
    "funnelGoal": {
      "kind": "page",
      "page": "/thank-you"
    },
    "seenHosts": [
      "localhost"
    ],
    "siteOrigin": null,
    "lastSeenOrigin": null,
    "runningExperiments": 0,
    "shopifyPixelOutdated": false
  }
}