> 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/segments.md).

# Segments

Named collections of contacts. **Static** segments are hand-managed member lists; **dynamic** segments are defined by a query and re-evaluated automatically. Use `GET /segments/schema` to discover the fields and operators a query can use, and `POST /segments/preview` to test a query before saving it.

## List segments.

> Paginated list of segments. Filter by type via \`?filter\[type]=static\` or \`?filter\[type]=dynamic\`. Other filters: \`?filter\[name]=...\` (case-insensitive prefix), \`?filter\[created\_at]\[gte]=...\`. Honours the sparse fieldset: \`?fields=id,name,type,size\` returns only those keys (plus \`id\` and \`object\`, which are always kept) instead of the full segment, including its \`query\`. Rate limit bucket: \`read\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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`."}}},"Segment":{"type":"object","description":"A named collection of contacts. Either static (hand-managed list) or dynamic (query-defined). Discriminated by the `type` field, which is immutable after creation.\n","required":["id","object","type","name","size","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/SegmentId"},"object":{"type":"string","const":"segment"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom that owns this segment. A flow can only be triggered by segments in its own workroom — compare against `Flow.workroom_id`."},"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","nullable":true,"description":"The segment's criteria. **Present on BOTH static and dynamic segments** — a \"static\" segment only means the engine doesn't auto-refresh membership; the criteria that defined the initial membership list is still stored and returned. When diagnosing \"why did this contact match this segment?\", read `query.segment_users` (+ `with_or_segment_users` and `exclude_segment_users`). May be `null` only on segments imported without criteria or created empty.\n"},"size":{"type":"integer","minimum":0,"description":"Current member count. Eventually consistent — up to minutes of lag on dynamic segments."},"email_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid email."},"phone_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid phone."},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When this dynamic segment was last recomputed. Null on static."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"The segment folder this segment currently belongs to, or `null` if unfoldered."},"segment_summary":{"type":"string","nullable":true,"description":"AI-generated narrative summary of the segment's criteria. Populated on demand via `POST /v3/segments/{id}/summary`."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentType":{"type":"string","enum":["static","dynamic"],"description":"`static` — hand-managed member list. Contacts are added/removed explicitly.\n`dynamic` — query-defined membership. Auto-evaluated; membership changes as contact data changes.\nImmutable after creation.\n"},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"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":{"Unauthorized":{"description":"Missing or invalid credentials.","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":{"/segments":{"get":{"tags":["Segments"],"operationId":"listSegments","summary":"List segments.","description":"Paginated list of segments. Filter by type via `?filter[type]=static` or `?filter[type]=dynamic`. Other filters: `?filter[name]=...` (case-insensitive prefix), `?filter[created_at][gte]=...`. Honours the sparse fieldset: `?fields=id,name,type,size` returns only those keys (plus `id` and `object`, which are always kept) instead of the full segment, including its `query`. 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 segments.","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListEnvelope"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Segment"}}}}]}}}},"401":{"$ref":"#/components/responses/Unauthorized"},"429":{"$ref":"#/components/responses/TooManyRequests"}}}}}}
```

## Create a segment (static or dynamic).

> \*\*Before constructing \`query.segment\_users\`, call \`GET /v3/segments/schema\` (MCP: \`describeSegmentSchema\`)\*\* to see the available categories, their attributes, valid operators per data type, and observed values on the current workroom. This is the authoritative source.\
> \
> \*\*Prefer built-in categories over creating custom fields.\*\* For membership status, purchases, appointments, visits, engagement, forms, flows, ratings, loyalty, sales pipeline stage, etc., there is already a first-class category (\`memberships\`, \`purchases\`, \`appointments\`, \`visits\`, \`email\_engagement\`, \`sms\_engagement\`, \`forms\`, \`flows\`, \`ratings\`, \`loyalty\`, \`salesattributes\`). The \`attributes\` (Custom) category resolves to \`userdetails.data.\<key>\` and covers concepts with no built-in category.\
> \
> \`type\` is immutable — pick correctly at creation. Dynamic segments require \`query\` and are evaluated on the server; membership updates automatically. Static segments accept an optional initial \`contact\_ids\` list and are mutated via \`POST /v3/segments/{id}/contacts\`. Rate limit bucket: \`write\`.\
> \
> Requires the name and the actual conditions. 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":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentCreate":{"type":"object","required":["type","name"],"description":"Create a static or dynamic segment. `type` is immutable — you cannot convert a static to dynamic later. Dynamic segments require `query`.\n\n**Static segments — how to supply initial members (pick ONE):**\n  - Pass a `query` (the filter criteria). The server stores the criteria on the segment (so the dashboard shows \"what this segment was built from\" and diagnostics can read `query.segment_users`) AND evaluates it once at creation time to freeze the currently-matching contacts as members. **This is the preferred way to build a \"static snapshot of everyone matching X\"** — do not pre-compute the matches yourself and pass them as `contact_ids`, or the criteria is lost and the dashboard shows no filter.\n  - Or pass an explicit `contact_ids` list for a purely hand-managed membership with no defining criteria.\n\n  If both are given, `contact_ids` wins and `query` is stored as criteria only (not re-evaluated). A snapshot that matches more than 100k contacts is rejected — narrow the filter. The snapshot is computed the way the dashboard cron computes membership (OR groups, shared-contact excludes, account timezone).\n\n  Exception: a `query` with External Events / Event Attributes conditions is not snapshotted at creation — the segment is created with size 0 and the dashboard's external-events cron computes its membership once (usually within minutes), exactly as for a static segment saved in the dashboard.\n","properties":{"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","description":"Required when `type: \"dynamic\"`. On a `static` segment, the criteria are stored for display/diagnostics and snapshotted into the initial member list at creation time."},"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"description":"Optional explicit initial member list. Static segments only. Prefer `query` instead when the segment represents \"everyone matching X\" — see the schema description.","maxItems":10000},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","description":"Optional segment folder to file this segment under at creation time. Must reference an existing folder in the same workroom — an unresolvable id returns 422."},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentType":{"type":"string","enum":["static","dynamic"],"description":"`static` — hand-managed member list. Contacts are added/removed explicitly.\n`dynamic` — query-defined membership. Auto-evaluated; membership changes as contact data changes.\nImmutable after creation.\n"},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"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"},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"Segment":{"type":"object","description":"A named collection of contacts. Either static (hand-managed list) or dynamic (query-defined). Discriminated by the `type` field, which is immutable after creation.\n","required":["id","object","type","name","size","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/SegmentId"},"object":{"type":"string","const":"segment"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom that owns this segment. A flow can only be triggered by segments in its own workroom — compare against `Flow.workroom_id`."},"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","nullable":true,"description":"The segment's criteria. **Present on BOTH static and dynamic segments** — a \"static\" segment only means the engine doesn't auto-refresh membership; the criteria that defined the initial membership list is still stored and returned. When diagnosing \"why did this contact match this segment?\", read `query.segment_users` (+ `with_or_segment_users` and `exclude_segment_users`). May be `null` only on segments imported without criteria or created empty.\n"},"size":{"type":"integer","minimum":0,"description":"Current member count. Eventually consistent — up to minutes of lag on dynamic segments."},"email_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid email."},"phone_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid phone."},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When this dynamic segment was last recomputed. Null on static."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"The segment folder this segment currently belongs to, or `null` if unfoldered."},"segment_summary":{"type":"string","nullable":true,"description":"AI-generated narrative summary of the segment's criteria. Populated on demand via `POST /v3/segments/{id}/summary`."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[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"}}}},"Unauthorized":{"description":"Missing or invalid credentials.","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":{"/segments":{"post":{"tags":["Segments"],"operationId":"createSegment","summary":"Create a segment (static or dynamic).","description":"**Before constructing `query.segment_users`, call `GET /v3/segments/schema` (MCP: `describeSegmentSchema`)** to see the available categories, their attributes, valid operators per data type, and observed values on the current workroom. This is the authoritative source.\n\n**Prefer built-in categories over creating custom fields.** For membership status, purchases, appointments, visits, engagement, forms, flows, ratings, loyalty, sales pipeline stage, etc., there is already a first-class category (`memberships`, `purchases`, `appointments`, `visits`, `email_engagement`, `sms_engagement`, `forms`, `flows`, `ratings`, `loyalty`, `salesattributes`). The `attributes` (Custom) category resolves to `userdetails.data.<key>` and covers concepts with no built-in category.\n\n`type` is immutable — pick correctly at creation. Dynamic segments require `query` and are evaluated on the server; membership updates automatically. Static segments accept an optional initial `contact_ids` list and are mutated via `POST /v3/segments/{id}/contacts`. Rate limit bucket: `write`.\n\nRequires the name and the actual conditions. 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/SegmentCreate"}}}},"responses":{"201":{"description":"Segment created.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Segment"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"$ref":"#/components/responses/Unauthorized"},"422":{"$ref":"#/components/responses/Unprocessable"},"429":{"$ref":"#/components/responses/TooManyRequests"}}}}}}
```

## Retrieve a segment.

> Fetch a segment with current \`size\`, \`email\_count\`, and \`phone\_count\`. For dynamic segments, these values are eventually consistent (up to minutes of lag from underlying contact writes). Honours the sparse fieldset: \`?fields=id,name,type,size\` returns only those keys (plus \`id\` and \`object\`, which are always kept) instead of the full segment, including its \`query\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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"}}},"schemas":{"Segment":{"type":"object","description":"A named collection of contacts. Either static (hand-managed list) or dynamic (query-defined). Discriminated by the `type` field, which is immutable after creation.\n","required":["id","object","type","name","size","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/SegmentId"},"object":{"type":"string","const":"segment"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom that owns this segment. A flow can only be triggered by segments in its own workroom — compare against `Flow.workroom_id`."},"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","nullable":true,"description":"The segment's criteria. **Present on BOTH static and dynamic segments** — a \"static\" segment only means the engine doesn't auto-refresh membership; the criteria that defined the initial membership list is still stored and returned. When diagnosing \"why did this contact match this segment?\", read `query.segment_users` (+ `with_or_segment_users` and `exclude_segment_users`). May be `null` only on segments imported without criteria or created empty.\n"},"size":{"type":"integer","minimum":0,"description":"Current member count. Eventually consistent — up to minutes of lag on dynamic segments."},"email_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid email."},"phone_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid phone."},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When this dynamic segment was last recomputed. Null on static."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"The segment folder this segment currently belongs to, or `null` if unfoldered."},"segment_summary":{"type":"string","nullable":true,"description":"AI-generated narrative summary of the segment's criteria. Populated on demand via `POST /v3/segments/{id}/summary`."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentType":{"type":"string","enum":["static","dynamic"],"description":"`static` — hand-managed member list. Contacts are added/removed explicitly.\n`dynamic` — query-defined membership. Auto-evaluated; membership changes as contact data changes.\nImmutable after creation.\n"},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"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":{"/segments/{id}":{"get":{"tags":["Segments"],"operationId":"retrieveSegment","summary":"Retrieve a segment.","description":"Fetch a segment with current `size`, `email_count`, and `phone_count`. For dynamic segments, these values are eventually consistent (up to minutes of lag from underlying contact writes). Honours the sparse fieldset: `?fields=id,name,type,size` returns only those keys (plus `id` and `object`, which are always kept) instead of the full segment, including its `query`.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"$ref":"#/components/parameters/FieldsParam"}],"responses":{"200":{"description":"The segment.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Segment"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Update a segment.

> Update name, description, folder, or (for dynamic segments) query. \`type\` cannot be changed. Sending \`query\` on a static segment returns 422 \`wrong\_segment\_type\`. To modify static membership use \`POST\` / \`DELETE\` on \`/segments/{id}/contacts\`. To move the segment into (or out of) a folder, set \`folder\_id\` (pass \`null\` to unfolder it) — an unresolvable folder\_id returns 422.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentUpdate":{"type":"object","description":"Partial update. `type` cannot be changed. Sending `query` on a static segment returns 422 `wrong_segment_type`; sending `contact_ids` here does nothing — use `POST /v3/segments/{id}/contacts` instead.\n","properties":{"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","description":"Only accepted for dynamic segments."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"Move the segment into this folder. Pass `null` explicitly to remove it from its current folder (unfolder it). Must reference an existing folder in the same workroom — an unresolvable id returns 422."},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"Segment":{"type":"object","description":"A named collection of contacts. Either static (hand-managed list) or dynamic (query-defined). Discriminated by the `type` field, which is immutable after creation.\n","required":["id","object","type","name","size","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/SegmentId"},"object":{"type":"string","const":"segment"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom that owns this segment. A flow can only be triggered by segments in its own workroom — compare against `Flow.workroom_id`."},"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","nullable":true,"description":"The segment's criteria. **Present on BOTH static and dynamic segments** — a \"static\" segment only means the engine doesn't auto-refresh membership; the criteria that defined the initial membership list is still stored and returned. When diagnosing \"why did this contact match this segment?\", read `query.segment_users` (+ `with_or_segment_users` and `exclude_segment_users`). May be `null` only on segments imported without criteria or created empty.\n"},"size":{"type":"integer","minimum":0,"description":"Current member count. Eventually consistent — up to minutes of lag on dynamic segments."},"email_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid email."},"phone_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid phone."},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When this dynamic segment was last recomputed. Null on static."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"The segment folder this segment currently belongs to, or `null` if unfoldered."},"segment_summary":{"type":"string","nullable":true,"description":"AI-generated narrative summary of the segment's criteria. Populated on demand via `POST /v3/segments/{id}/summary`."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentType":{"type":"string","enum":["static","dynamic"],"description":"`static` — hand-managed member list. Contacts are added/removed explicitly.\n`dynamic` — query-defined membership. Auto-evaluated; membership changes as contact data changes.\nImmutable after creation.\n"},"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"}}}},"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":{"/segments/{id}":{"patch":{"tags":["Segments"],"operationId":"updateSegment","summary":"Update a segment.","description":"Update name, description, folder, or (for dynamic segments) query. `type` cannot be changed. Sending `query` on a static segment returns 422 `wrong_segment_type`. To modify static membership use `POST` / `DELETE` on `/segments/{id}/contacts`. To move the segment into (or out of) a folder, set `folder_id` (pass `null` to unfolder it) — an unresolvable folder_id returns 422.\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/SegmentUpdate"}}}},"responses":{"200":{"description":"Updated.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Segment"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Delete a segment.

> Delete the segment. Contacts are not affected; only the segment definition and membership index are removed. Segments referenced by an active or paused flow, campaign, or sales automation cannot be deleted (409 \`segment\_in\_use\`) — remove the references first, or use \`?force=true\` (requires \`segments:write\` plus admin role) to cascade-remove those references. \`force\` does not leave a half-edited rule behind: a rule whose last trigger segment is removed is marked \`broken\` and completed.\
> \
> \*\*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":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"/segments/{id}":{"delete":{"tags":["Segments"],"operationId":"deleteSegment","summary":"Delete a segment.","description":"Delete the segment. Contacts are not affected; only the segment definition and membership index are removed. Segments referenced by an active or paused flow, campaign, or sales automation cannot be deleted (409 `segment_in_use`) — remove the references first, or use `?force=true` (requires `segments:write` plus admin role) to cascade-remove those references. `force` does not leave a half-edited rule behind: a rule whose last trigger segment is removed is marked `broken` and completed.\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"},{"name":"force","in":"query","required":false,"schema":{"type":"boolean","default":false},"description":"If true, cascade-remove references from active flows/campaigns. Admin-only."}],"responses":{"204":{"description":"Deleted."},"404":{"$ref":"#/components/responses/NotFound"},"409":{"$ref":"#/components/responses/Conflict"}}}}}}
```

## List/export segment members. When EXPORTING, ASK which columns first — do not export all fields by default.

> ⚠️ EXPORT RULE — READ FIRST: Plain member listing is unrestricted. But if the user is EXPORTING this segment (to CSV or a file), you MUST call with \`export=true\`, and then \`fields\` is mandatory: \`export=true\` with no \`fields\` returns 422 \`export\_columns\_required\` plus the column catalog — meaning ASK the user which columns they want (present the grouped human-readable options below), then call with \`export=true\&fields=\<chosen keys>\`. Never pick export columns yourself without asking, and never export all fields by default.\
> \
> Paginated members — this endpoint also backs "export a segment". Works for both static and dynamic segments. The list is read from the membership index, so it is never filtered by the segment's cached \`size\`: a segment showing \`size: 0\` with \`last\_evaluated\_at: null\` has simply never been evaluated, and may still list rows. On dynamic segments the list reflects the last evaluation — force a fresh one via \`POST /v3/segments/{id}/refresh\` if it is stale.\
> \
> EXPORTING — CHOOSE COLUMNS FIRST: by default the full contact is returned. Before exporting, ASK the customer which columns they want and present them in human-readable form, grouped exactly like the segment UI (show the Label; send the key). Pass the chosen keys as a comma-separated \`fields\` value; the response is then one row per contact keyed by the human Label, ready to write as CSV.\
> &#x20; Personal Info — Contact Name → \`col\_name\`, First Name → \`personalinfo.firstname\`, Last Name → \`personalinfo.lastname\`, Email → \`personalinfo.email\`, Phone → \`personalinfo.phone\`, Gender → \`personalinfo.gender\`, Date of Birth → \`personalinfo.dob\`, Birthday → \`personalinfo.birthday\`, City → \`personalinfo.city\`, State → \`personalinfo.state\`, Country → \`personalinfo.country\`, Added On → \`personalinfo.added\_on\`\
> &#x20; Account Info — Location → \`accountinfo.location\`, Location ID → \`accountinfo.location\_id\`, Status → \`accountinfo.status\`, Type → \`accountinfo.type\`, Tags → \`accountinfo.tags\`, Source → \`accountinfo.source\`\
> &#x20; Memberships — Membership Name → \`memberships.name\`, Membership Status → \`memberships.status\`, Membership Type → \`memberships.type\`, Membership Expiry → \`memberships.end\_date\`, Membership Start Date → \`memberships.start\_date\`, Membership Session Remaining → \`memberships.membership\_session\_remaining\`\
> &#x20; Contract Info — Contract Name → \`contracts.name\`, Contract Status → \`contracts.status\`, Contract Expiry → \`contracts.end\_date\`, Contract Start Date → \`contracts.start\_date\`, First Contract Date → \`contractinfo.first\_contract\_date\`\
> &#x20; Purchase Info — Last Purchased On → \`purchases.last\_purchase\_date\`, Last Purchased Item → \`purchases.last\_purchase\_products\`, Last Purchased Price → \`purchases.last\_purchase\_price\`, First Purchased On → \`purchases.first\_purchase\_date\`, First Purchased Item → \`purchases.first\_purchase\_products\`, First Purchased Price → \`purchases.first\_purchase\_price\`\
> &#x20; Visit Info — Last Visit On → \`visits.last\_visit\_date\`, Last Visit Service → \`visits.last\_visit\_services\`, Last Visit Type → \`visits.last\_visit\_type\`, Last Visit Status → \`visits.last\_visit\_status\`, First Visit On → \`visits.first\_visit\_date\`, First Visit Service → \`visits.first\_visit\_services\`, First Visit Status → \`visits.first\_visit\_status\`, Total Visits → \`visits.total\_class\_visits\`\
> &#x20; Pipeline — Pipeline Name → \`sales.pipeline\`, Stage → \`sales.stage\`, Status → \`sales.status\`, Responsible User → \`sales.responsible\`\
> &#x20; Ratings — Rating → \`ratings.rating\`, Review → \`ratings.review\`, Last Rating On → \`ratings.last\_rating\_on\`\
> &#x20; Custom — account-specific fields: call \`describeSegmentSchema\` (\`GET /v3/segments/schema\`), which exposes the account's custom attributes (the \`attributes\` map on the \`segments\` catalog — e.g. \`member\_id\`, \`join\_date\`, \`zipcode\`, …). Offer each key under a humanised label and pass the key verbatim as a \`fields\` value. (These are NOT on \`retrieveSegment\`, which returns only the saved segment definition.)\
> Example: \`fields=personalinfo.firstname,personalinfo.lastname,personalinfo.email,memberships.name\`. Multiple memberships stack in the cell. Present/label columns with the human names above, never the raw keys.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments:read","contacts: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"}},"BeforeParam":{"name":"before","in":"query","required":false,"description":"Opaque cursor from a prior response's `prev_cursor`, to fetch the PREVIOUS page. Supported on listContacts and listSegmentContacts only. If both `before` and `cursor` are sent, `before` wins.","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`."}}},"Contact":{"type":"object","description":"A person record. Central to almost every other resource in Gleantap.\nContacts have an internal id (`con_<24-hex>`) and optionally an external ID (`external_id`) you set from your own system. Both can be used to look up the record.\n","required":["id","object","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/ContactId"},"object":{"type":"string","const":"contact"},"external_id":{"type":"string","nullable":true,"description":"Your system's ID for this contact. Unique within the account. For contacts synced by an integration this is the member id the integration stores in `user_id` (returned when `external_id` itself is unset and `user_id` is not just the email/phone). `filter[external_id]` and `GET /v3/contacts/external_id:<x>` match either field, as string or integer."},"email":{"$ref":"#/components/schemas/Email","nullable":true},"phone":{"$ref":"#/components/schemas/PhoneE164","nullable":true,"description":"Stored the way every Gleantap writer stores it (formatPhone) — a `+` number is kept, a national number gets the account's country code (US/CA +1, GB +44, AU +61 with the trunk 0 dropped, NL, DK, LB, AE). Writes accept either form."},"first_name":{"type":"string","nullable":true,"maxLength":100},"last_name":{"type":"string","nullable":true,"maxLength":100},"date_of_birth":{"$ref":"#/components/schemas/Date","nullable":true,"description":"Stored as `personalinfo.dob` (date) + `personalinfo.birthday` (day of year), the pair birthday segments, campaigns and loyalty birthday rewards match on; `data.dob` is kept in step."},"locale":{"$ref":"#/components/schemas/Locale","nullable":true},"timezone":{"$ref":"#/components/schemas/Timezone","nullable":true},"tags":{"type":"array","items":{"$ref":"#/components/schemas/TagName"},"description":"All tags currently applied to this contact (`sales.tags`, the list the dashboard shows)."},"custom_fields":{"type":"object","additionalProperties":true,"description":"Account-defined custom fields. Schema is per-workroom (see `/v3/custom_fields`). Values are coerced to the declared type on write, as the dashboard CSV import does: date → stored date (a bare `YYYY-MM-DD` is midnight in the account timezone), number → integer/decimal, boolean → true/false. Dates are returned as ISO-8601 strings.\n"},"memberships":{"type":"array","items":{"$ref":"#/components/schemas/ContactMembership"},"description":"The contact's memberships/plans. Segment engine reads `memberships.status` / `memberships.type` / `memberships.renewal_date` / etc. directly off this array. Populated by CRM syncs (Mariana etc.) or by direct API writes.\n"},"consent":{"type":"object","description":"Per-channel consent records. Server-enforced on all marketing sends.","properties":{"sms":{"$ref":"#/components/schemas/ConsentRecord"},"email":{"$ref":"#/components/schemas/ConsentRecord"}}},"primary_location_id":{"$ref":"#/components/schemas/LocationId","nullable":true,"description":"Not populated yet (no Location resource). Use `location` / `location_id`."},"location":{"type":"string","nullable":true,"description":"The contact's location/club name as the integration or CSV import recorded it (`accountinfo.location`, else `data.location` / `data.location_name`). Numeric on some accounts; always returned as a string. Same value `filter[location]` matches."},"location_id":{"type":"string","nullable":true,"description":"The integration's location id (`accountinfo.location_id`, else `data.location_id`)."},"member_status":{"type":"string","nullable":true,"description":"Membership/account status as synced (`accountinfo.status`), e.g. `active`, `inactive`, `cancelled`. Vocabulary is the integration's."},"owner_user_id":{"$ref":"#/components/schemas/UserId","nullable":true},"segments":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"description":"Segment IDs this contact is currently a member of. Eventually consistent (up to minutes of lag from an underlying data change)."},"pipelines":{"type":"array","description":"Pipelines and stages this contact currently belongs to.","items":{"type":"object","properties":{"pipeline_id":{"$ref":"#/components/schemas/PipelineId"},"stage_id":{"$ref":"#/components/schemas/StageId","nullable":true},"stage_name":{"type":"string","nullable":true},"status":{"type":"string"},"added_at":{"$ref":"#/components/schemas/Timestamp"},"last_updated_at":{"$ref":"#/components/schemas/Timestamp"}}}},"lifecycle_stage":{"type":"string","nullable":true,"description":"Stage label stored in `accountinfo.type`. The values in real data are `member`, `prospect`, `past` and `non-member`, plus raw labels integrations pass through in their own case (`Kid`, `Parent`, `Individual`, …). Not enforced; `filter[lifecycle_stage]` matches case-insensitively. Writing `member` (or `customer`) also sets `accountinfo.member: 1`; anything other than member/former sets `accountinfo.prospect: 1`.\n"},"last_seen_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp","description":"Last change by any writer — the later of v3's own stamp and the `last_updated_on` the integrations and dashboard maintain. `sort=updated_at` orders by `last_updated_on`."},"deleted_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set if this contact was soft-deleted. Soft-deleted contacts are hidden from all list endpoints, the dashboard and every send by default; include `?filter[deleted]=true` to see them. Merged-away contacts also carry it."},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"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"},"Email":{"type":"string","format":"email"},"PhoneE164":{"type":"string","description":"E.164 international phone format.","pattern":"^\\+[1-9]\\d{1,14}$"},"Date":{"type":"string","format":"date","description":"Calendar date (no time), ISO 8601 `YYYY-MM-DD`."},"Locale":{"type":"string","description":"BCP 47 locale tag."},"Timezone":{"type":"string","description":"IANA timezone name."},"TagName":{"type":"string","description":"Tag name. Case-preserving, but case-insensitive on match. Whitespace preserved.","pattern":"^[^\\n\\r]{1,100}$"},"ContactMembership":{"type":"object","description":"A single membership/plan on a contact. Stored inline on `userdetails.memberships[]` (the segment DSL's `memberships.*` category queries this array via `$elemMatch`). Purchases live on events, but memberships live here because the segment engine needs cheap membership-status lookups without JOINing.\n","required":["id","name"],"properties":{"id":{"type":"string","description":"External identifier (from CRM / source system). Not a v3-prefixed ID."},"name":{"type":"string","description":"Plan name (e.g., \"Unlimited Monthly\", \"Class Pack — 10 sessions\")."},"type":{"type":"string","nullable":true,"description":"Optional plan type discriminator (e.g., \"monthly\", \"annual\", \"class_pack\")."},"status":{"type":"string","nullable":true,"description":"Current membership status. Common values: `active`, `on hold`, `cancelled`, `expired`, `pending cancel`. Free-form — call `GET /v3/segments/schema` to see `possible_values` observed in the current workroom. Mirrored to `member_status` on write.\n"},"member_status":{"type":"string","nullable":true,"description":"Segment-engine mirror of `status`. If you only set `status`, this is auto-populated (and vice versa) so segments querying either field find the contact."},"member_status_date":{"type":"string","format":"date-time","nullable":true,"description":"When the status was last set (used for tenure segments)."},"price":{"type":"number","nullable":true,"description":"Plan price in the account's currency."},"total_sessions":{"type":"integer","nullable":true,"description":"For class-pack / punch-card style memberships — the total number of sessions the plan grants at start (e.g., \"10-Class Pack\" → 10). Segment engine reads `memberships.total_sessions` as Numeric.\n"},"sessions_remaining":{"type":"integer","nullable":true,"description":"For class-pack / punch-card style memberships — sessions the contact has left. Decrement client-side or via CRM sync when a class is attended. Segments commonly filter on `memberships.sessions_remaining <= 2` for \"sessions running low\" campaigns.\n"},"location_id":{"type":"string","nullable":true,"description":"External location identifier (e.g., a Mariana / CRM location ID). Not a v3 `loc_` prefixed ID."},"start_date":{"type":"string","format":"date-time","nullable":true},"begin_date":{"type":"string","format":"date-time","nullable":true,"description":"Alias of `start_date` in some source systems."},"renewal_date":{"type":"string","format":"date-time","nullable":true},"next_billing_date":{"type":"string","format":"date-time","nullable":true},"end_date":{"type":"string","format":"date-time","nullable":true},"expiration_date":{"type":"string","format":"date-time","nullable":true},"renewal_type":{"type":"string","nullable":true,"description":"How the plan renews. Common values: `monthly`, `annual`, `manual`."},"invoice_ids":{"type":"array","nullable":true,"items":{"type":"string"},"description":"External invoice identifiers linked to this membership."}},"additionalProperties":true},"ConsentRecord":{"type":"object","required":["status"],"properties":{"status":{"$ref":"#/components/schemas/ConsentStatus"},"source":{"type":"string","description":"How consent was captured (`form_submission`, `import`, `api`, `admin_ui`, `double_opt_in_confirmed`).","nullable":true},"timestamp":{"$ref":"#/components/schemas/Timestamp","nullable":true},"source_ip":{"type":"string","nullable":true},"source_user_agent":{"type":"string","nullable":true}}},"ConsentStatus":{"type":"string","enum":["opted_in","opted_out","unknown","pending"],"description":"Consent state for a given channel. `opted_in` means the contact affirmatively consented (via form, import with proof, or explicit API call). `opted_out` means they revoked consent. `unknown` is the default for imported contacts without proof. `pending` means an opt-in confirmation was sent but not yet completed.\n"},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"LocationId":{"type":"string","pattern":"^loc_[0-9A-HJKMNP-TV-Z]{26}$"},"UserId":{"type":"string","pattern":"^usr_[0-9A-HJKMNP-TV-Z]{26}$"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"PipelineId":{"type":"string","pattern":"^pip_[0-9a-f]{24}$"},"StageId":{"type":"string","pattern":"^stg_[0-9a-f]{24}$"},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"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":{"/segments/{id}/contacts":{"get":{"tags":["Segments"],"operationId":"listSegmentContacts","summary":"List/export segment members. When EXPORTING, ASK which columns first — do not export all fields by default.","description":"⚠️ EXPORT RULE — READ FIRST: Plain member listing is unrestricted. But if the user is EXPORTING this segment (to CSV or a file), you MUST call with `export=true`, and then `fields` is mandatory: `export=true` with no `fields` returns 422 `export_columns_required` plus the column catalog — meaning ASK the user which columns they want (present the grouped human-readable options below), then call with `export=true&fields=<chosen keys>`. Never pick export columns yourself without asking, and never export all fields by default.\n\nPaginated members — this endpoint also backs \"export a segment\". Works for both static and dynamic segments. The list is read from the membership index, so it is never filtered by the segment's cached `size`: a segment showing `size: 0` with `last_evaluated_at: null` has simply never been evaluated, and may still list rows. On dynamic segments the list reflects the last evaluation — force a fresh one via `POST /v3/segments/{id}/refresh` if it is stale.\n\nEXPORTING — CHOOSE COLUMNS FIRST: by default the full contact is returned. Before exporting, ASK the customer which columns they want and present them in human-readable form, grouped exactly like the segment UI (show the Label; send the key). Pass the chosen keys as a comma-separated `fields` value; the response is then one row per contact keyed by the human Label, ready to write as CSV.\n  Personal Info — Contact Name → `col_name`, First Name → `personalinfo.firstname`, Last Name → `personalinfo.lastname`, Email → `personalinfo.email`, Phone → `personalinfo.phone`, Gender → `personalinfo.gender`, Date of Birth → `personalinfo.dob`, Birthday → `personalinfo.birthday`, City → `personalinfo.city`, State → `personalinfo.state`, Country → `personalinfo.country`, Added On → `personalinfo.added_on`\n  Account Info — Location → `accountinfo.location`, Location ID → `accountinfo.location_id`, Status → `accountinfo.status`, Type → `accountinfo.type`, Tags → `accountinfo.tags`, Source → `accountinfo.source`\n  Memberships — Membership Name → `memberships.name`, Membership Status → `memberships.status`, Membership Type → `memberships.type`, Membership Expiry → `memberships.end_date`, Membership Start Date → `memberships.start_date`, Membership Session Remaining → `memberships.membership_session_remaining`\n  Contract Info — Contract Name → `contracts.name`, Contract Status → `contracts.status`, Contract Expiry → `contracts.end_date`, Contract Start Date → `contracts.start_date`, First Contract Date → `contractinfo.first_contract_date`\n  Purchase Info — Last Purchased On → `purchases.last_purchase_date`, Last Purchased Item → `purchases.last_purchase_products`, Last Purchased Price → `purchases.last_purchase_price`, First Purchased On → `purchases.first_purchase_date`, First Purchased Item → `purchases.first_purchase_products`, First Purchased Price → `purchases.first_purchase_price`\n  Visit Info — Last Visit On → `visits.last_visit_date`, Last Visit Service → `visits.last_visit_services`, Last Visit Type → `visits.last_visit_type`, Last Visit Status → `visits.last_visit_status`, First Visit On → `visits.first_visit_date`, First Visit Service → `visits.first_visit_services`, First Visit Status → `visits.first_visit_status`, Total Visits → `visits.total_class_visits`\n  Pipeline — Pipeline Name → `sales.pipeline`, Stage → `sales.stage`, Status → `sales.status`, Responsible User → `sales.responsible`\n  Ratings — Rating → `ratings.rating`, Review → `ratings.review`, Last Rating On → `ratings.last_rating_on`\n  Custom — account-specific fields: call `describeSegmentSchema` (`GET /v3/segments/schema`), which exposes the account's custom attributes (the `attributes` map on the `segments` catalog — e.g. `member_id`, `join_date`, `zipcode`, …). Offer each key under a humanised label and pass the key verbatim as a `fields` value. (These are NOT on `retrieveSegment`, which returns only the saved segment definition.)\nExample: `fields=personalinfo.firstname,personalinfo.lastname,personalinfo.email,memberships.name`. Multiple memberships stack in the cell. Present/label columns with the human names above, never the raw keys.\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/BeforeParam"},{"name":"export","in":"query","required":false,"schema":{"type":"boolean"},"description":"Set `true` when the intent is to EXPORT this segment (CSV/file). With `export=true` and no `fields`, the endpoint returns 422 `export_columns_required` + the column catalog instead of data — forcing you to ask the user which columns first, then re-call with `fields`. Omit for normal member listing (no column restriction).\n"},{"name":"fields","in":"query","required":false,"schema":{"type":"string"},"description":"Comma-separated column KEYS to include, chosen by the user (see the grouped catalog in this operation's description). Required only for exports (`export=true`); optional for plain listing, where omitting it returns the full contact. DOTTED keys ARE supported and expected for exports (e.g. `personalinfo.firstname`, `memberships.name`, `accountinfo.location`), as are flat custom-attribute keys (e.g. `member_id`). When supplied, the response is one row per contact keyed by the human-readable column Label (ready to write as CSV). For exports, ASK the user which columns first — never default to all.\n"}],"responses":{"200":{"description":"A page of contacts.","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListEnvelope"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/Contact"}}}}]}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Add contact(s) to a static segment.

> Static segments only. Adding to a dynamic segment returns 422 \`wrong\_segment\_type\` — dynamic membership is defined by \`query\`. Duplicates are silently deduped. Max 1000 contacts per call; use the bulk contacts import for larger batches.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentMemberAdd":{"type":"object","required":["contact_ids"],"description":"Add contact(s) to a static segment. Duplicates are silently deduped.","properties":{"contact_ids":{"type":"array","items":{"$ref":"#/components/schemas/ContactId"},"minItems":1,"maxItems":1000}}},"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"},"Segment":{"type":"object","description":"A named collection of contacts. Either static (hand-managed list) or dynamic (query-defined). Discriminated by the `type` field, which is immutable after creation.\n","required":["id","object","type","name","size","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/SegmentId"},"object":{"type":"string","const":"segment"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom that owns this segment. A flow can only be triggered by segments in its own workroom — compare against `Flow.workroom_id`."},"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","nullable":true,"description":"The segment's criteria. **Present on BOTH static and dynamic segments** — a \"static\" segment only means the engine doesn't auto-refresh membership; the criteria that defined the initial membership list is still stored and returned. When diagnosing \"why did this contact match this segment?\", read `query.segment_users` (+ `with_or_segment_users` and `exclude_segment_users`). May be `null` only on segments imported without criteria or created empty.\n"},"size":{"type":"integer","minimum":0,"description":"Current member count. Eventually consistent — up to minutes of lag on dynamic segments."},"email_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid email."},"phone_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid phone."},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When this dynamic segment was last recomputed. Null on static."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"The segment folder this segment currently belongs to, or `null` if unfoldered."},"segment_summary":{"type":"string","nullable":true,"description":"AI-generated narrative summary of the segment's criteria. Populated on demand via `POST /v3/segments/{id}/summary`."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentType":{"type":"string","enum":["static","dynamic"],"description":"`static` — hand-managed member list. Contacts are added/removed explicitly.\n`dynamic` — query-defined membership. Auto-evaluated; membership changes as contact data changes.\nImmutable after creation.\n"},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"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"}}}},"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":{"/segments/{id}/contacts":{"post":{"tags":["Segments"],"operationId":"addSegmentContacts","summary":"Add contact(s) to a static segment.","description":"Static segments only. Adding to a dynamic segment returns 422 `wrong_segment_type` — dynamic membership is defined by `query`. Duplicates are silently deduped. Max 1000 contacts per call; use the bulk contacts import for larger batches.\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/SegmentMemberAdd"}}}},"responses":{"200":{"description":"Contacts added. Returns the updated segment with new `size`.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Segment"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Remove a contact from a static segment.

> Static segments only. Returns 422 \`wrong\_segment\_type\` on dynamic segments. Idempotent — removing a non-member returns 204.\
> \
> \*\*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":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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"}}}},"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"}}}}},"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":{"/segments/{id}/contacts/{contact_id}":{"delete":{"tags":["Segments"],"operationId":"removeSegmentContact","summary":"Remove a contact from a static segment.","description":"Static segments only. Returns 422 `wrong_segment_type` on dynamic segments. Idempotent — removing a non-member returns 204.\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":"Removed."},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Retrieve the segment DSL catalog for this account/workroom.

> Catalog for constructing a segment \`query\`. Returns the categories (\`memberships\`, \`purchases\`, \`visits\`, \`salesattributes\`, \`attributes\`/Custom, etc.), their attributes with data types and observed values from the current workroom's data, valid operators per data type, and each category's \`resolution\_hint\` describing where the attribute is stored on the contact doc.\
> \
> Workroom-aware: pass \`?workroom=\<name-or-id>\` to see values from a specific workroom, or omit for the account's default. The \`attributes\` (Custom) category resolves to \`userdetails.data.\<attr>\` — that's where account-defined custom fields live.\
> \
> Use this endpoint to:\
> &#x20; \- Discover the correct \`segment\` category + \`data\` attribute names to reference in \`segment\_users\`.\
> &#x20; \- Verify an attribute has a first-class category BEFORE creating a new custom\_field.\
> &#x20; \- See real-world \`possible\_values\` (a hint, not an exhaustive whitelist).\
> &#x20; \- Look up which \`operators\` are valid for a given attribute's \`data\_type\`.\
> \
> \`possible\_values\` is empty where no option list has been generated. It is populated only where someone has generated an option list for that attribute, which is true of a small minority of them. \`listAttributeValues\` returns the values an attribute actually holds in the workroom. A filter built on invented values saves without error and matches nobody.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentSchema":{"type":"object","description":"Machine-readable segment DSL catalog. Categories, attributes, valid operators per data type, and observed values in the current workroom. Merges three sources: (1) the global `segmentation_attributes` catalog, (2) this workroom's `segments` doc for `possible_values`, (3) the account's `v3_custom_fields` for Custom attributes.\n","properties":{"object":{"type":"string","enum":["segment_schema"]},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom this schema is scoped to. `null` when no workroom hint was provided."},"shared_contacts_enabled":{"type":"boolean","description":"Whether this account has shared contacts (linked copies across workrooms) enabled (`accountdetails.shared_contact_status`). It decides how to build an \"exclude X\" request — see the EXCLUDE entry in `notes[]` and the `exclude_segment_users` description. When `false`, express the exclusion as a negative condition inside `segment_users`; when `true`, put it in `exclude_segment_users` with the positive operator."},"categories":{"type":"array","items":{"$ref":"#/components/schemas/SegmentSchemaCategory"}},"operators_by_data_type":{"type":"object","description":"Data-type → operators. Use to validate operator choice when constructing a `segment_users[]` entry.","additionalProperties":{"type":"array","items":{"type":"string"}}},"notes":{"type":"array","items":{"type":"string"},"description":"Human-readable guidance about how to use the schema. Include verbatim in AI prompts when constructing segments."}}},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentSchemaCategory":{"type":"object","properties":{"value":{"type":"string","description":"Category key used in `segment_users[].segment`."},"title":{"type":"string","description":"Human-readable label."},"data_type":{"type":"string","description":"Legacy engine's internal category type."},"resolution_hint":{"type":"string","nullable":true,"description":"Where this category's attributes live at query time. Callers can use this to preview or debug matches without reading Segmentation.php."},"attributes":{"type":"array","items":{"$ref":"#/components/schemas/SegmentSchemaAttribute"}}}},"SegmentSchemaAttribute":{"type":"object","properties":{"value":{"type":"string","description":"Attribute key used in `segment_users[].data`."},"title":{"type":"string","description":"Human-readable label."},"data_type":{"type":"string","enum":["String","List","Numeric","Date","Day","Boolean"],"description":"Data type governing which operators apply."},"possible_values":{"type":"array","items":{"type":"string"},"description":"Values observed in this workroom's data. NOT an exhaustive whitelist — use as a hint."},"operators":{"type":"array","items":{"type":"string"},"description":"Operators supported for this attribute's `data_type`. ENGINE-NATIVE tokens — copy verbatim into `segment_users[].operator`. Human-friendly forms like \"In The Last\" and \"Equals\" are also accepted on write (normalized to engine-native), but the tokens listed here are the canonical set.\n"},"condition_template":{"type":"object","description":"Copy-and-fill template for constructing a `segment_users[]` entry that filters on this attribute. `segment`, `data`, `dataAlias`, and `data_type` are FIXED for this attribute — the caller must NOT invent new tokens like \"Add Date\" or \"Contact Email\". Replace `operator` with one from `operators[]` and `value` with the user-provided value.\n","properties":{"segment":{"type":"string"},"data":{"type":"string"},"dataAlias":{"type":"string"},"data_type":{"type":"string"},"operator":{"type":"string"},"value":{"type":"string"},"event":{"type":"string"}}},"source":{"type":"string","enum":["v3_custom_fields"],"description":"Present when the attribute comes from a v3_custom_fields definition, not the built-in catalog."},"resolution_path":{"type":"string","description":"Fully-qualified path on the contact doc — e.g. `data.company_size`. Set for Custom attributes."}}}}},"paths":{"/segments/schema":{"get":{"tags":["Segments"],"operationId":"describeSegmentSchema","summary":"Retrieve the segment DSL catalog for this account/workroom.","description":"Catalog for constructing a segment `query`. Returns the categories (`memberships`, `purchases`, `visits`, `salesattributes`, `attributes`/Custom, etc.), their attributes with data types and observed values from the current workroom's data, valid operators per data type, and each category's `resolution_hint` describing where the attribute is stored on the contact doc.\n\nWorkroom-aware: pass `?workroom=<name-or-id>` to see values from a specific workroom, or omit for the account's default. The `attributes` (Custom) category resolves to `userdetails.data.<attr>` — that's where account-defined custom fields live.\n\nUse this endpoint to:\n  - Discover the correct `segment` category + `data` attribute names to reference in `segment_users`.\n  - Verify an attribute has a first-class category BEFORE creating a new custom_field.\n  - See real-world `possible_values` (a hint, not an exhaustive whitelist).\n  - Look up which `operators` are valid for a given attribute's `data_type`.\n\n`possible_values` is empty where no option list has been generated. It is populated only where someone has generated an option list for that attribute, which is true of a small minority of them. `listAttributeValues` returns the values an attribute actually holds in the workroom. A filter built on invented values saves without error and matches nobody.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"The segment DSL schema.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentSchema"}}}}}}}}}
```

## List the values an attribute actually holds in this workroom.

> The values that exist in this workroom's data for one attribute — the API equivalent of the dashboard's \*\*Generate Options\*\* button.\
> \
> Catalog for building an \`Is One Of\` / \`Is Not One Of\` filter on any attribute whose \`possible\_values\` came back empty from \`describeSegmentSchema\`. Guessing values is the single most common way to produce a segment that saves cleanly and matches zero contacts: the values look plausible ("Gold", "Silver") while the workroom actually uses "Platinum Primary" and "Blue Card". Nothing errors, and the campaign built on it goes to nobody.\
> \
> Pass the attribute exactly as \`describeSegmentSchema\` names it: bare for Custom attributes (\`membership\_status\`), category-prefixed otherwise (\`memberships.status\`, \`personalinfo.state\`).\
> \
> \`status\` reports how complete \`values\` is:\
> &#x20; \- \`enumerated\` — \`values\` holds the real values, most common first. \`truncated: true\` means there are more than are shown.\
> &#x20; \- \`high\_cardinality\` — too many distinct values to enumerate, and too many to pick from. \`Contains\` or an exact \`Equals\` suit this better than \`Is One Of\`, which needs a list to choose from.\
> &#x20; \- \`unsupported\_type\` — a date, number or identity field. These are continuous or unique per contact; use a range or exact-match operator.\
> &#x20; \- \`empty\` — no contact in this workroom has this attribute set. Usually means the attribute name is wrong, or the data has not been imported yet. Say so rather than filtering on it.\
> \
> Results are cached on the workroom, including the negative verdicts, so repeat calls are free. The list is shared with the dashboard's own option list, so generating it here also populates Configure Workroom. Pass \`refresh=true\` to recompute when you have reason to believe the data changed. Rate limit bucket: \`search\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"AttributeValues":{"type":"object","description":"The values one attribute actually holds in a workroom. Always check `status` before reading `values` — an empty `values` means something different in each case.\n","properties":{"object":{"type":"string","enum":["attribute_values"]},"attribute":{"type":"string","description":"The attribute as requested."},"resolution_path":{"type":"string","description":"Where the attribute lives on the contact document. Custom attributes resolve under `data.`."},"status":{"type":"string","enum":["enumerated","high_cardinality","unsupported_type","empty"],"description":"`enumerated` — `values` is usable.\n`high_cardinality` — too many distinct values to list or to choose from; use Contains or Equals.\n`unsupported_type` — a date, number or identity field; use a range or exact match.\n`empty` — no contact here has this attribute set; check the name before filtering on it.\n"},"values":{"type":"array","items":{"type":"string"},"description":"Real values, most common first. Empty unless `status` is `enumerated`."},"distinct_total":{"type":"integer","nullable":true,"description":"How many distinct values exist. Null when the attribute was refused before counting."},"truncated":{"type":"boolean","description":"Present and true when there are more values than are shown."},"reason":{"type":"string","description":"Why the values could not be listed. Present for every status except `enumerated`."},"cached":{"type":"boolean","description":"True when answered from the stored option list rather than recomputed."},"computed_at":{"type":"string","format":"date-time"},"note":{"type":"string","description":"Human-readable footnote, e.g. that the list was capped."}}}}},"paths":{"/segments/attribute_values":{"get":{"tags":["Segments"],"operationId":"listAttributeValues","summary":"List the values an attribute actually holds in this workroom.","description":"The values that exist in this workroom's data for one attribute — the API equivalent of the dashboard's **Generate Options** button.\n\nCatalog for building an `Is One Of` / `Is Not One Of` filter on any attribute whose `possible_values` came back empty from `describeSegmentSchema`. Guessing values is the single most common way to produce a segment that saves cleanly and matches zero contacts: the values look plausible (\"Gold\", \"Silver\") while the workroom actually uses \"Platinum Primary\" and \"Blue Card\". Nothing errors, and the campaign built on it goes to nobody.\n\nPass the attribute exactly as `describeSegmentSchema` names it: bare for Custom attributes (`membership_status`), category-prefixed otherwise (`memberships.status`, `personalinfo.state`).\n\n`status` reports how complete `values` is:\n  - `enumerated` — `values` holds the real values, most common first. `truncated: true` means there are more than are shown.\n  - `high_cardinality` — too many distinct values to enumerate, and too many to pick from. `Contains` or an exact `Equals` suit this better than `Is One Of`, which needs a list to choose from.\n  - `unsupported_type` — a date, number or identity field. These are continuous or unique per contact; use a range or exact-match operator.\n  - `empty` — no contact in this workroom has this attribute set. Usually means the attribute name is wrong, or the data has not been imported yet. Say so rather than filtering on it.\n\nResults are cached on the workroom, including the negative verdicts, so repeat calls are free. The list is shared with the dashboard's own option list, so generating it here also populates Configure Workroom. Pass `refresh=true` to recompute when you have reason to believe the data changed. Rate limit bucket: `search`.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"name":"attribute","in":"query","required":true,"schema":{"type":"string"},"description":"Attribute name as `describeSegmentSchema` reports it, e.g. `membership_status` or `memberships.status`."},{"name":"refresh","in":"query","required":false,"schema":{"type":"boolean","default":false},"description":"Recompute instead of using the cached result. Use sparingly — enumeration scans contact data."}],"responses":{"200":{"description":"The attribute's values, or why they could not be listed.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AttributeValues"}}}}}}}}}
```

## Preview membership for a dynamic query without saving.

> Evaluate a query and return the estimated size. \`with\_or\_segment\_users\` and \`exclude\_segment\_users\` are applied exactly as the dashboard cron applies them to a saved segment, in the account's timezone. Set \`include\_sample: true\` to also get sample contacts (\`sample\_limit\`, default 10). Use this to iterate on a query before persisting it as a segment. Rate limit bucket: \`search\` (60 req/min default).\
> \
> A read: requires \`segments:read\` (a token with only \`segments:write\` is also accepted) and, for OAuth tokens, the dashboard role's Segments → View permission — view-only roles such as Analyst may preview. Own-records-only access does not restrict it (no saved segment is involved).<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentPreviewRequest":{"type":"object","required":["query"],"description":"Preview membership size for a query without saving anything. The whole query is evaluated — `segment_users`, `with_or_segment_users` and `exclude_segment_users` — combined, normalized and timezone-resolved exactly as the dashboard cron does for a saved segment, so the preview predicts the saved segment's size.\n","properties":{"query":{"$ref":"#/components/schemas/SegmentQuery"},"include_sample":{"type":"boolean","default":false,"description":"If true, include sample contacts in the response. Adds latency."},"sample_limit":{"type":"integer","minimum":1,"maximum":50,"default":10,"description":"Number of sample contacts when `include_sample` is true."}}},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"SegmentPreviewResponse":{"type":"object","required":["object","estimated_size"],"properties":{"object":{"type":"string","const":"segment_preview"},"workroom_id":{"type":"string","nullable":true},"workroom_count":{"type":"integer","description":"Number of workrooms the preview was scoped to."},"estimated_size":{"type":"integer","minimum":0,"nullable":true,"description":"Contacts matching the query (soft-deleted contacts excluded). `null` when the query carries an External Events count threshold (`operator2`/`value2`) the preview cannot apply — it would otherwise report the event-match total, which misleads; see the `external_events_count_threshold` warning. The saved segment's real size is computed by the external-events cron."},"engine":{"type":"string","const":"legacy_createWhere"},"timezone":{"type":"string","description":"The account timezone relative-date operators were evaluated in (the same one the cron uses)."},"warnings":{"type":"array","items":{"type":"string"},"description":"Non-fatal notes, e.g. `invalid_operator:` (saving this query would be rejected), `external_events_approximate:` (External Events count thresholds are evaluated only by the cron), `condition_matches_nothing:`."},"sample":{"type":"array","items":{"$ref":"#/components/schemas/Contact"},"description":"Present only if `include_sample: true` was requested."}}},"Contact":{"type":"object","description":"A person record. Central to almost every other resource in Gleantap.\nContacts have an internal id (`con_<24-hex>`) and optionally an external ID (`external_id`) you set from your own system. Both can be used to look up the record.\n","required":["id","object","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/ContactId"},"object":{"type":"string","const":"contact"},"external_id":{"type":"string","nullable":true,"description":"Your system's ID for this contact. Unique within the account. For contacts synced by an integration this is the member id the integration stores in `user_id` (returned when `external_id` itself is unset and `user_id` is not just the email/phone). `filter[external_id]` and `GET /v3/contacts/external_id:<x>` match either field, as string or integer."},"email":{"$ref":"#/components/schemas/Email","nullable":true},"phone":{"$ref":"#/components/schemas/PhoneE164","nullable":true,"description":"Stored the way every Gleantap writer stores it (formatPhone) — a `+` number is kept, a national number gets the account's country code (US/CA +1, GB +44, AU +61 with the trunk 0 dropped, NL, DK, LB, AE). Writes accept either form."},"first_name":{"type":"string","nullable":true,"maxLength":100},"last_name":{"type":"string","nullable":true,"maxLength":100},"date_of_birth":{"$ref":"#/components/schemas/Date","nullable":true,"description":"Stored as `personalinfo.dob` (date) + `personalinfo.birthday` (day of year), the pair birthday segments, campaigns and loyalty birthday rewards match on; `data.dob` is kept in step."},"locale":{"$ref":"#/components/schemas/Locale","nullable":true},"timezone":{"$ref":"#/components/schemas/Timezone","nullable":true},"tags":{"type":"array","items":{"$ref":"#/components/schemas/TagName"},"description":"All tags currently applied to this contact (`sales.tags`, the list the dashboard shows)."},"custom_fields":{"type":"object","additionalProperties":true,"description":"Account-defined custom fields. Schema is per-workroom (see `/v3/custom_fields`). Values are coerced to the declared type on write, as the dashboard CSV import does: date → stored date (a bare `YYYY-MM-DD` is midnight in the account timezone), number → integer/decimal, boolean → true/false. Dates are returned as ISO-8601 strings.\n"},"memberships":{"type":"array","items":{"$ref":"#/components/schemas/ContactMembership"},"description":"The contact's memberships/plans. Segment engine reads `memberships.status` / `memberships.type` / `memberships.renewal_date` / etc. directly off this array. Populated by CRM syncs (Mariana etc.) or by direct API writes.\n"},"consent":{"type":"object","description":"Per-channel consent records. Server-enforced on all marketing sends.","properties":{"sms":{"$ref":"#/components/schemas/ConsentRecord"},"email":{"$ref":"#/components/schemas/ConsentRecord"}}},"primary_location_id":{"$ref":"#/components/schemas/LocationId","nullable":true,"description":"Not populated yet (no Location resource). Use `location` / `location_id`."},"location":{"type":"string","nullable":true,"description":"The contact's location/club name as the integration or CSV import recorded it (`accountinfo.location`, else `data.location` / `data.location_name`). Numeric on some accounts; always returned as a string. Same value `filter[location]` matches."},"location_id":{"type":"string","nullable":true,"description":"The integration's location id (`accountinfo.location_id`, else `data.location_id`)."},"member_status":{"type":"string","nullable":true,"description":"Membership/account status as synced (`accountinfo.status`), e.g. `active`, `inactive`, `cancelled`. Vocabulary is the integration's."},"owner_user_id":{"$ref":"#/components/schemas/UserId","nullable":true},"segments":{"type":"array","items":{"$ref":"#/components/schemas/SegmentId"},"description":"Segment IDs this contact is currently a member of. Eventually consistent (up to minutes of lag from an underlying data change)."},"pipelines":{"type":"array","description":"Pipelines and stages this contact currently belongs to.","items":{"type":"object","properties":{"pipeline_id":{"$ref":"#/components/schemas/PipelineId"},"stage_id":{"$ref":"#/components/schemas/StageId","nullable":true},"stage_name":{"type":"string","nullable":true},"status":{"type":"string"},"added_at":{"$ref":"#/components/schemas/Timestamp"},"last_updated_at":{"$ref":"#/components/schemas/Timestamp"}}}},"lifecycle_stage":{"type":"string","nullable":true,"description":"Stage label stored in `accountinfo.type`. The values in real data are `member`, `prospect`, `past` and `non-member`, plus raw labels integrations pass through in their own case (`Kid`, `Parent`, `Individual`, …). Not enforced; `filter[lifecycle_stage]` matches case-insensitively. Writing `member` (or `customer`) also sets `accountinfo.member: 1`; anything other than member/former sets `accountinfo.prospect: 1`.\n"},"last_seen_at":{"$ref":"#/components/schemas/Timestamp","nullable":true},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp","description":"Last change by any writer — the later of v3's own stamp and the `last_updated_on` the integrations and dashboard maintain. `sort=updated_at` orders by `last_updated_on`."},"deleted_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"Set if this contact was soft-deleted. Soft-deleted contacts are hidden from all list endpoints, the dashboard and every send by default; include `?filter[deleted]=true` to see them. Merged-away contacts also carry it."},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"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"},"Email":{"type":"string","format":"email"},"PhoneE164":{"type":"string","description":"E.164 international phone format.","pattern":"^\\+[1-9]\\d{1,14}$"},"Date":{"type":"string","format":"date","description":"Calendar date (no time), ISO 8601 `YYYY-MM-DD`."},"Locale":{"type":"string","description":"BCP 47 locale tag."},"Timezone":{"type":"string","description":"IANA timezone name."},"TagName":{"type":"string","description":"Tag name. Case-preserving, but case-insensitive on match. Whitespace preserved.","pattern":"^[^\\n\\r]{1,100}$"},"ContactMembership":{"type":"object","description":"A single membership/plan on a contact. Stored inline on `userdetails.memberships[]` (the segment DSL's `memberships.*` category queries this array via `$elemMatch`). Purchases live on events, but memberships live here because the segment engine needs cheap membership-status lookups without JOINing.\n","required":["id","name"],"properties":{"id":{"type":"string","description":"External identifier (from CRM / source system). Not a v3-prefixed ID."},"name":{"type":"string","description":"Plan name (e.g., \"Unlimited Monthly\", \"Class Pack — 10 sessions\")."},"type":{"type":"string","nullable":true,"description":"Optional plan type discriminator (e.g., \"monthly\", \"annual\", \"class_pack\")."},"status":{"type":"string","nullable":true,"description":"Current membership status. Common values: `active`, `on hold`, `cancelled`, `expired`, `pending cancel`. Free-form — call `GET /v3/segments/schema` to see `possible_values` observed in the current workroom. Mirrored to `member_status` on write.\n"},"member_status":{"type":"string","nullable":true,"description":"Segment-engine mirror of `status`. If you only set `status`, this is auto-populated (and vice versa) so segments querying either field find the contact."},"member_status_date":{"type":"string","format":"date-time","nullable":true,"description":"When the status was last set (used for tenure segments)."},"price":{"type":"number","nullable":true,"description":"Plan price in the account's currency."},"total_sessions":{"type":"integer","nullable":true,"description":"For class-pack / punch-card style memberships — the total number of sessions the plan grants at start (e.g., \"10-Class Pack\" → 10). Segment engine reads `memberships.total_sessions` as Numeric.\n"},"sessions_remaining":{"type":"integer","nullable":true,"description":"For class-pack / punch-card style memberships — sessions the contact has left. Decrement client-side or via CRM sync when a class is attended. Segments commonly filter on `memberships.sessions_remaining <= 2` for \"sessions running low\" campaigns.\n"},"location_id":{"type":"string","nullable":true,"description":"External location identifier (e.g., a Mariana / CRM location ID). Not a v3 `loc_` prefixed ID."},"start_date":{"type":"string","format":"date-time","nullable":true},"begin_date":{"type":"string","format":"date-time","nullable":true,"description":"Alias of `start_date` in some source systems."},"renewal_date":{"type":"string","format":"date-time","nullable":true},"next_billing_date":{"type":"string","format":"date-time","nullable":true},"end_date":{"type":"string","format":"date-time","nullable":true},"expiration_date":{"type":"string","format":"date-time","nullable":true},"renewal_type":{"type":"string","nullable":true,"description":"How the plan renews. Common values: `monthly`, `annual`, `manual`."},"invoice_ids":{"type":"array","nullable":true,"items":{"type":"string"},"description":"External invoice identifiers linked to this membership."}},"additionalProperties":true},"ConsentRecord":{"type":"object","required":["status"],"properties":{"status":{"$ref":"#/components/schemas/ConsentStatus"},"source":{"type":"string","description":"How consent was captured (`form_submission`, `import`, `api`, `admin_ui`, `double_opt_in_confirmed`).","nullable":true},"timestamp":{"$ref":"#/components/schemas/Timestamp","nullable":true},"source_ip":{"type":"string","nullable":true},"source_user_agent":{"type":"string","nullable":true}}},"ConsentStatus":{"type":"string","enum":["opted_in","opted_out","unknown","pending"],"description":"Consent state for a given channel. `opted_in` means the contact affirmatively consented (via form, import with proof, or explicit API call). `opted_out` means they revoked consent. `unknown` is the default for imported contacts without proof. `pending` means an opt-in confirmation was sent but not yet completed.\n"},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"LocationId":{"type":"string","pattern":"^loc_[0-9A-HJKMNP-TV-Z]{26}$"},"UserId":{"type":"string","pattern":"^usr_[0-9A-HJKMNP-TV-Z]{26}$"},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"PipelineId":{"type":"string","pattern":"^pip_[0-9a-f]{24}$"},"StageId":{"type":"string","pattern":"^stg_[0-9a-f]{24}$"},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"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"}}}},"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":{"/segments/preview":{"post":{"tags":["Segments"],"operationId":"previewSegment","summary":"Preview membership for a dynamic query without saving.","description":"Evaluate a query and return the estimated size. `with_or_segment_users` and `exclude_segment_users` are applied exactly as the dashboard cron applies them to a saved segment, in the account's timezone. Set `include_sample: true` to also get sample contacts (`sample_limit`, default 10). Use this to iterate on a query before persisting it as a segment. Rate limit bucket: `search` (60 req/min default).\n\nA read: requires `segments:read` (a token with only `segments:write` is also accepted) and, for OAuth tokens, the dashboard role's Segments → View permission — view-only roles such as Analyst may preview. Own-records-only access does not restrict it (no saved segment is involved).\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/SegmentPreviewRequest"}}}},"responses":{"200":{"description":"Preview result.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentPreviewResponse"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"422":{"$ref":"#/components/responses/Unprocessable"},"429":{"$ref":"#/components/responses/TooManyRequests"}}}}}}
```

## Force recompute of a dynamic segment.

> Re-evaluate the segment now — synchronously. Membership is recomputed with the same engine the preview and the scheduled cron use, written to the membership index, and \`size\` / \`email\_count\` / \`phone\_count\` / \`last\_evaluated\_at\` are updated before the response is returned. Dynamic segments also refresh on a schedule (default \~30 min, longer for segments with external-event conditions); this forces an immediate pass.\
> \
> The response is the segment's state AFTER the recompute, so there is nothing to poll: \`status: completed\` with the new counts, or \`status: queued\` when the evaluation itself failed — in that case nothing was written, \`reason\` names the failure, and the segment is left marked for the dashboard cron's next pass (a later \`GET /v3/segments/{id}\` shows whether it filled in). Returns 422 \`wrong\_segment\_type\` on static segments (nothing to refresh). Rate limit bucket: \`search\`.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentRefresh":{"type":"object","description":"Result of a forced recompute — the segment's state after the evaluation attempt, so the caller can verify the refresh from this response alone (there is no job to poll).\n","required":["object","segment_id","status"],"properties":{"object":{"type":"string","const":"segment_refresh"},"segment_id":{"$ref":"#/components/schemas/SegmentId"},"status":{"type":"string","enum":["completed","queued"],"description":"`completed` — evaluated inline; the counts below are the new values. `queued` — the evaluation failed, nothing was written, and the segment was left marked for the dashboard cron; `reason` says why."},"size":{"type":"integer","minimum":0,"description":"Member count after the evaluation. A zero size on a queued refresh means not evaluated, not empty."},"email_count":{"type":"integer","minimum":0},"phone_count":{"type":"integer","minimum":0},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When membership was last computed. `null` means never evaluated."},"reason":{"type":"string","description":"Present only when the refresh was queued — why the evaluation failed."}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"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"}}}},"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":{"/segments/{id}/refresh":{"post":{"tags":["Segments"],"operationId":"refreshSegment","summary":"Force recompute of a dynamic segment.","description":"Re-evaluate the segment now — synchronously. Membership is recomputed with the same engine the preview and the scheduled cron use, written to the membership index, and `size` / `email_count` / `phone_count` / `last_evaluated_at` are updated before the response is returned. Dynamic segments also refresh on a schedule (default ~30 min, longer for segments with external-event conditions); this forces an immediate pass.\n\nThe response is the segment's state AFTER the recompute, so there is nothing to poll: `status: completed` with the new counts, or `status: queued` when the evaluation itself failed — in that case nothing was written, `reason` names the failure, and the segment is left marked for the dashboard cron's next pass (a later `GET /v3/segments/{id}` shows whether it filled in). Returns 422 `wrong_segment_type` on static segments (nothing to refresh). Rate limit bucket: `search`.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Segment recomputed. Counts are the freshly evaluated values.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentRefresh"}}}},"202":{"description":"Evaluation failed; the segment is queued for the dashboard cron's next pass. Nothing was written.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentRefresh"}}}},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/Unprocessable"},"429":{"$ref":"#/components/responses/TooManyRequests"},"500":{"description":"`refresh_engine_error` — the evaluation could not run at all (no workroom, database handle unavailable). Nothing was written."}}}}}}
```

## List segment folders.

> Backed by the dashboard's \`segment\_folder\` collection.

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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`."}}},"SegmentFolder":{"type":"object","properties":{"object":{"type":"string","const":"segment_folder"},"id":{"$ref":"#/components/schemas/SegmentFolderId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"name":{"type":"string"},"segment_count":{"type":"integer","minimum":0},"created_at":{"type":"string","format":"date-time","nullable":true},"updated_at":{"type":"string","format":"date-time","nullable":true}}},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"}}},"paths":{"/segments/folders":{"get":{"tags":["Segments"],"operationId":"listSegmentFolders","summary":"List segment folders.","description":"Backed by the dashboard's `segment_folder` collection.","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"}],"responses":{"200":{"description":"A page of folders.","content":{"application/json":{"schema":{"allOf":[{"$ref":"#/components/schemas/ListEnvelope"},{"type":"object","properties":{"data":{"type":"array","items":{"$ref":"#/components/schemas/SegmentFolder"}}}}]}}}}}}}}}
```

## Create a segment folder.

> Names must be unique within a workroom; conflicts return 409.\
> \
> Requires the folder name. 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":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentFolderCreate":{"type":"object","required":["name"],"properties":{"name":{"type":"string","minLength":1},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"}}},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentFolder":{"type":"object","properties":{"object":{"type":"string","const":"segment_folder"},"id":{"$ref":"#/components/schemas/SegmentFolderId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"name":{"type":"string"},"segment_count":{"type":"integer","minimum":0},"created_at":{"type":"string","format":"date-time","nullable":true},"updated_at":{"type":"string","format":"date-time","nullable":true}}},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."}}},"paths":{"/segments/folders":{"post":{"tags":["Segments"],"operationId":"createSegmentFolder","summary":"Create a segment folder.","description":"Names must be unique within a workroom; conflicts return 409.\n\nRequires the folder name. 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"}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentFolderCreate"}}}},"responses":{"201":{"description":"Folder created.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentFolder"}}}},"409":{"description":"Name conflict."}}}}}}
```

## GET /segments/folders/{id}

> Retrieve a segment folder.

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentFolder":{"type":"object","properties":{"object":{"type":"string","const":"segment_folder"},"id":{"$ref":"#/components/schemas/SegmentFolderId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"name":{"type":"string"},"segment_count":{"type":"integer","minimum":0},"created_at":{"type":"string","format":"date-time","nullable":true},"updated_at":{"type":"string","format":"date-time","nullable":true}}},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"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":{"/segments/folders/{id}":{"get":{"tags":["Segments"],"operationId":"retrieveSegmentFolder","summary":"Retrieve a segment folder.","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Folder.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentFolder"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## PATCH /segments/folders/{id}

> Rename a segment folder.

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentFolderUpdate":{"type":"object","properties":{"name":{"type":"string","minLength":1}}},"SegmentFolder":{"type":"object","properties":{"object":{"type":"string","const":"segment_folder"},"id":{"$ref":"#/components/schemas/SegmentFolderId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"name":{"type":"string"},"segment_count":{"type":"integer","minimum":0},"created_at":{"type":"string","format":"date-time","nullable":true},"updated_at":{"type":"string","format":"date-time","nullable":true}}},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"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":{"/segments/folders/{id}":{"patch":{"tags":["Segments"],"operationId":"updateSegmentFolder","summary":"Rename a segment folder.","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/SegmentFolderUpdate"}}}},"responses":{"200":{"description":"Updated folder.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentFolder"}}}},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"Name conflict."}}}}}}
```

## Delete a segment folder.

> Segments in the folder become unfoldered (they are not deleted).\
> \
> \*\*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":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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"}}}}},"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":{"/segments/folders/{id}":{"delete":{"tags":["Segments"],"operationId":"deleteSegmentFolder","summary":"Delete a segment folder.","description":"Segments in the folder become unfoldered (they are not deleted).\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"}}}}}}
```

## GET /segments/{id}/sharing

> Read a segment's sharing configuration.

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentSharing":{"type":"object","properties":{"object":{"type":"string","const":"segment_sharing"},"segment_id":{"$ref":"#/components/schemas/SegmentId"},"allowed_roles":{"type":"object","description":"Boolean map keyed by role. Accepted keys: `me`, `Admin`, `WorkroomAdmin`, `Marketing`, `Sales`, `Analyst`, `Other`. Unknown keys are dropped on write. Missing keys read as false.\n","additionalProperties":{"type":"boolean"}},"other_allowed_user_ids":{"type":"array","items":{"$ref":"#/components/schemas/StaffId"}},"role_updated_on":{"type":"string","format":"date-time","nullable":true}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"StaffId":{"type":"string","pattern":"^usr_[0-9a-f]{24}$","description":"A staff user (from the legacy `users` collection). Used for `owner_id`, `responsible_id`, `created_by`, `assigned_to`, etc."},"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":{"/segments/{id}/sharing":{"get":{"tags":["Segments"],"operationId":"retrieveSegmentSharing","summary":"Read a segment's sharing configuration.","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Sharing config.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentSharing"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Replace a segment's sharing configuration.

> Full-replace (matches the dashboard's checkbox POST — unchecked boxes just don't appear). Accepted role keys: \`me\`, \`Admin\`, \`WorkroomAdmin\`, \`Marketing\`, \`Sales\`, \`Analyst\`, \`Other\`. When \`Other\` is true, \`other\_allowed\_user\_ids\[]\` must contain at least one valid staff ID or 400 is returned.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentSharingUpdate":{"type":"object","properties":{"allowed_roles":{"type":"object","additionalProperties":{"type":"boolean"}},"other_allowed_user_ids":{"type":"array","items":{"$ref":"#/components/schemas/StaffId"},"description":"Required (non-empty) when `allowed_roles.Other` is true; otherwise ignored."}}},"StaffId":{"type":"string","pattern":"^usr_[0-9a-f]{24}$","description":"A staff user (from the legacy `users` collection). Used for `owner_id`, `responsible_id`, `created_by`, `assigned_to`, etc."},"SegmentSharing":{"type":"object","properties":{"object":{"type":"string","const":"segment_sharing"},"segment_id":{"$ref":"#/components/schemas/SegmentId"},"allowed_roles":{"type":"object","description":"Boolean map keyed by role. Accepted keys: `me`, `Admin`, `WorkroomAdmin`, `Marketing`, `Sales`, `Analyst`, `Other`. Unknown keys are dropped on write. Missing keys read as false.\n","additionalProperties":{"type":"boolean"}},"other_allowed_user_ids":{"type":"array","items":{"$ref":"#/components/schemas/StaffId"}},"role_updated_on":{"type":"string","format":"date-time","nullable":true}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"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"}}}}}},"paths":{"/segments/{id}/sharing":{"put":{"tags":["Segments"],"operationId":"updateSegmentSharing","summary":"Replace a segment's sharing configuration.","description":"Full-replace (matches the dashboard's checkbox POST — unchecked boxes just don't appear). Accepted role keys: `me`, `Admin`, `WorkroomAdmin`, `Marketing`, `Sales`, `Analyst`, `Other`. When `Other` is true, `other_allowed_user_ids[]` must contain at least one valid staff ID or 400 is returned.\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/SegmentSharingUpdate"}}}},"responses":{"200":{"description":"Updated sharing config.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentSharing"}}}},"400":{"$ref":"#/components/responses/BadRequest"},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Compute a demographic/behavior report for a segment.

> Ported from the dashboard's Audience::segmentGraphs — same aggregations against \`userdetails.segments1\`, same cache (\`segment\_report\_data\`) with a 4-day TTL. A cached report is reused only while the live membership count still matches the one it was computed over and the stored payload is the current shape version, so \`segment\_size\` and the bucket totals always describe the same population.\
> \
> Capped at 50,000 members. The cap is checked against the LIVE count, not the stored segment size, so a dynamic segment that has never been evaluated cannot slip past it; at 50,000 or more the request returns 413.\
> \
> Report shapes by \`type\`:\
> \- \`gender\`  → \`\[{gender, count}]\` normalized to Male, Female, Other, Unknown\
> \- \`age\`     → buckets: \`<18, 18-24, 25-30, 31-40, 41-50, 50+, Unknown\`\
> \- \`lifespan\` → buckets by \`add\_date\`: \`< 2 mo, 2 - 6 mo, 6 - 12 mo, 12 - 24 mo, 24 mo +\`, plus \`Unknown\`\
> \- \`behaviour\_analysis\` → last-3-calendar-month rollup: \`{behaviorMonthLabel\[], purchaseMonth\[], checkinMonth\[]}\`, always 3 labels with zero counts when no activity\
> \
> A contact whose \`dob\` or \`add\_date\` is not a parseable date is counted as \`Unknown\` rather than failing the request — one bad record does not take the report down.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentReport":{"type":"object","properties":{"object":{"type":"string","const":"segment_report"},"segment_id":{"$ref":"#/components/schemas/SegmentId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"type":{"type":"string","enum":["gender","age","lifespan","behaviour_analysis"]},"segment_size":{"type":"integer","description":"Membership counted at report time, over the same `userdetails.segments1` population the buckets are aggregated from — so the bucket counts always sum to this value. Not the stored `usersegments.size`, which is only as fresh as the last refresh and is 0 for a never-evaluated dynamic segment."},"generated_at":{"type":"string","format":"date-time","nullable":true},"data":{"description":"Shape varies by `type`. For gender: `[{gender, count}]` normalized to Male, Female, Other, Unknown (`Unknown` always present; it absorbs null, empty and unrecognised values). For age: `[{age, count}]` (<18, 18-24, 25-30, 31-40, 41-50, 50+, Unknown — `Unknown` always present and holds contacts with no DOB or an unparseable one). For lifespan: `[{lifespan, count}]` (< 2 mo, 2 - 6 mo, 6 - 12 mo, 12 - 24 mo, 24 mo +, plus Unknown when any `add_date` is missing or unparseable). For behaviour_analysis: `{behaviorMonthLabel[], purchaseMonth[], checkinMonth[]}` for the last 3 calendar months, always with 3 labels and zero counts when there was no activity."}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"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":{"/segments/{id}/report":{"get":{"tags":["Segments"],"operationId":"retrieveSegmentReport","summary":"Compute a demographic/behavior report for a segment.","description":"Ported from the dashboard's Audience::segmentGraphs — same aggregations against `userdetails.segments1`, same cache (`segment_report_data`) with a 4-day TTL. A cached report is reused only while the live membership count still matches the one it was computed over and the stored payload is the current shape version, so `segment_size` and the bucket totals always describe the same population.\n\nCapped at 50,000 members. The cap is checked against the LIVE count, not the stored segment size, so a dynamic segment that has never been evaluated cannot slip past it; at 50,000 or more the request returns 413.\n\nReport shapes by `type`:\n- `gender`  → `[{gender, count}]` normalized to Male, Female, Other, Unknown\n- `age`     → buckets: `<18, 18-24, 25-30, 31-40, 41-50, 50+, Unknown`\n- `lifespan` → buckets by `add_date`: `< 2 mo, 2 - 6 mo, 6 - 12 mo, 12 - 24 mo, 24 mo +`, plus `Unknown`\n- `behaviour_analysis` → last-3-calendar-month rollup: `{behaviorMonthLabel[], purchaseMonth[], checkinMonth[]}`, always 3 labels with zero counts when no activity\n\nA contact whose `dob` or `add_date` is not a parseable date is counted as `Unknown` rather than failing the request — one bad record does not take the report down.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"},{"name":"type","in":"query","required":true,"schema":{"type":"string","enum":["gender","age","lifespan","behaviour_analysis"]}}],"responses":{"200":{"description":"Report data.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentReport"}}}},"404":{"$ref":"#/components/responses/NotFound"},"413":{"description":"Segment too large to report on (>50,000 members). Narrow the segment first."},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## GET /segments/{id}/facebook\_audience

> Read Facebook Custom Audience sync status for a segment.

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentFacebookAudience":{"type":"object","properties":{"object":{"type":"string","const":"segment_facebook_audience"},"segment_id":{"$ref":"#/components/schemas/SegmentId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"enabled":{"type":"boolean"},"workroom_configured":{"type":"boolean","description":"True iff the workroom has an FB Ad Account linked in the dashboard."},"ad_account_id":{"type":"string","nullable":true},"custom_audience_id":{"type":"string","nullable":true,"description":"Populated once the dashboard cron creates the audience on Meta."},"last_error":{"type":"string","nullable":true,"description":"Last pending error from `facebook_custom_audience_error`, if any."}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"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":{"/segments/{id}/facebook_audience":{"get":{"tags":["Segments"],"operationId":"retrieveSegmentFacebookAudience","summary":"Read Facebook Custom Audience sync status for a segment.","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"FB audience sync state.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentFacebookAudience"}}}},"404":{"$ref":"#/components/responses/NotFound"}}}}}}
```

## Enable or disable FB Custom Audience sync for a segment.

> Enable requires the workroom to have an FB Ad Account linked (setup is dashboard-only). If not linked, 422 \`workroom\_not\_configured\` is returned. Actual list creation + member sync runs in the dashboard's background cron once enabled.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"SegmentFacebookAudienceUpdate":{"type":"object","required":["enabled"],"properties":{"enabled":{"type":"boolean"}}},"SegmentFacebookAudience":{"type":"object","properties":{"object":{"type":"string","const":"segment_facebook_audience"},"segment_id":{"$ref":"#/components/schemas/SegmentId"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId"},"enabled":{"type":"boolean"},"workroom_configured":{"type":"boolean","description":"True iff the workroom has an FB Ad Account linked in the dashboard."},"ad_account_id":{"type":"string","nullable":true},"custom_audience_id":{"type":"string","nullable":true,"description":"Populated once the dashboard cron creates the audience on Meta."},"last_error":{"type":"string","nullable":true,"description":"Last pending error from `facebook_custom_audience_error`, if any."}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"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":{"/segments/{id}/facebook_audience":{"put":{"tags":["Segments"],"operationId":"updateSegmentFacebookAudience","summary":"Enable or disable FB Custom Audience sync for a segment.","description":"Enable requires the workroom to have an FB Ad Account linked (setup is dashboard-only). If not linked, 422 `workroom_not_configured` is returned. Actual list creation + member sync runs in the dashboard's background cron once enabled.\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/SegmentFacebookAudienceUpdate"}}}},"responses":{"200":{"description":"Updated sync state.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SegmentFacebookAudience"}}}},"404":{"$ref":"#/components/responses/NotFound"},"422":{"$ref":"#/components/responses/Unprocessable"}}}}}}
```

## Freeze a dynamic segment's current membership as static.

> Evaluates the segment's criteria NOW, then flips \`type\` to \`static\` and stamps \`last\_evaluated\_at\`. The evaluation is the same one \`refreshSegment\` and the preview run (OR groups, excludes, external events, account timezone), so the frozen list is the segment's membership at the moment of the call — not whatever the last cron pass happened to leave behind. Idempotent guard: 409 \`already\_static\` if the segment is already static.\
> \
> If the evaluation fails, \*\*nothing is converted\*\* — the response is 500 \`snapshot\_evaluation\_failed\`, the segment stays dynamic, and the detail names the failure. A static segment frozen from an unevaluated membership list would be wrong permanently, since nothing recomputes a static segment afterwards.\
> \
> \*\*Irreversible.\*\* Converting to static freezes membership: the segment stops tracking its criteria and cannot be converted back.<br>

```json
{"openapi":"3.1.0","info":{"title":"Gleantap API v3","version":"2026-05-27"},"tags":[{"name":"Segments","description":"Named collections of contacts. Static (hand-managed member lists) or dynamic (query-defined, auto-evaluated). Full query DSL documented in the Segment Query DSL companion spec."}],"servers":[{"url":"https://api.gleantap.com/v3","description":"Production. There is no separate sandbox."}],"security":[{"ApiKey":[]},{"OAuth2":["segments: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":{"Segment":{"type":"object","description":"A named collection of contacts. Either static (hand-managed list) or dynamic (query-defined). Discriminated by the `type` field, which is immutable after creation.\n","required":["id","object","type","name","size","created_at","updated_at"],"properties":{"id":{"$ref":"#/components/schemas/SegmentId"},"object":{"type":"string","const":"segment"},"workroom_id":{"$ref":"#/components/schemas/WorkroomId","nullable":true,"description":"The workroom that owns this segment. A flow can only be triggered by segments in its own workroom — compare against `Flow.workroom_id`."},"type":{"$ref":"#/components/schemas/SegmentType"},"name":{"type":"string","maxLength":200},"description":{"type":"string","nullable":true,"maxLength":2000},"query":{"$ref":"#/components/schemas/SegmentQuery","nullable":true,"description":"The segment's criteria. **Present on BOTH static and dynamic segments** — a \"static\" segment only means the engine doesn't auto-refresh membership; the criteria that defined the initial membership list is still stored and returned. When diagnosing \"why did this contact match this segment?\", read `query.segment_users` (+ `with_or_segment_users` and `exclude_segment_users`). May be `null` only on segments imported without criteria or created empty.\n"},"size":{"type":"integer","minimum":0,"description":"Current member count. Eventually consistent — up to minutes of lag on dynamic segments."},"email_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid email."},"phone_count":{"type":"integer","minimum":0,"description":"Members with a non-empty, non-invalid phone."},"last_evaluated_at":{"$ref":"#/components/schemas/Timestamp","nullable":true,"description":"When this dynamic segment was last recomputed. Null on static."},"folder_id":{"$ref":"#/components/schemas/SegmentFolderId","nullable":true,"description":"The segment folder this segment currently belongs to, or `null` if unfoldered."},"segment_summary":{"type":"string","nullable":true,"description":"AI-generated narrative summary of the segment's criteria. Populated on demand via `POST /v3/segments/{id}/summary`."},"created_at":{"$ref":"#/components/schemas/Timestamp"},"updated_at":{"$ref":"#/components/schemas/Timestamp"},"metadata":{"$ref":"#/components/schemas/Metadata"}}},"SegmentId":{"type":"string","pattern":"^seg_[0-9A-HJKMNP-TV-Z]{26}$"},"WorkroomId":{"type":"string","pattern":"^wrm_[0-9a-f]{24}$"},"SegmentType":{"type":"string","enum":["static","dynamic"],"description":"`static` — hand-managed member list. Contacts are added/removed explicitly.\n`dynamic` — query-defined membership. Auto-evaluated; membership changes as contact data changes.\nImmutable after creation.\n"},"SegmentQuery":{"type":"object","description":"The segment criteria. **Present on BOTH `static` and `dynamic` segments** — \"static\" only means the engine doesn't auto-refresh membership; the criteria that defined the segment is still on the doc, and diagnostic tools (like \"why did this contact match this segment?\") MUST read it here.\n\nFull match logic:\n\n  (all `segment_users` ANDed together)\n  OR (all conditions in `with_or_segment_users[0]` ANDed)\n  OR (all conditions in `with_or_segment_users[1]` ANDed)\n  OR ...\n  MINUS contacts removed by `exclude_segment_users` (all ANDed) — self-match or shared-copy match per the account setting below\n\nHow `exclude_segment_users` matches depends on the account's `shared_contact_status` (surfaced as `shared_contacts_enabled` on `GET /segments/schema`). When shared contacts are ENABLED it is the dashboard's \"exclude shared contacts\" rule: a contact is removed when one of its linked copies in another workroom (`shared_contacts[]`) matches these conditions, NOT when the contact itself matches. When shared contacts are OFF it is a plain self-subtraction: the contact is removed when its OWN fields match. The exclusion can be any condition (attribute match, event done, tag, form filled — just the positive form of what to exclude). Either way the segment must keep at least one primary condition in `segment_users`; an exclude-only (or `with_or`-only) query is rejected. To exclude by a contact's own attributes regardless of the account setting, you can also use a negative condition in `segment_users` (e.g. `Is Not One Of`, `Has not Filled a Form`, `Does Not Contain`).\n\nConditions are stored in the exact tokens the dashboard's segment engine evaluates: friendly category names are rewritten on write (`Custom`/`attributes` → `Attributes`, `email_engagement` → `EmailCampaigns`, `salesattributes` → `sales`, …), and an absolute-date `<`/`>` on a Date field is stored as `Before`/`After` with an `MM-DD-YYYY` value. A retrieved segment therefore shows the stored (engine) form.\n\nThere is no additional `all/any/none` grouping. Express further OR via multi-value operators (`Is One Of`, `Segments` with an array).\n","properties":{"segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Base inclusion conditions. All ANDed. A contact must satisfy every one to be included via this group."},"with_or_segment_users":{"type":"array","description":"Alternate inclusion groups. Each inner array is a set of conditions that are ANDed together; the outer array is OR-joined with `segment_users` and each other inner array. Use this to build \"criteria A OR criteria B\" queries without touching the top-level `segment_users`.\n","items":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"}}},"exclude_segment_users":{"type":"array","items":{"$ref":"#/components/schemas/SegmentCondition"},"description":"Exclusion conditions, ANDed. How they match depends on the account's `shared_contact_status` — shared-copy match when shared contacts are ON (a contact is removed when a linked copy in another workroom, `shared_contacts[]`, matches all of them), self-match when OFF (removed when the contact's own fields match all of them). Same condition shape as `segment_users`. Cannot stand alone — `segment_users` must be non-empty. See the match logic above."}}},"SegmentCondition":{"type":"object","description":"A single condition in a dynamic segment query. Shape and operator vocabulary are documented in the Segment Query DSL companion doc — the query language supports 28 segment types (Attributes, Tags, Event Trigger, External Events, Segments, SalesAttributes, Forms, Flows, Optin, and more) and 60+ operators. This schema is intentionally loose to accommodate that surface; the server validates the concrete shape.\n","required":["segment","operator"],"additionalProperties":true,"properties":{"segment":{"type":"string","description":"Segment-type discriminator. Full inventory in the DSL doc. Common values include `Attributes`, `Tags`, `Country`, `City`, `Event Trigger`, `External Events`, `Segments`, `SalesAttributes`, `Forms`, `Flows`, `SMS Optin`, `SMS Opted Out`, `Email Topics`, `Add Date`, `Last Access`.\n"},"data":{"type":"string","description":"Field or attribute within the segment type. E.g., `first_name`, `city`, `sales.pipeline.stage`.","nullable":true},"event":{"type":"string","description":"Event name — used only when `segment` is `Event Trigger`.","nullable":true},"operator":{"type":"string","description":"Operator vocabulary. Full list in the DSL doc. Common: `=`, `!=`, `<`, `>` (numeric — on a Date field they are stored as `Before`/`After`), `Contains`, `Does Not Contain`, `Is One Of`, `Is Not One Of`, `Is Empty`, `Is Not Empty`, `Exists`, `Does Not Exist`, `Is True`, `Is False`, `InLast`, `OverDays`, `InNext`, `Before`, `After`, `IsToday`, `DayInNext`, `DayInMonth`, `Is In Segment`, `Is Not In Segment`, `Has Filled a Form`. For recurring day-of-year fields (`data_type: Day`, e.g. Birthday) use the `DayInNext`/`DayInNextXY`/`DayInMonth` family — not the absolute-date `InNext`/`=` — so \"birthday in the next N days\" recurs every year (see `describeSegmentSchema`).\n\n`Exists`/`Does Not Exist` vs `Is Not Empty`/`Is Empty`: both check for a populated value and are usually close in practice, but `Exists` is what the dashboard UI itself uses when a user says a field \"exists\" - prefer `Exists`/`Does Not Exist` for that phrasing, especially inside `with_or_segment_users`, to match what the UI would produce for the same request.\n"},"value":{"type":["string","number","boolean","array","null"],"description":"The operand. Which type applies depends on the operator: a scalar for `=` and `Contains`, an array (or comma-separated string) for `Is One Of`, a number for count comparisons, and omitted entirely for `Exists` / `Is Empty`.\n"},"value2":{"type":["string","number","null"],"description":"Secondary operand for two-parameter conditions (currently `External Events` count comparison and `SalesAttributes` pipeline-stage filter)."},"operator2":{"type":"string","description":"Secondary operator for two-parameter conditions.","nullable":true},"value2_id":{"type":"array","items":{"type":"string"},"nullable":true,"description":"Object-ID list for stage-title disambiguation on `SalesAttributes`."},"data_type":{"type":"string","enum":["String","Numeric","Date","List"],"nullable":true,"description":"Optional hint for the engine's disambiguation logic."},"dataAlias":{"type":"string","nullable":true,"description":"Human-readable alias shown in the UI. Not evaluated."}}},"Timestamp":{"type":"string","format":"date-time","description":"RFC 3339 timestamp, always UTC, millisecond precision."},"SegmentFolderId":{"type":"string","pattern":"^sfd_[0-9a-fA-F]{24}$","description":"Segment folder ID."},"Metadata":{"type":"object","description":"Free-form key/value pairs the caller stores on the resource. Not evaluated by Gleantap.\nUse for opaque identifiers, integration state, or notes you need to survive round-trips.\n","additionalProperties":true},"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":{"/segments/{id}/convert_to_static":{"post":{"tags":["Segments"],"operationId":"convertSegmentToStatic","summary":"Freeze a dynamic segment's current membership as static.","description":"Evaluates the segment's criteria NOW, then flips `type` to `static` and stamps `last_evaluated_at`. The evaluation is the same one `refreshSegment` and the preview run (OR groups, excludes, external events, account timezone), so the frozen list is the segment's membership at the moment of the call — not whatever the last cron pass happened to leave behind. Idempotent guard: 409 `already_static` if the segment is already static.\n\nIf the evaluation fails, **nothing is converted** — the response is 500 `snapshot_evaluation_failed`, the segment stays dynamic, and the detail names the failure. A static segment frozen from an unevaluated membership list would be wrong permanently, since nothing recomputes a static segment afterwards.\n\n**Irreversible.** Converting to static freezes membership: the segment stops tracking its criteria and cannot be converted back.\n","parameters":[{"$ref":"#/components/parameters/VersionHeader"},{"$ref":"#/components/parameters/AccountHeader"},{"$ref":"#/components/parameters/WorkroomHeader"},{"$ref":"#/components/parameters/WorkroomQuery"}],"responses":{"200":{"description":"Converted segment (now static), with the membership frozen from a fresh evaluation.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Segment"}}}},"404":{"$ref":"#/components/responses/NotFound"},"409":{"description":"Segment is already static (`already_static`)."},"500":{"description":"`snapshot_evaluation_failed` — membership could not be evaluated; the segment is unchanged and still dynamic."}}}}}}
```
