> For the complete documentation index, see [llms.txt](https://developers.gleantap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.gleantap.com/api-reference-v3/campaigns.md).

# Campaigns

One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split.

## List campaigns.

> Paginated list. Common filters: \`?filter\[status]=scheduled\`, \`?filter\[channel]=email\`, \`?filter\[created\_at]\[gte]=...\`. Archived campaigns (see \`POST /v3/campaigns/{id}/archive\`) are excluded by default — pass \`?filter\[include\_archived]=true\` to include them. Rate limit bucket: \`read\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:read"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}},"LimitParam":{"name":"limit","in":"query","required":false,"description":"Page size. Default 25, max 100.","schema":{"type":"integer","minimum":1,"maximum":100,"default":25}},"CursorParam":{"name":"cursor","in":"query","required":false,"description":"Opaque cursor from a prior response's `next_cursor`, to fetch the NEXT page (alias - `after`). On listContacts and listSegmentContacts, use `before` with a `prev_cursor` to page backward; other list endpoints are forward-only.","schema":{"type":"string"}},"SortParam":{"name":"sort","in":"query","required":false,"description":"Comma-separated list of fields to sort by. Leading `-` reverses. Default `-created_at`. Sortable fields vary per resource; unsortable fields return 400 `invalid_sort_field`.\n","schema":{"type":"string"}},"FieldsParam":{"name":"fields","in":"query","required":false,"description":"Sparse fieldset — comma-separated list of fields to include in the response. Reduces payload size on high-volume reads. Nested field access is not supported; request the parent object.\n","schema":{"type":"string"}}},"schemas":{"ListEnvelope":{"type":"object","required":["object","data","has_more","next_cursor","prev_cursor"],"properties":{"object":{"type":"string","const":"list"},"data":{"type":"array","items":{"type":"object"},"description":"The page of results. Item type varies per endpoint — see the specific response schema."},"has_more":{"type":"boolean","description":"True if additional records exist beyond this page."},"next_cursor":{"type":"string","nullable":true,"description":"Opaque cursor for the next page. Null on the last page."},"prev_cursor":{"type":"string","nullable":true,"description":"Cursor for the previous page. Supported on `listContacts` and `listSegmentContacts`: pass it back as `?before=...` to page backward; `null` on the first page. On every other list endpoint paging is forward-only and this is always `null`."}}},"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}}}},"paths":{"/campaigns":{"get":{"tags":["Campaigns"],"operationId":"listCampaigns","summary":"List campaigns.","description":"Paginated list. Common filters: `?filter[status]=scheduled`, `?filter[channel]=email`, `?filter[created_at][gte]=...`. Archived campaigns (see `POST /v3/campaigns/{id}/archive`) are excluded by default — pass `?filter[include_archived]=true` to include them. Rate limit bucket: `read`.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/CursorParam"},{"$ref":"#/components/parameters/SortParam"},{"$ref":"#/components/parameters/FieldsParam"},{"name":"filter","in":"query","style":"deepObject","explode":true,"schema":{"type":"object","additionalProperties":{"type":"string"}}}],"responses":{"200":{"description":"A page of campaigns.","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListEnvelope"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Campaign"}}}}]}}}}}}}}}
```

## Create a draft campaign.

> Creates a \`draft\` campaign. Nothing sends until you call \`POST /v3/campaigns/{id}/schedule\` or \`/send\_now\`. Referenced \`template\_id\` must exist and match \`channel\` at send time.\
> \
> \*\*Content is required unless the caller is intentionally creating a stub.\*\* For \`channel: "email"\` provide \`subject\` + \`message\_body\` (or \`template\_id\`). For \`channel: "sms"\` provide \`message\_body\` (or \`template\_id\`). Campaign channels are \`sms\` and \`email\` only. A campaign needs finished copy: \`subject\` and \`message\_body\` are what gets delivered, and a campaign saved with them blank or stubbed sends that placeholder text. \`from\_phone\_number\` / \`from\_name\` / \`from\_email\` inherit from the workroom's app defaults when omitted. For SMS, \`from\_phone\_number\` selects the sending number; omitted, it falls back to the workroom default. \`listWorkroomPhoneNumbers\` returns the usable numbers.\
> \
> Requires the audience, the content and when it should send. Optional fields fall back to a server-side default when omitted. That includes the workroom: an omitted workroom resolves to the account default, and a record created in the wrong workroom is invisible where it was expected. Half-specified records are created successfully and then have to be hunted down and fixed by hand.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}},"IdempotencyKey":{"name":"Idempotency-Key","in":"header","required":false,"description":"A unique key (≤255 chars) chosen by the client. Replays with the same key + same body return the cached response. Replays with the same key + different body return 409 `idempotency_conflict`. Required on messaging sends and bulk operations; recommended elsewhere.\n","schema":{"type":"string","maxLength":255}}},"schemas":{"CampaignCreate":{"type":"object","required":["name","channel","audience"],"if":{"properties":{"channel":{"const":"email"}},"required":["channel"]},"then":{"required":["objective"]},"description":"Creates a `drafted` campaign. Nothing is sent until `POST /v3/campaigns/{id}/schedule` or `/send_now` is called. Provide either `template_id` (reference a template) OR `message_body` (inline content); not both.\n\nContent is required for `email` and `sms` campaigns: pass `template_id` or `message_body`. When `template_id` is given, the template's saved body is copied onto the campaign at create time (the send path reads the campaign's own stored content, not the template reference), so the referenced template must have a non-empty body. If content can't be resolved (no `message_body` and the template is missing or empty), the request fails `422 validation_failed` — a campaign is never created with an empty body.\n\n`channel` must be `sms` or `email`. `voice` is rejected with `422`: no send worker delivers voice campaigns (use `POST /v3/messages` for individual calls). Push does not exist in Gleantap.\n\n`objective` is required for `channel: \"email\"` campaigns and ignored for SMS.\n","properties":{"name":{"type":"string","maxLength":200},"channel":{"type":"string","enum":["sms","email"],"description":"Campaign channel. `voice` is rejected (no campaign send worker for it); push does not exist."},"template_id":{"$ref":"#/components/schemas/TemplateId"},"message_body":{"type":"string","description":"SMS campaigns: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. A longer body (inline or copied from `template_id`) is rejected with 422 `validation_failed`."},"message_title":{"type":"string"},"subject":{"type":"string","description":"Email subject line (alias for message_title on email campaigns). Legacy column: subject."},"objective":{"type":"string","description":"Campaign objective / category (matches the dashboard's objective picker). Legacy column: campaign_objective.","enum":["Feedback / Review","Lead Engagement","Milestone","Nuture Customer","Referral","Survey","Up-sell / Cross-sell","Welcome","Win Back","Promotional","Newsletter / Announcement","Other"]},"from_phone_number":{"type":"string","description":"E.164 sender phone for SMS/voice. When omitted it resolves to the workroom's default number (the `phone_numbers` row marked `is_default_number`, else the app's provider number). If the workroom has more than one usable number and none is clearly the intended sender, do NOT guess — call `listWorkroomPhoneNumbers` and confirm which one with the user, then pass the chosen E.164 value here."},"from_email":{"type":"string","format":"email","description":"Email only. Sender address. Inherits the workroom's email-settings default when omitted. Must be a valid email address, and its domain must be verified for this account if it's a registered custom domain (a shared/Gleantap-managed domain is always allowed)."},"from_name":{"type":"string","description":"Email only. Sender display name. Inherits the workroom's email-settings default when omitted."},"reply_to":{"type":"string","format":"email","description":"Email only. Reply-To address. Inherits the workroom's reply_to_email / default_email / from_email when omitted. Must be a valid email address."},"reply_to_name":{"type":"string","description":"Email only. Reply-To display name. Defaults to the sender name when omitted."},"attachment_url":{"type":"string","format":"uri","description":"MMS attachment URL."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"ab_test":{"$ref":"#/components/schemas/CampaignABTest"},"label":{"type":"string"},"tags":{"type":"array","items":{"type":"string"}}}},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"BadRequest":{"description":"Request could not be parsed or failed validation.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Unprocessable":{"description":"Semantic validation failed — the request is well-formed but references an object in the wrong state (e.g., sending to an opted-out contact).","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns":{"post":{"tags":["Campaigns"],"operationId":"createCampaign","summary":"Create a draft campaign.","description":"Creates a `draft` campaign. Nothing sends until you call `POST /v3/campaigns/{id}/schedule` or `/send_now`. Referenced `template_id` must exist and match `channel` at send time.\n\n**Content is required unless the caller is intentionally creating a stub.** For `channel: \"email\"` provide `subject` + `message_body` (or `template_id`). For `channel: \"sms\"` provide `message_body` (or `template_id`). Campaign channels are `sms` and `email` only. A campaign needs finished copy: `subject` and `message_body` are what gets delivered, and a campaign saved with them blank or stubbed sends that placeholder text. `from_phone_number` / `from_name` / `from_email` inherit from the workroom's app defaults when omitted. For SMS, `from_phone_number` selects the sending number; omitted, it falls back to the workroom default. `listWorkroomPhoneNumbers` returns the usable numbers.\n\nRequires the audience, the content and when it should send. Optional fields fall back to a server-side default when omitted. That includes the workroom: an omitted workroom resolves to the account default, and a record created in the wrong workroom is invisible where it was expected. Half-specified records are created successfully and then have to be hunted down and fixed by hand.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CampaignCreate"}}}},"responses":{"201":{"description":"Draft campaign created.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Retrieve a campaign.

> Includes current \`stats\` and status. Use \`?expand=template,audience.segment\` to inline related resources (\`segments\` also accepted as a shorthand for \`audience.segment\`). Expanded fields are always included even if \`?fields=\` doesn't list them.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:read"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}},"FieldsParam":{"name":"fields","in":"query","required":false,"description":"Sparse fieldset — comma-separated list of fields to include in the response. Reduces payload size on high-volume reads. Nested field access is not supported; request the parent object.\n","schema":{"type":"string"}},"ExpandParam":{"name":"expand","in":"query","required":false,"description":"Comma-separated list of related resources to inline in the response. Without `expand`, a related field is just the ID string. With `expand`, it's the full sub-object. Up to two levels deep; max 4 expansions per request.\n","schema":{"type":"string"}}},"schemas":{"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}":{"get":{"tags":["Campaigns"],"operationId":"retrieveCampaign","summary":"Retrieve a campaign.","description":"Includes current `stats` and status. Use `?expand=template,audience.segment` to inline related resources (`segments` also accepted as a shorthand for `audience.segment`). Expanded fields are always included even if `?fields=` doesn't list them.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/FieldsParam"},{"$ref":"#/components/parameters/ExpandParam"}],"responses":{"200":{"description":"The campaign.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Update a campaign.

> Campaigns in \`drafted\` or \`paused\` status can edit any field; once launched only \`name\`, \`label\`, and \`tags\` are editable. \`channel\` and \`template\_id\` are immutable — create a new campaign. Returns 409 \`campaign\_locked\` otherwise (cancel first to unlock).<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"CampaignUpdate":{"type":"object","description":"Partial update. Campaigns in `drafted` or `paused` status can edit any field; once launched only `name`, `label`, and `tags` are editable — 409 `campaign_locked` otherwise. Cancel first to unlock.\n","properties":{"name":{"type":"string","maxLength":200},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true},"message_body":{"type":"string","nullable":true,"description":"SMS campaigns: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. A longer body (inline or copied from `template_id`) is rejected with 422 `validation_failed`."},"message_title":{"type":"string","nullable":true},"subject":{"type":"string","nullable":true,"description":"Email subject line (alias for message_title). Legacy column: subject."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (matches the dashboard's objective picker). Legacy column: campaign_objective.","enum":["Feedback / Review","Lead Engagement","Milestone","Nuture Customer","Referral","Survey","Up-sell / Cross-sell","Welcome","Win Back","Promotional","Newsletter / Announcement","Other"]},"from_phone_number":{"type":"string","nullable":true},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Omitting leaves the stored value unchanged — workroom defaults are NOT re-resolved on update. Must be a valid email address, and its domain must be verified for this account if it's a registered custom domain."},"from_name":{"type":"string","nullable":true,"description":"Email only. Omitting leaves the stored value unchanged — workroom defaults are NOT re-resolved on update."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Omitting leaves the stored value unchanged — workroom defaults are NOT re-resolved on update. Must be a valid email address."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Omitting leaves the stored value unchanged."},"attachment_url":{"type":"string","format":"uri","nullable":true},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"label":{"type":"string","nullable":true},"tags":{"type":"array","items":{"type":"string"}}}},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"BadRequest":{"description":"Request could not be parsed or failed validation.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Conflict":{"description":"Idempotency conflict, version conflict (`If-Match`), or state conflict.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Unprocessable":{"description":"Semantic validation failed — the request is well-formed but references an object in the wrong state (e.g., sending to an opted-out contact).","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}":{"patch":{"tags":["Campaigns"],"operationId":"updateCampaign","summary":"Update a campaign.","description":"Campaigns in `drafted` or `paused` status can edit any field; once launched only `name`, `label`, and `tags` are editable. `channel` and `template_id` are immutable — create a new campaign. Returns 409 `campaign_locked` otherwise (cancel first to unlock).\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CampaignUpdate"}}}},"responses":{"200":{"description":"Updated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Hard-delete a draft or paused campaign.

> Only \`drafted\` and \`paused\` campaigns can be deleted this way — this is a permanent, irreversible hard delete (no audit copy), not an archive. Every other status (\`upcoming\`, \`scheduled\`, \`ongoing\`, \`sending\`, \`sent\`, \`failed\`, \`archived\`) returns 409 \`campaign\_locked\`; use \`POST /v3/campaigns/{id}/archive\` instead to retire a campaign that isn't a draft or paused, or \`POST /v3/campaigns/{id}/cancel\` first to pause a scheduled/sending/ongoing one before deleting.\
> \
> \*\*Permanent.\*\* There is no undo and no trash to restore from. Anything that references the deleted record is affected too.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Conflict":{"description":"Idempotency conflict, version conflict (`If-Match`), or state conflict.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}},"schemas":{"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}}},"paths":{"/campaigns/{id}":{"delete":{"tags":["Campaigns"],"operationId":"deleteCampaign","summary":"Hard-delete a draft or paused campaign.","description":"Only `drafted` and `paused` campaigns can be deleted this way — this is a permanent, irreversible hard delete (no audit copy), not an archive. Every other status (`upcoming`, `scheduled`, `ongoing`, `sending`, `sent`, `failed`, `archived`) returns 409 `campaign_locked`; use `POST /v3/campaigns/{id}/archive` instead to retire a campaign that isn't a draft or paused, or `POST /v3/campaigns/{id}/cancel` first to pause a scheduled/sending/ongoing one before deleting.\n\n**Permanent.** There is no undo and no trash to restore from. Anything that references the deleted record is affected too.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"204":{"description":"Deleted."},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}}}}
```

## Schedule a draft campaign.

> Transitions status from \`draft\` to \`scheduled\` and locks the definition. \`send\_at\` must be in the future (at least 1 min out). An offset-less \`send\_at\` is interpreted in the account's own configured timezone and converted to UTC automatically — see its own schema description for the exact rule; there is no recipient-local scheduling option.\
> \
> \*\*Goes live.\*\* Once live it keeps reaching real contacts on its own, with no further call.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"CampaignScheduleRequest":{"type":"object","required":["mode"],"description":"Body for `POST /v3/campaigns/{id}/schedule`. For \"send right now\" use `POST /send_now` instead (which is equivalent to `mode: immediate` with `send_at: now`).\n\n**`send_at` without an explicit offset is interpreted in the account's own configured timezone, not UTC.** See `send_at`'s own description below for the exact rule.\n","properties":{"mode":{"type":"string","enum":["scheduled","ongoing"],"description":"- `scheduled` — send at a specific future `send_at`.\n- `ongoing` — recurring send (weekly/daily/etc.) driven by `frequency` + optional `days_of_week`.\n"},"send_at":{"type":"string","format":"date-time","description":"RFC 3339 timestamp. Required when `mode: \"scheduled\"`. Must be in the future (at least 1 min out).\n\nRead back as `schedule.send_at`, always the real UTC instant. (Storage note: for `scheduled`, the legacy `date_time` holds the workroom-local wall clock written as if it were UTC, plus `time` — exactly what the dashboard writes and the send worker reads. Don't compare raw `date_time` values to real instants.)\n\n**An offset-less value (no `+HH:MM`, `-HH:MM`, or `Z`) is interpreted in the scheduling timezone — the workroom's timezone, else the account's configured timezone (Settings), the same one the send worker uses — and converted to UTC automatically — send the local wall-clock time the user asked for as-is, with no manual conversion needed.** E.g. `\"2026-09-16T20:00:00\"` for \"8pm\" schedules 8pm in whatever timezone the account has configured, not 8pm UTC. If you include an explicit offset or `Z`, it's always honored exactly as given and overrides the account's timezone — use this when you already know the intended instant precisely (e.g. `\"2026-09-16T14:30:00Z\"`) rather than relying on account defaults.\n"},"frequency":{"type":"string","enum":["daily","multiple","once","weekly"],"default":"daily","description":"For `ongoing`. The send worker knows exactly two behaviors:\n  - `daily` — once per run day, at `send_at`'s time of day. `once` and `weekly` are accepted aliases (`weekly` requires `days_of_week`). Read back as `daily`.\n  - `multiple` — continuously throughout the day, on every worker run.\nWhich days run is `days_of_week`. Monthly recurrence is not supported (`422`).\n"},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"For `ongoing`. Omitted = every day (all seven are stored explicitly — the worker skips Sunday when none are stored). Stored as the worker's `Mon`…`Sun` tokens."}}},"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"BadRequest":{"description":"Request could not be parsed or failed validation.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Conflict":{"description":"Idempotency conflict, version conflict (`If-Match`), or state conflict.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Unprocessable":{"description":"Semantic validation failed — the request is well-formed but references an object in the wrong state (e.g., sending to an opted-out contact).","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/schedule":{"post":{"tags":["Campaigns"],"operationId":"scheduleCampaign","summary":"Schedule a draft campaign.","description":"Transitions status from `draft` to `scheduled` and locks the definition. `send_at` must be in the future (at least 1 min out). An offset-less `send_at` is interpreted in the account's own configured timezone and converted to UTC automatically — see its own schema description for the exact rule; there is no recipient-local scheduling option.\n\n**Goes live.** Once live it keeps reaching real contacts on its own, with no further call.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CampaignScheduleRequest"}}}},"responses":{"200":{"description":"Scheduled.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Send a campaign immediately.

> Transitions \`drafted\` → \`upcoming\` (the worker picks it up and moves it to \`sending\` shortly after - status won't read \`sending\` instantly). Returns immediately; delivery happens asynchronously. Subscribe to \`campaign.sending\` / \`campaign.sent\` / \`campaign.failed\` webhooks. \`Idempotency-Key\` is strongly recommended.\
> \
> \*\*Sends to real people the moment it is called.\*\* There is no recall. Reaches the full audience of the target segment or campaign. The test-send operations deliver to a single address instead.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write","messaging:send"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}},"IdempotencyKey":{"name":"Idempotency-Key","in":"header","required":false,"description":"A unique key (≤255 chars) chosen by the client. Replays with the same key + same body return the cached response. Replays with the same key + different body return 409 `idempotency_conflict`. Required on messaging sends and bulk operations; recommended elsewhere.\n","schema":{"type":"string","maxLength":255}}},"schemas":{"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Conflict":{"description":"Idempotency conflict, version conflict (`If-Match`), or state conflict.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Unprocessable":{"description":"Semantic validation failed — the request is well-formed but references an object in the wrong state (e.g., sending to an opted-out contact).","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"TooManyRequests":{"description":"Rate limited.","headers":{"Retry-After":{"$ref":"#/components/headers/RetryAfter"}},"content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}},"headers":{"RetryAfter":{"description":"On 429, seconds to wait before retrying.","schema":{"type":"integer"}}}},"paths":{"/campaigns/{id}/send_now":{"post":{"tags":["Campaigns"],"operationId":"sendCampaignNow","summary":"Send a campaign immediately.","description":"Transitions `drafted` → `upcoming` (the worker picks it up and moves it to `sending` shortly after - status won't read `sending` instantly). Returns immediately; delivery happens asynchronously. Subscribe to `campaign.sending` / `campaign.sent` / `campaign.failed` webhooks. `Idempotency-Key` is strongly recommended.\n\n**Sends to real people the moment it is called.** There is no recall. Reaches the full audience of the target segment or campaign. The test-send operations deliver to a single address instead.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/IdempotencyKey"}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"throttle":{"type":"object","properties":{"messages_per_minute":{"type":"integer","minimum":1,"maximum":10000}}}}}}}},"responses":{"202":{"description":"Send started.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"},"422":{"$ref":"#/components/responses/Unprocessable"},"429":{"$ref":"#/components/responses/TooManyRequests"}}}}}}
```

## Cancel a scheduled or sending campaign.

> Cancels an \`upcoming\` campaign before the cron picks it up (e.g. a \`send\_now\` still waiting out quiet hours), a \`scheduled\` campaign before it starts, an \`ongoing\` campaign, or a \`sending\` campaign mid-send (already-queued messages continue to deliver — no rollback). Canceling moves the campaign to \`paused\` and clears its schedule - there is no separate \`canceled\` status. Terminal-state campaigns (\`sent\`, \`failed\`) return 409.\
> \
> \*\*Affects something real.\*\* This cancels a scheduled send or a booking a person is expecting.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Conflict":{"description":"Idempotency conflict, version conflict (`If-Match`), or state conflict.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/cancel":{"post":{"tags":["Campaigns"],"operationId":"cancelCampaign","summary":"Cancel a scheduled or sending campaign.","description":"Cancels an `upcoming` campaign before the cron picks it up (e.g. a `send_now` still waiting out quiet hours), a `scheduled` campaign before it starts, an `ongoing` campaign, or a `sending` campaign mid-send (already-queued messages continue to deliver — no rollback). Canceling moves the campaign to `paused` and clears its schedule - there is no separate `canceled` status. Terminal-state campaigns (`sent`, `failed`) return 409.\n\n**Affects something real.** This cancels a scheduled send or a booking a person is expecting.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"reason":{"type":"string","maxLength":500}}}}}},"responses":{"200":{"description":"Canceled.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}}}}
```

## Duplicate a campaign.

> Creates a new \`draft\` campaign with the same template, audience, and A/B config as the source. Schedule and stats are NOT copied.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/duplicate":{"post":{"tags":["Campaigns"],"operationId":"duplicateCampaign","summary":"Duplicate a campaign.","description":"Creates a new `draft` campaign with the same template, audience, and A/B config as the source. Schedule and stats are NOT copied.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"requestBody":{"required":false,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","description":"Name for the duplicate. Defaults to `\"<source name> (copy)\"`."}}}}}},"responses":{"201":{"description":"Duplicate created.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Archive a campaign.

> Soft-archives the campaign: sets \`status\` to \`archived\` and reversibly hides it from \`GET /v3/campaigns\` unless \`?filter\[include\_archived]=true\` is passed. Unlike \`DELETE /v3/campaigns/{id}\`, this works from ANY lifecycle status — including \`sent\`, \`paused\`, and \`failed\` — so a campaign's history is never lost. The campaign's prior status is remembered internally and restored exactly by \`POST /v3/campaigns/{id}/unarchive\`. Idempotent — archiving an already-archived campaign is a no-op that returns its current state.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/archive":{"post":{"tags":["Campaigns"],"operationId":"archiveCampaign","summary":"Archive a campaign.","description":"Soft-archives the campaign: sets `status` to `archived` and reversibly hides it from `GET /v3/campaigns` unless `?filter[include_archived]=true` is passed. Unlike `DELETE /v3/campaigns/{id}`, this works from ANY lifecycle status — including `sent`, `paused`, and `failed` — so a campaign's history is never lost. The campaign's prior status is remembered internally and restored exactly by `POST /v3/campaigns/{id}/unarchive`. Idempotent — archiving an already-archived campaign is a no-op that returns its current state.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Archived.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Restore an archived campaign.

> Reverses \`POST /v3/campaigns/{id}/archive\`: clears the archived state, restores \`status\` to whatever it was immediately before archiving (falls back to \`drafted\` if that isn't known — e.g. a campaign archived before this field existed), and makes the campaign visible again in \`GET /v3/campaigns\`'s default list. Idempotent — unarchiving a campaign that isn't archived is a no-op that returns its current state.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"Campaign":{"type":"object","required":["id","object","name","channel","audience","status","stats","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/CampaignId"},"object":{"type":"string","const":"campaign"},"name":{"type":"string","maxLength":200},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/CampaignStatus"},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true,"description":"The template used for content. On create/update the template's saved body is copied onto the campaign's own content (`message_details`) — the send path reads that, not this reference. Mutually exclusive with `message_body` (use one or the other)."},"message_body":{"type":"string","nullable":true,"description":"Inline message body — HTML for email, plain text for SMS/voice. Alternative to `template_id`; ignored if `template_id` is set (the template supplies the body). Legacy column: `message_details`. SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded."},"message_title":{"type":"string","nullable":true,"description":"Push/SMS message title; email subject line. Legacy column: `message_title`."},"subject":{"type":"string","nullable":true,"description":"Email subject line (mirrors `message_title` for email campaigns). Legacy column: `subject`."},"objective":{"type":"string","nullable":true,"description":"Campaign objective / category (dashboard picker values: Feedback / Review, Lead Engagement, Milestone, Nuture Customer, Referral, Survey, Up-sell / Cross-sell, Welcome, Win Back, Promotional, Newsletter / Announcement, Other). Not enum-constrained on read so older/free-form values still round-trip. Legacy column: `campaign_objective`."},"from_phone_number":{"type":"string","nullable":true,"description":"SMS/voice only. Sender phone (E.164). Legacy column: `fromnumber`. NOT a v3 PhoneNumber resource ID — a raw phone string."},"from_email":{"type":"string","format":"email","nullable":true,"description":"Email only. Sender address. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_email`."},"from_name":{"type":"string","nullable":true,"description":"Email only. Sender display name. Resolved from the workroom's email-settings default at creation time when omitted. Legacy column: `from_name`."},"reply_to":{"type":"string","format":"email","nullable":true,"description":"Email only. Reply-To address. Resolved at creation time from the workroom's reply_to_email / default_email / from_email when omitted. Legacy column: `reply_to`."},"reply_to_name":{"type":"string","nullable":true,"description":"Email only. Reply-To display name. Defaults to the sender name when omitted. Legacy column: `reply_to_name`."},"attachment_url":{"type":"string","format":"uri","nullable":true,"description":"MMS attachment URL. Legacy column: `full_path`."},"audience":{"$ref":"#/components/schemas/CampaignAudience"},"schedule":{"$ref":"#/components/schemas/CampaignSchedule","nullable":true},"ab_test":{"$ref":"#/components/schemas/CampaignABTest","nullable":true},"stats":{"$ref":"#/components/schemas/CampaignStats"},"label":{"type":"string","nullable":true,"description":"Optional organizational label (dashboard's campaign labels feature)."},"tags":{"type":"array","items":{"type":"string"},"description":"Campaign-level tags (not contact tags)."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"scheduled_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"started_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"completed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"archived_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set when the campaign was archived (`POST /v3/campaigns/{id}/archive`); `null` otherwise. Its presence is what drives status `archived`."}}},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"CampaignStatus":{"type":"string","enum":["drafted","upcoming","scheduled","ongoing","sending","sent","paused","failed","archived"],"description":"Derived from the legacy `campaign` doc's (status, schedule, date_time) triple. Values mirror the dashboard UI:\n  - `drafted` — created, not launched.\n  - `upcoming` — Send ASAP or Specific Date & Time; queued for the worker.\n  - `scheduled` — Specific Date & Time with `date_time` in the future (view-only convenience derived from `upcoming`).\n  - `ongoing` — recurring send (weekly/daily/etc.). Also the legacy `recurring` status.\n  - `sending` — worker is actively dispatching. Also the dashboard's `optimized_sending`.\n  - `sent` — completed.\n  - `paused` — canceled/paused by the user. Stored as the dashboard's own `pause` token (legacy docs may also carry `paused`); both read as `paused`.\n  - `failed` — send worker errored terminally.\n  - `archived` — archived via `POST /v3/campaigns/{id}/archive` (or the dashboard's own Archive action). Takes priority over whatever the campaign's status was before archiving; restored to that prior status by `POST /v3/campaigns/{id}/unarchive`.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"CampaignAudience":{"type":"object","required":["type"],"description":"Discriminated on `type`. Only the field matching `type` should be set:\n  - `segment` → set `segment_ids` (array, at least 1). Every id must be an existing segment in this account. Optionally set `exclude_segment_ids` to leave out members of other segments (the dashboard's \"Exclude Segments\").\n  - `contact_ids` → set `contact_ids` (array, at least 1). Every id must be an existing contact in this account.\nLegacy storage is a single `segment` array of DSL conditions; v3 hydrates it back to this shape on read. `segment` uses `{segment: \"Segments\", operator: \"Is In Segment\"}` with every included id, followed (when `exclude_segment_ids` is set) by one `{segment: \"Segments\", operator: \"Is Not In Segment\"}` condition with every excluded id, plus `excludedFlag: 1` - exactly what the dashboard campaign editor saves, so campaigns created in either place read back the same way. `audience` is replaced as a whole on PATCH: send `exclude_segment_ids` again (or `[]` to clear it) whenever you send `audience`. `contact_ids` uses `{segment: \"Manual Segment Users\", operator: \"Having\"}` - the same shape the dashboard's own manual contact picker writes, and the only contact_ids shape the actual send worker (`createWhere()`) resolves into a real recipient filter. AI-reported, 2026-10-14: an earlier, invented shape (`{segment: \"Users\", operator: \"Is One Of\"}`) round-tripped correctly through v3's own read/estimate endpoints but was never recognized by the send worker, so the campaign silently fell back to sending to the entire workroom instead of the specified contacts.\n","properties":{"type":{"$ref":"#/components/schemas/CampaignAudienceType"},"segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"minItems":1,"maxItems":10,"description":"Only when `type: \"segment\"`. Union — contact matches if in ANY listed segment. Every id must belong to an existing segment in this account - an unrecognized id is rejected with 422, not silently accepted."},"exclude_segment_ids":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"maxItems":10,"description":"Only when `type: \"segment\"` (422 with `contact_ids`). Contacts in ANY of these segments are left out, even if they are in an included segment (the dashboard's \"Exclude Segments\"). Every id must be a well-formed, existing segment in this account, and must not also appear in `segment_ids` - otherwise 422. Always present in responses for `type: \"segment\"` (empty array when none), including for campaigns created in the dashboard. `GET /campaigns/{id}/recipients` subtracts these from `total_estimate` and lists them in `audience_expression` with `type: \"excluded_segment\"`."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":10000,"description":"Only when `type: \"contact_ids\"`. At least one id, and every id must belong to an existing contact in this account - an empty list or an unrecognized id is rejected with 422, not silently accepted."}}},"CampaignAudienceType":{"type":"string","enum":["segment","contact_ids"],"description":"`segment` — target one or more segments (static or dynamic). `contact_ids` — explicit list up to 10k. There is no \"everyone\" audience: the send worker completes a campaign with no segment without sending anything, so `all_subscribed` (formerly listed) is rejected with `422`. To reach everyone, target a segment that covers them.\n"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignSchedule":{"type":"object","required":["mode"],"description":"Read shape — derived from the legacy doc's `schedule` + `date_time`. On write, use `CampaignScheduleRequest` against `POST /campaigns/{id}/schedule`.\n","properties":{"mode":{"type":"string","enum":["immediate","scheduled","ongoing","draft"],"description":"- `draft` — the campaign hasn't been scheduled yet.\n- `immediate` — Send ASAP (dashboard's \"Send ASAP\" schedule).\n- `scheduled` — Specific Date & Time in the future.\n- `ongoing` — recurring send.\n"},"send_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When the worker should fire. Set for `immediate` (=now) and `scheduled` (=future). Optional for `ongoing`."},"end_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Ongoing only — when the recurring campaign stops."},"frequency":{"type":"string","nullable":true,"description":"Ongoing only. Legacy vocab: `once`, `daily`, `weekly`, `monthly`."},"days_of_week":{"type":"array","items":{"type":"string","enum":["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]},"description":"Ongoing weekly recurrences only."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"CampaignABTest":{"type":"object","required":["variants"],"description":"A/B split test. On create, the API materializes each variant as a sibling\ncampaign in the legacy `campaign` collection — the \"master\" carries\n`is_master: true` + `ab_variants[]`, and each child carries\n`master_id: <master hex>` + `ab_variant_label`. Analytics rolls up per-variant\nstats. Children are hidden from list responses by default.\n","properties":{"is_master":{"type":"boolean","description":"True on the master doc; false on child variant docs (present when reading a variant directly).","readOnly":true},"master_id":{"$ref":"#/components/schemas/CampaignId","nullable":true,"description":"On child docs, points to the master campaign.","readOnly":true},"split_field":{"type":"string","enum":["template_id","message_body","subject"],"default":"template_id","description":"What to vary between variants."},"variants":{"type":"array","minItems":2,"maxItems":5,"items":{"$ref":"#/components/schemas/CampaignABTestVariant"}},"variant_label":{"type":"string","description":"On child docs, the label assigned to this variant.","readOnly":true}}},"CampaignABTestVariant":{"type":"object","description":"A single A/B variant. The `split_field` on the parent CampaignABTest determines which of `template_id` / `message_body` / `subject` is honored.\n","properties":{"label":{"type":"string","description":"Human-readable variant label (e.g. `Variant A`). Auto-generated if omitted."},"template_id":{"$ref":"#/components/schemas/TemplateId","description":"Only when `split_field: \"template_id\"`."},"message_body":{"type":"string","description":"Only when `split_field: \"message_body\"` (SMS/voice campaigns). For SMS: At most 10 SMS segments: 1530 plain (GSM-7) characters, or 670 if the text contains emoji or any other non-GSM character (once split, each segment holds 153 GSM / 67 unicode characters; emoji count as 2). Merge tags count as written, not expanded. Longer variants are rejected with 422 `validation_failed`."},"subject":{"type":"string","description":"Only when `split_field: \"subject\"` (email campaigns)."}}},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/unarchive":{"post":{"tags":["Campaigns"],"operationId":"unarchiveCampaign","summary":"Restore an archived campaign.","description":"Reverses `POST /v3/campaigns/{id}/archive`: clears the archived state, restores `status` to whatever it was immediately before archiving (falls back to `drafted` if that isn't known — e.g. a campaign archived before this field existed), and makes the campaign visible again in `GET /v3/campaigns`'s default list. Idempotent — unarchiving a campaign that isn't archived is a no-op that returns its current state.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Unarchived.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Campaign"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Send a test rendering to specific addresses.

> Renders the campaign's template with sample variables and sends to up to 5 QA recipients. Excluded from campaign analytics. \`Idempotency-Key\` is required.\
> \
> \*\*Still a real send.\*\* Delivers to whichever address is given.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:write","messaging:send"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"CampaignTestSendRequest":{"type":"object","required":["to"],"description":"QA-send to a small ad-hoc address list (up to 5). Renders the campaign's referenced template — or its inline content — and hands each recipient to the messaging pipeline, exactly like the per-template test send. Tagged `category: transactional`, so it bypasses marketing opt-out and is excluded from campaign analytics.\n","properties":{"to":{"type":"array","minItems":1,"maxItems":5,"items":{"$ref":"#/components/schemas/NotificationRecipient"}},"variables":{"type":"object","additionalProperties":true}}},"NotificationRecipient":{"type":"object","description":"Recipient selector. Exactly one of `contact_id`, `phone`, or `email` must be set. If a raw `phone` or `email` doesn't match an existing contact, an unmanaged contact is auto-created (visible in dashboard, excluded from marketing lists).\n","properties":{"contact_id":{"$ref":"#/components/schemas/ContactId"},"phone":{"$ref":"#/components/schemas/PhoneE164"},"email":{"$ref":"#/components/schemas/Email"}},"oneOf":[{"required":["contact_id"]},{"required":["phone"]},{"required":["email"]}]},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"PhoneE164":{"type":"string","description":"E.164 international phone format.","pattern":"^\\+[1-9]\\d{1,14}$"},"Email":{"type":"string","format":"email"},"Message":{"type":"object","description":"A single message record — the outcome of a notification send, an outbound message from a campaign or flow, or a message inside a conversation. Same shape regardless of origin.\n","required":["id","object","channel","status","to","category","created_at"],"properties":{"id":{"$ref":"#/components/schemas/MessageId"},"object":{"type":"string","const":"message"},"channel":{"$ref":"#/components/schemas/MessageChannel"},"status":{"$ref":"#/components/schemas/MessageStatus"},"category":{"$ref":"#/components/schemas/MessageCategory"},"direction":{"type":"string","enum":["outbound","inbound"]},"conversation_id":{"type":"string","nullable":true,"description":"If this message is part of a conversation, its ID. Transactional sends default to null."},"to":{"type":"object","description":"Resolved recipient at send time.","properties":{"contact_id":{"$ref":"#/components/schemas/ContactId"},"phone":{"$ref":"#/components/schemas/PhoneE164"},"email":{"$ref":"#/components/schemas/Email"}}},"from":{"type":"object","nullable":true,"description":"Sender identity used for this send.","additionalProperties":true},"template_id":{"$ref":"#/components/schemas/TemplateId","nullable":true},"template_version":{"type":"integer","nullable":true,"description":"Which version of the template was rendered."},"subject":{"type":"string","nullable":true,"description":"Email only."},"body_snippet":{"type":"string","nullable":true,"description":"First ~200 chars of the rendered body, for previews."},"variables":{"type":"object","additionalProperties":true,"description":"Variables that were passed at send time (echoed for debugging)."},"provider":{"type":"string","nullable":true,"description":"Underlying delivery provider (`twilio`, `telnyx`, `mailgun`, etc.). Informational."},"provider_message_id":{"type":"string","nullable":true},"error":{"type":"object","nullable":true,"properties":{"code":{"type":"string"},"message":{"type":"string"}}},"cost":{"type":"object","nullable":true,"description":"Metered cost of this send in account currency.","properties":{"amount":{"type":"number"},"currency":{"type":"string"}}},"sent_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"delivered_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"opened_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"clicked_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"failed_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"}}},"MessageId":{"type":"string","pattern":"^msg_[0-9a-f]{24}$"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"MessageStatus":{"type":"string","enum":["pending","queued","sending","sent","success","delivered","opened","clicked","failed","bounced","undelivered"],"description":"A v3 send lands in the shared `messages` collection as `pending` — that collection's own queued state — and a delivery worker moves it to `success` or `failed`.\n\nCampaign-pipeline sends use the richer lifecycle: `queued` → `sending` → `sent` → `delivered` (or `bounced`/`failed`/`undelivered`). `opened` / `clicked` follow `delivered` for email and for SMS with tracked links. Terminal states: `success`, `delivered`, `opened`, `clicked`, `failed`, `bounced`, `undelivered`. Not every channel produces all of them.\n"},"MessageCategory":{"type":"string","enum":["transactional","marketing"],"description":"Does NOT bypass opt-out. As in the dashboard's one-to-one sends, a contact who has opted out of SMS (STOP / `optin_sms: 0`) gets no SMS and a contact who has unsubscribed from email (`optout_email: 1`) gets no email, whatever the category — both return 422 `compliance_block` (`opted_out_all` likewise blocks every channel). `marketing` additionally suppresses addresses the dashboard's campaign audience excludes: `invalid_email` 2/3/4 (bounced, complained, inactive) and `invalid_phone: 1`, returning 422 `compliance_block`; marketing email also carries the workroom's unsubscribe/address footers. Voice opt-out (`optout_voice`) still blocks marketing only. Earlier versions let `transactional` (the default) bypass channel opt-out; that bypass is gone.\n"},"TemplateId":{"type":"string","pattern":"^tpl_[0-9a-f]{24}$"},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"BadRequest":{"description":"Request could not be parsed or failed validation.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"TooManyRequests":{"description":"Rate limited.","headers":{"Retry-After":{"$ref":"#/components/headers/RetryAfter"}},"content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}},"headers":{"RetryAfter":{"description":"On 429, seconds to wait before retrying.","schema":{"type":"integer"}}}},"paths":{"/campaigns/{id}/test_send":{"post":{"tags":["Campaigns"],"operationId":"testSendCampaign","summary":"Send a test rendering to specific addresses.","description":"Renders the campaign's template with sample variables and sends to up to 5 QA recipients. Excluded from campaign analytics. `Idempotency-Key` is required.\n\n**Still a real send.** Delivers to whichever address is given.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"name":"Idempotency-Key","in":"header","required":true,"schema":{"type":"string","maxLength":255}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CampaignTestSendRequest"}}}},"responses":{"200":{"description":"Test sends dispatched. Returns the created Messages.","content":{"application/json":{"schema":{"type":"object","properties":{"object":{"type":"string","const":"list"},"data":{"type":"array","items":{"$ref":"#/components/schemas/Message"}}}}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"429":{"$ref":"#/components/responses/TooManyRequests"}}}}}}
```

## List materialized recipients for a campaign.

> The concrete recipient list is materialized at schedule time (or send time for \`send\_now\`). Before that, this returns 422 \`not\_materialized\_yet\` — use \`POST /v3/segments/preview\` on the audience to estimate. Includes A/B variant assignment when applicable.\
> \
> Before the first send the response is an estimate (\`total\_estimate\` + \`audience\_expression\`). When the audience has \`exclude\_segment\_ids\`, \`total\_estimate\` is the live count of contacts in any included segment minus contacts in any excluded segment (the same filter the send worker uses), and each excluded segment appears in \`audience\_expression\` with \`type: "excluded\_segment"\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:read"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}},"LimitParam":{"name":"limit","in":"query","required":false,"description":"Page size. Default 25, max 100.","schema":{"type":"integer","minimum":1,"maximum":100,"default":25}},"CursorParam":{"name":"cursor","in":"query","required":false,"description":"Opaque cursor from a prior response's `next_cursor`, to fetch the NEXT page (alias - `after`). On listContacts and listSegmentContacts, use `before` with a `prev_cursor` to page backward; other list endpoints are forward-only.","schema":{"type":"string"}}},"schemas":{"ListEnvelope":{"type":"object","required":["object","data","has_more","next_cursor","prev_cursor"],"properties":{"object":{"type":"string","const":"list"},"data":{"type":"array","items":{"type":"object"},"description":"The page of results. Item type varies per endpoint — see the specific response schema."},"has_more":{"type":"boolean","description":"True if additional records exist beyond this page."},"next_cursor":{"type":"string","nullable":true,"description":"Opaque cursor for the next page. Null on the last page."},"prev_cursor":{"type":"string","nullable":true,"description":"Cursor for the previous page. Supported on `listContacts` and `listSegmentContacts`: pass it back as `?before=...` to page backward; `null` on the first page. On every other list endpoint paging is forward-only and this is always `null`."}}},"CampaignRecipient":{"type":"object","required":["contact_id","status"],"description":"Materialized recipient for a campaign — computed at schedule time (or send time for `send_now`). Includes the per-contact resolved variant when A/B is active.\n","properties":{"contact_id":{"$ref":"#/components/schemas/ContactId"},"variant_index":{"type":"integer","nullable":true,"description":"0-based index into `ab_test.variants`. Null if no A/B test."},"status":{"type":"string","enum":["queued","sent","delivered","opened","clicked","failed","bounced","skipped"]},"message_id":{"$ref":"#/components/schemas/CampaignMessageId","nullable":true},"skipped_reason":{"type":"string","nullable":true,"description":"When `status: \"skipped\"`, why (e.g., `opted_out`, `no_channel_contact`, `duplicate`)."}}},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"CampaignMessageId":{"type":"string","pattern":"^cmsg_[0-9a-f]{24}$","description":"A per-recipient message record produced by a campaign send. Distinct from `MessageId` (standalone sends/conversations)."},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}},"Unprocessable":{"description":"Semantic validation failed — the request is well-formed but references an object in the wrong state (e.g., sending to an opted-out contact).","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/recipients":{"get":{"tags":["Campaigns"],"operationId":"listCampaignRecipients","summary":"List materialized recipients for a campaign.","description":"The concrete recipient list is materialized at schedule time (or send time for `send_now`). Before that, this returns 422 `not_materialized_yet` — use `POST /v3/segments/preview` on the audience to estimate. Includes A/B variant assignment when applicable.\n\nBefore the first send the response is an estimate (`total_estimate` + `audience_expression`). When the audience has `exclude_segment_ids`, `total_estimate` is the live count of contacts in any included segment minus contacts in any excluded segment (the same filter the send worker uses), and each excluded segment appears in `audience_expression` with `type: \"excluded_segment\"`.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/CursorParam"},{"name":"filter","in":"query","style":"deepObject","explode":true,"schema":{"type":"object","additionalProperties":{"type":"string"}}}],"responses":{"200":{"description":"A page of recipients.","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListEnvelope"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/CampaignRecipient"}}}}]}}}},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Aggregate stats for a campaign.

> Returns delivery, engagement, and (if A/B) per-variant breakdown. Numbers stabilize hours after send as delivered/opened/clicked events roll in from providers.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:read"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}}},"schemas":{"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"CampaignStats":{"type":"object","description":"On this object embedded in Campaign (via retrieve/list/create/update), delivered/opened/bounced/failed are computed live only by getCampaignAnalytics, to avoid an expensive per-campaign query on every list page - elsewhere they read quickly but can lag; call getCampaignAnalytics for current numbers.","properties":{"total_users":{"type":"integer","minimum":0,"description":"Materialized recipient count at send time."},"sent":{"type":"integer","minimum":0},"delivered":{"type":"integer","minimum":0},"opened":{"type":"integer","minimum":0},"clicked":{"type":"integer","minimum":0},"bounced":{"type":"integer","minimum":0},"failed":{"type":"integer","minimum":0},"converted":{"type":"integer","minimum":0}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/analytics":{"get":{"tags":["Campaigns"],"operationId":"getCampaignAnalytics","summary":"Aggregate stats for a campaign.","description":"Returns delivery, engagement, and (if A/B) per-variant breakdown. Numbers stabilize hours after send as delivered/opened/clicked events roll in from providers.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Analytics payload.","content":{"application/json":{"schema":{"type":"object","properties":{"object":{"type":"string","const":"campaign_analytics"},"campaign_id":{"$ref":"#/components/schemas/CampaignId"},"stats":{"$ref":"#/components/schemas/CampaignStats"},"variants":{"type":"array","nullable":true,"description":"Present when A/B testing is configured.","items":{"type":"object","properties":{"variant_index":{"type":"integer"},"weight":{"type":"integer"},"stats":{"$ref":"#/components/schemas/CampaignStats"},"winner":{"type":"boolean"}}}},"computed_at":{"$ref":"#/components/schemas/Timestamp"}}}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## List per-recipient message records for a campaign.

> Paginated list of \`Message\` records produced by this campaign. Use for per-recipient delivery inspection, bounce analysis, or reply tracking. Common filters: \`?filter\[status]=failed\`, \`?filter\[status]=bounced\`, \`?filter\[contact\_id]=\`. \`filter\[status]\` matches the returned (normalized) \`status\`, not a raw field: for SMS \`delivered\` / \`bounced\` / \`failed\` come from the carrier outcome (\`messagestatus\`), \`sent\` means handed off with no outcome yet; for email \`delivered\` includes the provider's \`success\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Campaigns","description":"One-shot audience-driven sends. Reference a Template for content, a Segment (or explicit contact list) for audience, an optional schedule, and optional A/B split."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["campaigns:read","conversations:read"]}],"components":{"securitySchemes":{"ApiKey":{"type":"http","scheme":"bearer","bearerFormat":"gltp_sk_*","description":"The **API Secret** from the Gleantap dashboard under **Settings → API** (Generate New Key if none exists). Send it bare (40 hex characters) or prefixed as `gltp_sk_live_<40-hex>`. There is no sandbox: every key acts on the live account.\n\nKeys are account-scoped and carry all permissions on that account (no per-key scope selection). Cross-workroom reads are unrestricted by default — narrow with `?workroom=` / `Gleantap-Workroom` on each request. Revoke via the dashboard.\n\nFor per-user consent, per-workroom scoping, and short-lived tokens, use OAuth 2.1 instead.\n"},"OAuth2":{"type":"oauth2","description":"OAuth 2.1 with PKCE. Use for third-party apps acting on behalf of a Gleantap user.\nAuthorization Code + PKCE is the only supported grant for interactive flows; refresh_token grant is supported and rotates on every use.\n","flows":{"authorizationCode":{"authorizationUrl":"https://api.gleantap.com/v3/oauth/authorize","tokenUrl":"https://api.gleantap.com/v3/oauth/token","refreshUrl":"https://api.gleantap.com/v3/oauth/token","scopes":{"contacts:read":"Read contact records.","contacts:write":"Create, update, delete contacts (soft delete).","contacts:delete_hard":"Hard-delete contacts (irreversible).","events:read":"Read event records.","events:write":"Record events.","segments:read":"Read segments and preview membership.","segments:write":"Create, update, delete segments.","templates:read":"Read message templates.","templates:write":"Create, update, delete templates.","campaigns:read":"Read campaigns and analytics.","campaigns:write":"Create, schedule, cancel campaigns.","flows:read":"Read flow definitions and analytics.","flows:write":"Create, edit, publish flows.","flows:publish":"Publish/unpublish flows (separately scoped for governance).","messaging:send":"Send transactional messages (SMS, email, voice).","conversations:read":"Read conversations and messages.","conversations:write":"Send messages, close/reopen conversations.","webhooks:manage":"Create, update, delete webhook endpoints.","forms:manage":"Create, update, delete, publish, duplicate forms; list submissions and rotate the submission_token.","campaigns:manage":"Create, schedule, cancel, duplicate campaigns; read recipients and analytics. (Supersedes the earlier `campaigns:read` + `campaigns:write` split; the split scopes still work.)","admin:impersonate:read":"Gleantap staff only — read any customer account named via `Gleantap-Account`. Not available through dynamic client registration.","admin:impersonate:write":"Gleantap staff only — required for any state-changing method while impersonating. Not available through dynamic client registration."}}}}},"parameters":{"VersionHeader":{"name":"Gleantap-Version","in":"header","required":false,"description":"Minor version to run the request under (date-based). Older dates remain supported for at least 24 months. If omitted, the account's default pinned version is used.\n","schema":{"type":"string","pattern":"^\\d{4}-\\d{2}-\\d{2}$"}},"AccountHeader":{"name":"Gleantap-Account","in":"header","required":false,"description":"Target customer account, as `acc_<24-hex>` or a bare 24-hex ID. **Only for Gleantap staff (CSM) tokens**, which authenticate against the internal staff directory and are bound to no account; for a normal customer token the account is fixed by the token and this header is ignored.\n\nA staff token MUST name an account on every request — there is no default, and omitting it returns 400 `admin_account_required` rather than falling back to some first account. Switching accounts is just a different value here; no re-authorization. Account *names* are rejected (400 `admin_account_invalid`) because they are neither unique nor stable — list IDs with `GET /v3/accounts`.\n\nEvery impersonated response carries an `impersonation` block naming the account actually acted on, so an account switch mid-session is always visible. Also settable via `?account=`.\n","schema":{"type":"string"}},"WorkroomHeader":{"name":"Gleantap-Workroom","in":"header","required":false,"description":"Which workroom to act in. Accepts a workroom name (case-insensitive), a prefixed ID (`wrm_<hex>`), a raw 24-hex ID, or the literal `all`.\n\n**On any write, ask the user which workroom — do not omit this.** Optional here means the server has a fallback, not that the fallback is what anyone wanted: an omitted workroom sends the write to the account's *default* workroom, and accounts routinely have dozens. Creating a contact, flow, campaign or segment in the wrong workroom puts it where nobody is looking, and moving it afterwards is manual.\n\nThe one case where you need not ask: the account has exactly one workroom. Call `listWorkrooms` to find out — if it returns a single row, use it; if it returns several, ask which one before writing.\n\n**Reads are scoped too.** Omitting a workroom on a read does not span the account — it narrows to the same default workroom a write would go to, and the response carries a `workroom_defaulted` warning saying so. So a count, a list or a segment preview describes *one* workroom unless you said otherwise. Pass `all` to deliberately span every workroom; that is the only way to get account-wide figures, and it is never the default. `listWorkrooms` itself is never narrowed, since it is how you discover what to ask for.\n\nAlso settable via `?workroom=` or a `workroom` body field (POST/PATCH only) — query wins over header wins over body.\n","schema":{"type":"string"}},"WorkroomQuery":{"name":"workroom","in":"query","required":false,"description":"Same semantics as the `Gleantap-Workroom` header, including that a write should never be sent without a workroom the user actually chose, and that an omitted workroom scopes a read to the account default rather than spanning the account. Prefer this on GETs so proxies and caches can key on it. Accepts name, prefixed ID, raw hex, or `all`.\n","schema":{"type":"string"}},"LimitParam":{"name":"limit","in":"query","required":false,"description":"Page size. Default 25, max 100.","schema":{"type":"integer","minimum":1,"maximum":100,"default":25}},"CursorParam":{"name":"cursor","in":"query","required":false,"description":"Opaque cursor from a prior response's `next_cursor`, to fetch the NEXT page (alias - `after`). On listContacts and listSegmentContacts, use `before` with a `prev_cursor` to page backward; other list endpoints are forward-only.","schema":{"type":"string"}}},"schemas":{"ListEnvelope":{"type":"object","required":["object","data","has_more","next_cursor","prev_cursor"],"properties":{"object":{"type":"string","const":"list"},"data":{"type":"array","items":{"type":"object"},"description":"The page of results. Item type varies per endpoint — see the specific response schema."},"has_more":{"type":"boolean","description":"True if additional records exist beyond this page."},"next_cursor":{"type":"string","nullable":true,"description":"Opaque cursor for the next page. Null on the last page."},"prev_cursor":{"type":"string","nullable":true,"description":"Cursor for the previous page. Supported on `listContacts` and `listSegmentContacts`: pass it back as `?before=...` to page backward; `null` on the first page. On every other list endpoint paging is forward-only and this is always `null`."}}},"CampaignMessage":{"type":"object","required":["id","object","campaign_id","contact_id","channel","to","status","created_at"],"description":"A single per-recipient message record produced by a campaign send.","properties":{"id":{"$ref":"#/components/schemas/CampaignMessageId"},"object":{"type":"string","const":"campaign_message"},"campaign_id":{"$ref":"#/components/schemas/CampaignId"},"contact_id":{"$ref":"#/components/schemas/ContactId"},"channel":{"$ref":"#/components/schemas/MessageChannel"},"to":{"type":"string","description":"Phone number (SMS/voice) or email address (email) this message was sent to."},"status":{"type":"string","enum":["queued","sent","delivered","bounced","failed"]},"clicked":{"type":"boolean"},"sent_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"delivered_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"opened_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"clicked_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"error":{"type":"string","nullable":true,"description":"Provider bounce/reject/error text, when `status` is `bounced` or `failed`."},"created_at":{"$ref":"#/components/schemas/Timestamp"}}},"CampaignMessageId":{"type":"string","pattern":"^cmsg_[0-9a-f]{24}$","description":"A per-recipient message record produced by a campaign send. Distinct from `MessageId` (standalone sends/conversations)."},"CampaignId":{"type":"string","pattern":"^cam_[0-9a-f]{24}$"},"ContactId":{"type":"string","pattern":"^con_[0-9a-f]{24}$|^external_id:[^/]+$","description":"A contact ID. Accepts either the native prefixed id (`con_<24-hex>`) or an external-ID reference (`external_id:<your_id>`).\n"},"MessageChannel":{"type":"string","enum":["sms","email","voice"],"description":"Delivery channel. Push is not supported by Gleantap."},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"Problem":{"type":"object","description":"RFC 9457 Problem Details with Gleantap extensions. Every error response follows this shape.\nHandle by inspecting the `code` field (not the human-readable `title` or `detail`), which is stable across versions.\n","required":["type","title","status","code","request_id"],"properties":{"type":{"type":"string","format":"uri","description":"URL to the human-readable error documentation."},"title":{"type":"string","description":"Short human-readable summary."},"status":{"type":"integer","description":"HTTP status code repeated in the body for convenience."},"detail":{"type":"string","description":"Longer human-readable explanation. May be null.","nullable":true},"code":{"type":"string","description":"Machine-readable error code. This is the field to switch on programmatically.\nStandard values include: `authentication_required`, `invalid_credentials`, `permission_denied`, `scope_required`, `resource_not_found`, `validation_error`, `invalid_field`, `missing_field`, `idempotency_conflict`, `rate_limited`, `quota_exceeded`, `internal_error`, `service_unavailable`, `feature_not_enabled`, `compliance_block`, `version_conflict`.\n"},"request_id":{"type":"string","description":"The X-Request-ID for this response. Include when reporting issues."},"errors":{"type":"array","nullable":true,"description":"Field-level details, present on validation errors.","items":{"type":"object","required":["field","code","message"],"properties":{"field":{"type":"string"},"code":{"type":"string"},"message":{"type":"string"}}}}}}},"responses":{"NotFound":{"description":"The resource doesn't exist or isn't visible to this caller.","content":{"application/problem+json":{"schema":{"$ref":"#/components/schemas/Problem"}}}}}},"paths":{"/campaigns/{id}/messages":{"get":{"tags":["Campaigns"],"operationId":"listCampaignMessages","summary":"List per-recipient message records for a campaign.","description":"Paginated list of `Message` records produced by this campaign. Use for per-recipient delivery inspection, bounce analysis, or reply tracking. Common filters: `?filter[status]=failed`, `?filter[status]=bounced`, `?filter[contact_id]=`. `filter[status]` matches the returned (normalized) `status`, not a raw field: for SMS `delivered` / `bounced` / `failed` come from the carrier outcome (`messagestatus`), `sent` means handed off with no outcome yet; for email `delivered` includes the provider's `success`.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/LimitParam"},{"$ref":"#/components/parameters/CursorParam"},{"name":"filter","in":"query","style":"deepObject","explode":true,"schema":{"type":"object","additionalProperties":{"type":"string"}}}],"responses":{"200":{"description":"A page of messages.","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListEnvelope"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/CampaignMessage"}}}}]}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```
