# =============================================================================
# AiEngage CRM - Modules Public API (OpenAPI 3.1)
#
# SCOPE: the public Modules API - the 16 endpoints under
# /api/public/v1/objects and /api/public/v1/properties that were implemented
# by Atul (git: routes/api/public-v1.php, created in df739f9e3, associations
# added in 77fdc4215; every route verified with `git blame -w -M -C`) - PLUS
# the three email endpoints (two under /email, one under /campaign) and the
# four /api/public/v1/whatsapp ones, which are documented here rather than in
# documents of their own: they
# share this API's token, scope model, error envelope and rate-limit
# machinery, and separate pages would hide that.
#
# Deliberately NOT in scope, and documented elsewhere:
#   - GET /objects                       (module catalogue - Prayas Jain)
#   - GET /objects/{module}/{id}/timeline (Prayas Jain)
#   - every non-module public surface: reports, analytics, dashboards,
#     campaigns, support, whatsapp, OAuth, forms, booking, documents,
#     portfolio, widget.
#
# STRUCTURE follows Zoho CRM's v8 API reference (Purpose / Endpoint / Scope /
# Header / Parameters / Sample Request / Sample Response / Possible Errors)
# and Shopify's Admin API resource pages (typed property blocks with
# read-only and required flags, a full example object per resource).
#
# DOCUMENTATION ONLY. No route, controller, middleware, service or database
# behaviour was changed to produce this file. Nothing is invented: where a
# value could not be established from source it is marked x-unverified.
# =============================================================================
openapi: 3.1.0

info:
  title: AiEngage CRM Public API
  version: v1
  summary: >-
    Create, read, update, archive, search, batch-process and link CRM records
    through one module-agnostic API, plus the field metadata that tells you
    what each module contains.
  description: |
    > ### Start here: paste your token
    >
    > **Step 1** below has a **Paste your key here** box. Put your
    > `cak_live_…` key into it **once**. From that moment:
    >
    > - every **code sample** on this page — curl, Python, Node, PHP — is
    >   written with your token in it, ready to copy and run;
    > - the **Send** button on each endpoint makes the real call and shows you
    >   the real response beside it;
    > - your browser remembers it, so you only do this once.
    >
    > Your token stays in this browser and is sent only to your own CRM.
    >
    > No token yet? **Step 1** below shows you where to get one.

    ## What this API is

    One API for **every** CRM module - Contacts, Deals, Companies, Products,
    and any custom module your organization creates. You name the module in
    the URL:

    ```
    GET /api/public/v1/objects/contacts
    GET /api/public/v1/objects/deals
    GET /api/public/v1/objects/your_custom_module
    ```

    There is no separate "Contacts API" and "Deals API" to learn. The request
    is the same shape every time - only the module name and the field names
    change.

    ## How to use it

    1. **Get an API token** - in the CRM, Settings → API Keys → Create.
    2. **Pick your module** - the slug that goes in the URL, like `contacts`.
    3. **Check its fields** - `GET /properties/{module}` lists them.
    4. **Enter your data** - edit the body in the panel beside any endpoint.
    5. **Copy the cURL, or press Send** - and read the response.

    Each of those is one step below.

    ---

    # Quick Start

    Five minutes, start to finish.

    ## Step 1 - Get an API token

    In the CRM: **Settings → API Keys → Create**. Tick the scopes you need -
    for this guide, `crm.contacts.read`, `crm.contacts.write` and
    `crm.schema.read`.

    **One key is enough for everything.** Scopes mix freely, so the same key
    can read records, send email and send WhatsApp. To use every endpoint
    here, also tick `email.from_addresses.read`, `email.messages.send`,
    `email.transactional.send`, `whatsapp.templates.read` and
    `whatsapp.templates.send`.

    You get a token like `cak_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6`.
    **Copy it now** - it is shown only once.

    > The token acts as **the user who created it**, and sees only the records
    > that person can see. Two keys from one organization can legitimately
    > return different results.

    ## Step 2 - Send it on every request

    One header, on every call:

    ```
    Authorization: Bearer cak_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6
    ```

    You do not have to type it here. Paste your key into the **Paste your key
    here** box in Step 1, and every sample on this page - curl, Python, Node, PHP -
    is rewritten with it, the **Send** buttons start making real calls, and
    your browser remembers it.

    Paste the key on its own. If you copy it out of Postman it may arrive as
    `Bearer cak_live_...`; the box strips that, so the header is never written
    twice.

    Your key is stored in this browser only. Send calls your CRM directly -
    nothing is relayed through the documentation host.

    To run something this page does not list, open the **Console** in the
    header, paste any curl, and press Send.

    > If Send says the request never left the browser, that host has not
    > allowed this page's origin. The sample is still correct - press **Copy**
    > and run it in a terminal.

    ## Step 3 - Find out which modules exist

    ```bash
    curl "https://app.aiengagecrm.com/cback/api/public/v1/objects" \
      -H "Authorization: Bearer YOUR_API_TOKEN"
    ```

    This returns the modules your key can address, each with the `slug` you
    put in the URL.

    > **Note:** `GET /objects` is outside this document's scope - it is part
    > of the wider Public API rather than the Modules API documented here, and
    > it was implemented separately. It is shown because it is genuinely the
    > easiest way to discover module names. If you would rather not use it,
    > the **Supported modules** table further down lists the standard slugs.

    ## Step 4 - Find out what a module contains

    This is the call that matters most, and the one most people skip:

    ```bash
    curl "https://app.aiengagecrm.com/cback/api/public/v1/properties/contacts" \
      -H "Authorization: Bearer YOUR_API_TOKEN"
    ```

    ```json
    {
      "results": [
        {
          "name": "email",
          "label": "Email",
          "type": "email",
          "required_on_create": false,
          "unique": true,
          "options": null
        },
        {
          "name": "first_name",
          "label": "First Name",
          "type": "single_line",
          "required_on_create": true,
          "unique": false,
          "options": null
        }
      ]
    }
    ```

    Read it like this:

    | Key | Why you care |
    |---|---|
    | `name` | The exact key to put inside `properties`. Not the label. |
    | `required_on_create` | Leave it out of a create and the call fails. |
    | `unique` | Safe to use as `id_property` or `matching_property`. |
    | `options` | For a picklist, the only values that will be accepted. |

    **Field names differ per organization.** An admin can rename, add or hide
    fields. Never hardcode a field list - read it from here.

    ## Step 5 - Create your first record

    ```bash
    curl "https://app.aiengagecrm.com/cback/api/public/v1/objects/contacts" \
      -X POST \
      -H "Authorization: Bearer YOUR_API_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"properties":{"first_name":"Ada","last_name":"Lovelace","email":"ada@example.com"}}'
    ```

    ```json
    {
      "id": "6650f1a2b3c4d5e6f7a8b9c0",
      "properties": { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com" },
      "created_at": "2026-11-10T09:30:00.000Z",
      "updated_at": "2026-11-10T09:30:00.000Z",
      "created_by": "6640a1b2c3d4e5f6a7b8c9d0",
      "updated_by": "6640a1b2c3d4e5f6a7b8c9d0",
      "archived": false
    }
    ```

    That is the whole loop: **authenticate → discover the module → read its
    fields → write a record.**

    ---

    # Every request in Postman

    One import, and all 24 endpoints arrive ready to run.

    1. Postman -> **Import** -> **Link**
    2. Paste this URL:

    ```
    https://developer.aiengagecrm.com/module-public-api.yaml
    ```

    3. Add your token as collection-level **Bearer Token** auth - every
       request inherits it.

    That URL belongs in **Import**, not in the address bar of a new
    request. A request *to* the document downloads it: you get 200 and a
    screenful of YAML in the response pane, and nothing in your sidebar.
    Import is what turns one file into 23 requests.

    The collection arrives pointing at the live API already - the
    document names it as the first server, and Postman takes the base URL
    from there. Change it only to call a different instance.

    You get one request per endpoint, grouped by tag, each carrying real
    request and response examples - so they run rather than arriving as
    empty shells.

    Prefer a file? **Download YAML** at the top of this page is the same
    document, for **Import -> File**.

    The same file imports into Insomnia, Hoppscotch, Stoplight, Redocly and
    anything else that reads OpenAPI 3.1. `openapi-generator` will produce a
    typed client from it directly.

    ---

    # The endpoints

    These say "contact" because that is the one everybody starts with, and
    because a sentence about a *record* is a sentence about nothing in
    particular. Swap the word for whatever you are addressing: `{module}` is
    `contacts` here, and `deals`, `companies`, `tickets` or any other module
    you can reach works the same way, with the same 24 calls.

    | # | Method | Endpoint | What it does |
    |---|---|---|---|
    | 1 | GET | `/objects/{module}` | Get a list back - every contact, a page at a time |
    | 2 | POST | `/objects/{module}` | Create one new contact |
    | 3 | PUT | `/objects/{module}` | Update it if it already exists, create it if it does not |
    | 4 | GET | `/objects/{module}/{id}` | Get one contact back, by its id |
    | 5 | PATCH | `/objects/{module}/{id}` | Change a few fields on one contact, leave the rest alone |
    | 6 | DELETE | `/objects/{module}/{id}` | Hide one contact from lists and searches - it is not destroyed |
    | 7 | POST | `/objects/{module}/search` | Find the contacts that match what you ask for |
    | 8 | POST | `/objects/{module}/batch/create` | Create up to 100 at once |
    | 9 | POST | `/objects/{module}/batch/read` | Get up to 100 back at once, by id |
    | 10 | POST | `/objects/{module}/batch/update` | Change up to 100 at once |
    | 11 | POST | `/objects/{module}/batch/archive` | Hide up to 100 at once |
    | 12 | PUT | `/objects/{module}/{id}/associations/{toModule}/{toId}` | Join two records - a contact to a deal, say |
    | 13 | GET | `/objects/{module}/{id}/associations/{toModule}` | See what a contact is joined to |
    | 14 | DELETE | `/objects/{module}/{id}/associations/{toModule}/{toId}` | Undo that join |
    | 15 | GET | `/properties/{module}` | See which fields a module has, and what each one accepts |
    | 16 | GET | `/properties/{module}/{property}` | See one field in detail |
    | 17 | GET | `/email/from-addresses` | See which addresses you are allowed to send from |
    | 18 | POST | `/campaign/send` | Send one email to any address |
    | 19 | POST | `/email/send` | Send one email to a contact, and log it on their timeline |
    | 20 | POST | `/contact/email/send` | Send one plain-text email from your own address, with cc and bcc, writing nothing to the CRM |
    | 21 | GET | `/whatsapp/templates` | See the approved templates you may send |
    | 22 | GET | `/whatsapp/templates/{id}` | See one template - its words, and the blanks it expects |
    | 23 | POST | `/whatsapp/templates/{id}/send` | Send a template to a phone number |
    | 24 | POST | `/whatsapp/send` | Send a template to a contact, creating the contact if it is new |

    ---

    # The CRM inside an AI assistant

    The Modules API is one way in: you write the client. MCP is the other. You
    connect Claude - or any MCP client - to the CRM once, and then ask in plain
    English. Same data, same permissions, the same scopes the Modules API uses.
    No code at all.

    One address, identical for every customer, with nothing to add to the end:

    ```
    https://mcp-api.aiengagecrm.com/mcp
    ```

    It is **read-only by design**. The connector can look things up. It can never
    create, update, delete or send anything - not because it politely declines,
    but because no write tool exists to call.

    ## What it is, in four lines

    | Guarantee | What it means |
    |---|---|
    | **Reads as you** | Sharing rules, role hierarchy, profile and field permissions all apply. Two people connecting the same CRM legitimately see different answers. |
    | **Per person** | Each person connects their own assistant with their own CRM login. There is no org-wide connection and no API key to hand round. |
    | **Read-only** | Blocked at the connection, not just hidden in the menu. |
    | **Revocable** | Settings → Developer Hub → API Keys → **Connections**. **Disconnect** takes effect immediately; **Change access** narrows a live connection on its very next request. |

    Your plan needs **API access** (Business Pro). Without it the connection still
    authorises, and then every question comes back refused - which looks like a
    broken connector and is not one.

    ## Connect your client

    **Claude on the web, mobile or desktop.** In the CRM: Settings → Developer Hub
    → **MCP** → **Copy address**. In Claude: **Customize → Connectors → + Add →
    Add custom connector**, paste the address, name it, and leave the OAuth client
    id and secret empty - this server does not need them. Claude opens a CRM
    sign-in, then an **Authorize access to your CRM** screen where you tick what it
    may read. Press **Allow access** and you are done.

    The click-by-click version, with screenshots, is in the help centre:
    [Connect Claude to AiEngage CRM](https://help.aiengagecrm.com/article/connect-claude-to-aiengage-crm-mcp).

    On Claude Team or Enterprise only an Owner can add the connector; everybody
    else then presses **Connect** on it and authorises for themselves.

    For a terminal or an editor, it is one line:

    ```bash
    # tab: Claude Code
    claude mcp add --transport http aiengage https://mcp-api.aiengagecrm.com/mcp
    # then run /mcp inside Claude Code and pick "aiengage" to authorize
    ```

    ```json
    # tab: Cursor, VS Code, others
    {
      "mcpServers": {
        "aiengage": {
          "type": "http",
          "url": "https://mcp-api.aiengagecrm.com/mcp"
        }
      }
    }
    ```

    There is no API key in either of those. The first tool call opens a browser,
    you sign in, you press **Allow access**, and the client holds the token from
    then on.

    > Were you given a `cak_live_…` key for MCP before this existed? It still
    > works, as an `Authorization: Bearer` header against the same address. New
    > ones are no longer issued - connect through the flow above and delete the
    > old entry.

    ## What the connector can read

    The connector exposes **48 tools** in **16 groups**. Every one of
    them reads; none of them writes.

    The checkbox list on the authorization screen is this same catalogue. Whatever
    you leave unticked, the connection never holds - the selection IS the scope
    grant, not a display filter.

    ### Schema discovery · 3 tools

    Scope granted: `crm.schema.read`.

    | Tool | What it does |
    |---|---|
    | `objects_list_types` | **List object types.** List every CRM object type (module) available here, including the custom modules this org built — each entry has `slug` (the value every other tool's… |
    | `properties_list` | **List fields of a module.** List the field (property) definitions for a CRM module — each field's key/slug, label, and type. |
    | `search_everything` | **Search everything.** Search across EVERY module and entity at once. |

    ### Records · 4 tools

    Scope granted: `crm.{module}.read` — one per module you tick.

    | Tool | What it does |
    |---|---|
    | `objects_list` | **List records.** List records of a CRM object type, newest first, with cursor pagination. |
    | `objects_get` | **Get one record.** Fetch a single CRM record by its id, with all of its properties. |
    | `objects_search` | **Search / filter records.** Search / filter records of a CRM object type. |
    | `records_timeline` | **Record history.** The HISTORY of one record — what changed, when, and who did it. |

    ### My agenda · 1 tool

    Scope granted: `crm.agenda.read`.

    | Tool | What it does |
    |---|---|
    | `my_agenda` | **My overdue & due-today items.** The signed-in person's OWN plate: what is OVERDUE and what is DUE TODAY, across EVERY module at once (tasks, meetings, calls, deals… |

    ### Reports · 4 tools

    Scope granted: `crm.reports.read`.

    | Tool | What it does |
    |---|---|
    | `reports_overview` | **Reports overview.** High-level sales/CRM overview KPIs for a date range (new contacts, connected, calls, meetings, emails, WhatsApp, lead-status distribution… |
    | `reports_pipeline` | **Pipeline report.** Sales pipeline breakdown — deal counts/amounts by stage, and deals by user — for a date range. |
    | `reports_activities` | **Activities report.** Activity-type breakdown (calls, meetings, notes, emails, WhatsApp) for a date range, plus meetings-by-user. |
    | `reports_users` | **Per-user activity report.** Per-user activity table for a date range — contacts, deals, calls and meetings per person. |

    ### Analytics · 6 tools

    Scope granted: `crm.analytics.read`.

    | Tool | What it does |
    |---|---|
    | `analytics_metrics` | **List analytics metrics.** The catalog of shortcut analytics metrics, PLUS the list of modules you can aggregate directly. |
    | `analytics_fields` | **Groupable fields of a module.** Which fields of ONE module can be grouped by, filtered on, bucketed over time, and summed. |
    | `analytics_group_by` | **Break down by a field.** Break a module's records down BY a field and aggregate them — the tool for every 'X by Y' question: 'calls by user', 'deals by stage'… |
    | `analytics_run` | **Run an analytics query.** Run a full report-builder config — the ESCAPE HATCH for shapes analytics_group_by cannot express: pivots (row x column cross-tabs), funnels… |
    | `saved_reports_list` | **List saved reports.** The reports this organization has already built and named. |
    | `saved_reports_run` | **Run a saved report.** Run a saved report by id and return its numbers. |

    ### Dashboards · 6 tools

    Scope granted: `crm.dashboards.read`.

    | Tool | What it does |
    |---|---|
    | `dashboards_productivity` | **Productivity dashboard.** The current user's productivity summary — open tasks, tasks due today, today's meetings, and pinned notes. |
    | `dashboards_list` | **List dashboards.** The organization's saved dashboards. |
    | `dashboards_get` | **Get one dashboard.** One dashboard and its tiles. |
    | `dashboards_widget` | **Productivity widget.** One productivity widget for the person asking: my_tasks, tasks_due_today, events_today, calendar, kanban or sticky_notes. |
    | `dashboards_meetings` | **My meetings.** The asking person's meetings for a date (defaults to today). |
    | `notifications_list` | **My notifications.** The asking person's in-app notifications and unread count. |

    ### Advertising · 3 tools

    Scope granted: `crm.ads.read`.

    | Tool | What it does |
    |---|---|
    | `ads_report` | **Advertising report.** Paid advertising performance combined across every connected platform (Meta, Google Ads, Custom Advertising): total spend, impressions, clicks… |
    | `ads_grid` | **Advertising grid.** The same advertising metrics as ads_report but as ranked, paginated rows grouped by one dimension. |
    | `ads_filter_options` | **Advertising filter options.** The valid filter values for the advertising tools — platforms, businesses, ad accounts, campaigns, ad sets and ads. |

    ### Campaigns · 3 tools

    Scope granted: `crm.campaigns.read`.

    | Tool | What it does |
    |---|---|
    | `campaigns_list` | **List campaigns.** List marketing campaigns (newest first, paginated). |
    | `campaigns_get` | **Get one campaign.** Fetch a single campaign by id, with its details. |
    | `campaigns_analytics` | **Campaign analytics.** Performance analytics for one campaign (sends, delivered, opens, clicks, conversions, rates). |

    ### Segments · 3 tools

    Scope granted: `crm.segments.read`.

    | Tool | What it does |
    |---|---|
    | `segments_list` | **List segments.** List audience segments (paginated). |
    | `segments_get` | **Get one segment.** Fetch a single segment by id, with its definition. |
    | `segments_kpis` | **Segment KPIs.** KPI counters for one segment (total members, added/removed today, last processed). |

    ### Contact lists · 2 tools

    Scope granted: `crm.lists.read`.

    | Tool | What it does |
    |---|---|
    | `lists_list` | **List contact lists.** List static contact lists (paginated). |
    | `lists_get` | **Get one contact list.** Fetch a single contact list by id. |

    ### Workflows · 3 tools

    Scope granted: `crm.workflows.read`.

    | Tool | What it does |
    |---|---|
    | `workflows_list` | **List workflows.** List automation workflows (paginated). |
    | `workflows_get` | **Get one workflow.** Fetch a single workflow by id, with its definition. |
    | `workflows_report` | **Workflow report.** Execution report / stats for one workflow (sent, delivered, read, clicked, failed, rates). |

    ### People · 2 tools

    Scope granted: `crm.users.read`.

    | Tool | What it does |
    |---|---|
    | `users_list` | **List people.** List the people in this CRM — names, ids, active state, team membership. |
    | `users_get` | **Get one person.** Fetch one person by their user id. |

    ### Teams · 2 tools

    Scope granted: `crm.teams.read`.

    | Tool | What it does |
    |---|---|
    | `teams_list` | **List teams.** List teams with their leads and member counts. |
    | `teams_get` | **Get one team.** Fetch one team by id, with its members expanded to names. |

    ### Web forms · 3 tools

    Scope granted: `crm.webforms.read`.

    | Tool | What it does |
    |---|---|
    | `webforms_list` | **List web forms.** The organization's web forms. |
    | `webforms_stats` | **Web form stats.** Submission counts and conversion for one form. |
    | `webforms_submissions` | **Web form submissions.** The submissions to one form, newest first, with their status (pending / approved / rejected) and captured data. |

    ### Telephony · 2 tools

    Scope granted: `crm.voice.read`.

    | Tool | What it does |
    |---|---|
    | `voice_quota` | **Call allowance.** Telephony allowance: calls made this month, the cap, and the phone number limit. |
    | `voice_routing` | **Call routing.** Which phone number rings which agent, inbound and outbound. |

    ### Plan and usage · 1 tool

    Scope granted: `crm.billing.read`.

    | Tool | What it does |
    |---|---|
    | `plan_usage` | **Plan limits and usage.** The plan's limits and how much of each is consumed — contacts, seats, storage, emails, API calls. |

    ## How this lines up with the Modules API

    This is the part worth understanding, because the two halves are not separate
    systems wearing different clothes.

    **The checkboxes on the authorization screen are scope grants.** Ticking the
    Records tools is what gives the connection `crm.{module}.read` - the very
    scope documented under *Scopes* above. Untick them and the connection stops
    holding the scope, so it is not that the tool is hidden: the data is gone.

    **The same middleware answers both.** An MCP connection carries a
    `cak_oauth_…` access token where an integration carries `cak_live_…`. Both
    arrive at the same authentication path, both resolve to one organization and
    one acting user, and both get the identical `403 MISSING_SCOPE` when the scope
    is absent. Nothing about MCP is a side door.

    **Publication is shared too.** A module an admin has not published to the
    public API is equally invisible to the assistant. If the authorization screen
    says there is nothing to read, that is the cause - not a broken connector.

    **Visibility is shared too.** Every read is scoped to the person who
    authorised the connection, exactly as a personal access token is scoped to the
    person who created it. "Claude can see the module but says the record does not
    exist" means that record is not theirs to see.

    So the mental model is one API with two front doors:

    | | REST API | MCP |
    |---|---|---|
    | You write | the client | nothing |
    | Address | `/api/public/v1/…` on your CRM host | `https://mcp-api.aiengagecrm.com/mcp` |
    | Credential | `cak_live_…` personal access token | `cak_oauth_…`, minted by the browser flow |
    | Scopes | chosen when you create the key | chosen on the authorization screen |
    | Writes | yes - POST, PATCH, PUT, DELETE | never |

    ## Build your own MCP client

    Only needed if you are writing an MCP client yourself. If you are using Claude,
    Cursor or VS Code, the flow above already did all of this for you.

    Authorization is OAuth 2.1. Start from the discovery document and take every
    URL from it rather than hardcoding one:

    ```
    GET https://mcp-api.aiengagecrm.com/.well-known/oauth-authorization-server
    ```

    The same document is served at `/.well-known/oauth-authorization-server/mcp`
    and at `/.well-known/openid-configuration`, because clients differ on which
    they probe first.

    | Endpoint | Method | What it is for |
    |---|---|---|
    | `/oauth/authorize` | GET, browser | Starts the flow. Parks a consent ticket and sends the person to the CRM to sign in and choose tools. |
    | `/oauth/token` | POST, form-encoded | `authorization_code` and `refresh_token` grants. |
    | `/oauth/register` | POST, JSON | Dynamic client registration, if you are not using a client-id metadata document. |
    | `/oauth/revoke` | POST, form-encoded | Hand a token back. |
    | `/oauth/introspect` | POST | Used by the resource server with its own credentials, not by you. |

    What the server will and will not accept:

    - **PKCE is required, and `S256` only.** OAuth 2.1 removed `plain`, which
      protects nobody who can see the authorization request.
    - **Grants:** `authorization_code` and `refresh_token`. Nothing else.
    - **Ask for `offline_access`** alongside `crm:read` or your connection dies
      with the first access token and the person has to authorise again.
    - **Identify your client** either with a client-id metadata document (the
      server advertises `client_id_metadata_document_supported`) or by registering
      at `/oauth/register`. Registration is rate limited per IP.
    - **The audience is the MCP server**, `https://mcp-api.aiengagecrm.com/mcp`.
      A token minted for anything else is refused.
    - The issuer is returned on the authorization response and must byte-match
      `https://mcp-api.aiengagecrm.com`.

    ## How long a connection lasts

    | Limit | How long |
    |---|---|
    | Access token | 1 hour |
    | Authorization code | 60 seconds |
    | Time to finish the consent screen | 10 minutes |
    | Idle before the connection dies | 60 days |
    | Maximum life, however active | 365 days |

    When a connection expires the client asks the person to authorise again. There
    is nothing to renew in the CRM and no key to rotate.

    MCP calls draw on the organization's ordinary API allowance - the same monthly
    and daily quota the REST API uses, visible under Settings → API Keys →
    **Usage**. A connector that suddenly answers "refused" when it worked an hour
    ago has usually run the org out of calls, not broken.

    # Reference

    ## Authentication

    Four token kinds are accepted, and **every** authentication failure in
    **every** mode returns an identical `401 UNAUTHORIZED` body, so a caller
    cannot probe which one it nearly matched.

    | Mode | Token | Who uses it |
    |---|---|---|
    | 1 | `cak_live_<32 chars>` | External integrations. Settings → API Keys. |
    | 2 | Purpose-scoped user JWT | The in-app CRM agent. |
    | 3 | Dashboard login JWT | A signed-in person using their own session. |
    | 4 | `cak_oauth_<...>` | A remote MCP client that completed the OAuth flow. |

    If the user who created a token is deleted, the token stops working and
    returns `500 INTERNAL_ERROR` telling you to revoke and re-issue.
    `cak_test_` is reserved and is rejected.

    ## Scopes

    **A key carries a list of scopes, and they mix freely.** One key can read
    records, send email and send WhatsApp; there is no per-channel key. There
    are three families:

    | Family | Covers |
    |---|---|
    | `crm.<module>.<action>` | records, schema, campaigns, reports |
    | `email.<area>.<action>` | from addresses, sending |
    | `whatsapp.<area>.<action>` | templates, sending |

    The `crm.*` family is substituted per request - calling
    `/objects/contacts` checks `crm.contacts.read`, not a literal
    `crm.{module}.read`.

    | Scope | Granted when the token's user has |
    |---|---|
    | `crm.{module}.read` | **view** permission on that module |
    | `crm.{module}.write` | **create** AND **edit** permission |
    | `crm.{module}.delete` | **delete** permission |
    | `crm.schema.read` | the `manage_organization` feature permission |

    Note that `write` needs **both** create and edit - a user who can create
    but not edit cannot be granted it.

    ## Which modules you can reach

    `Module.public_api_enabled` decides whether third parties may address a
    module. It is **default-ON**: a module is reachable unless an admin
    explicitly turned it off.

    A module turned off that way returns `404 MODULE_NOT_AVAILABLE` **even
    when your token holds a scope for it** - the scope grant does not override
    publication. A de-activated module is unavailable to everyone.

    This publication gate applies to `cak_live_*` keys only. The other three
    token modes are not third parties, so it is relaxed for them.

    ## The record envelope

    Every record read or written uses the same envelope. Metadata at the top
    level, everything the module defines under `properties`.

    ```json
    {
      "id": "6650f1a2b3c4d5e6f7a8b9c0",
      "properties": { "first_name": "Ada", "email": "ada@example.com" },
      "created_at": "2026-11-10T09:30:00.000Z",
      "updated_at": "2026-11-10T09:30:00.000Z",
      "created_by": "6640a1b2c3d4e5f6a7b8c9d0",
      "updated_by": "6640a1b2c3d4e5f6a7b8c9d0",
      "archived": false
    }
    ```

    `properties` is always an object - `{}` when empty, never `[]`.
    Timestamps are UTC, `YYYY-MM-DDTHH:MM:SS.sssZ`.

    ## Errors

    Every error shares one envelope:

    ```json
    {
      "status": "error",
      "message": "Token is missing the required scope: crm.deals.read.",
      "category": "MISSING_SCOPE",
      "correlationId": "01J8ZQ9K3M4N5P6Q7R8S9T0V",
      "errors": [],
      "documentation_url": "https://developer.aiengagecrm.com/#g-errors"
    }
    ```

    **Branch on `category`, never on `message`.** The wording can change; the
    category will not. Log `correlationId` - it is the one thing that lets
    anyone trace your exact request in the backend.

    > `documentation_url` points at **aitrillion.com**, not aiengagecrm.com.
    > That is not a typo here: the backend emits that host on every error, so
    > this document reproduces what you will actually receive.

    | Category | HTTP | Description | Resolution |
    |---|---|---|---|
    | `UNAUTHORIZED` | 401 | Token missing, malformed, unknown, revoked or expired. | Check the `Authorization: Bearer` header. |
    | `MISSING_SCOPE` | 403 | Authenticated, but the token lacks this route's scope. | The message names the scope. Re-issue the key with it. |
    | `FORBIDDEN` | 403 | Scoped, but the acting user may not do this - an owner change without Change Owner, or a mass update with that tool off. | A permissions change, not a token change. |
    | `VALIDATION_ERROR` | 400 | Body or query parameter failed validation. | `errors[]` names the property. Also returned for a batch over 100 items, and for upsert without `matching_property`. Nothing was written. |
    | `INVALID_PROPERTY` | 400 | A property name does not exist on this module, or more than 5 `include` values. | Call `GET /properties/{module}` for the real names. |
    | `INVALID_FILTER` | 400 | Unknown operator, more than 5 filter groups, or more than 6 filters in a group. | Check the operator table in the search guide. |
    | `INVALID_CURSOR` | 400 | The `after` cursor is malformed. | Pass `paging.next.after` back verbatim. |
    | `OBJECT_NOT_FOUND` | 404 | No such record, **or** it is outside the acting user's visibility. | The two are deliberately indistinguishable so existence never leaks. |
    | `MODULE_NOT_AVAILABLE` | 404 | No module matches that name, it is de-activated, or unpublished. | Holding the scope does not override publication. |
    | `ENDPOINT_NOT_FOUND` | 404 | The version is valid, but nothing serves that method and path. | Check the path against this document. A route that works on one host and 404s on another is not deployed there yet. |
    | `VERSION_NOT_AVAILABLE` | 404 | The first path segment is not a version this host serves. | `available_versions` in the body lists the ones it does. |
    | `CONFLICT` | 409 | An `id_property` or `matching_property` on a non-unique field matched more than one record. | Use a field marked `unique`. |
    | `IDEMPOTENCY_KEY_CONFLICT` | 409 | The same key was reused with a different body. | Use a fresh key per operation. |
    | `RATE_LIMITED` | 429 | Per-window limit hit. | Wait `Retry-After` seconds. |
    | `RATE_LIMITED_DAILY` | 429 | Daily quota spent. | `Retry-After` counts to end of day. |
    | `RATE_LIMITED_MONTHLY` | 429 | Monthly quota spent. | `Retry-After` counts to end of month. |
    | `INTERNAL_ERROR` | 500 | Unexpected failure, or the token's creating user was deleted. | Revoke and re-issue. Quote `correlationId`. |

    ## Rate limits

    Every **authenticated** response carries `RateLimit-Limit`,
    `RateLimit-Remaining` and `RateLimit-Reset`.

    A **401 does not.** Authentication runs before the rate limiter, so a
    rejected key never reaches it — do not write a client that expects those
    headers on every response, because the one response you are most likely
    to hit first has none of them.

    Browsers see none of these headers at all unless the server sends
    `Access-Control-Expose-Headers`. From your own code (curl, Python, PHP)
    they are all there.

    | Bucket | Rate | Daily cap | Applies to |
    |---|---|---|---|
    | `general` | 100 per 10s | 250,000 | 19 of the 24 endpoints |
    | `search` | **5 per 1s** | 50,000 | `/objects/{module}/search` and `/objects/{module}/batch/read` |
    | `email_send` | **5 per 60s** | 500 | `POST /campaign/send` and `POST /email/send` |
    | `contact_email_send` | **15 per 1h** | 360 | `POST /contact/email/send` |

    Tokens on the `elevated` tier get 5x both.

    ## Idempotency

    Send `Idempotency-Key` on any mutating call to make a retry safe.

    - Same key, same body - the cached response is replayed with
      `Idempotency-Replayed: true`.
    - Same key, **different** body - `409 IDEMPOTENCY_KEY_CONFLICT`.

    Cached 24 hours, keyed by organization + route + key so it cannot collide
    across tenants. For a batch call, one key covers the whole batch.

    ## Supported modules

    Use any of these as `{module}` in the URL:

    `contacts` · `deals` · `companies` · `products` · `quotes` · `invoices` ·
    `payments` · `leads` · `tasks` · `tickets` · `meetings` · `calls` ·
    `notes` — plus any custom module your organization has created.

    **Field lists are not printed here, on purpose.** Fields are defined per
    organization: an admin adds, renames and removes them, so any list written
    into this document would be a snapshot that goes stale and quietly starts
    lying.

    Call `GET /properties/{module}` instead. It returns exactly what your
    organization has, right now — names, types, which are required, which are
    unique, and a picklist's accepted values.

    Module resolution is forgiving: the exact slug is tried first, then a
    case-insensitive slug match, then the module's display, singular or plural
    name. Prefer the slug.

    ## Scope of this document

    The endpoint reference covers the public **Modules** API - the 16
    endpoints under `/objects` and `/properties` - plus the three `/email`
    endpoints, `/campaign/send`, and the four `/whatsapp` ones. Two endpoints
    in the same route file are **not** included:
    `GET /objects` (the module catalogue) and
    `GET /objects/{module}/{id}/timeline`, both implemented separately and
    documented elsewhere. Everything else - reports, analytics, dashboards,
    campaigns, support, forms, booking, documents, portfolio and the widget
    - has no endpoint documented here.

    Email and WhatsApp are here rather than on pages of their own because
    they are the same API wearing the same clothes: one `cak_live_` token,
    the same three-part scopes, the same error envelope, the same
    rate-limit headers. Splitting them out would duplicate all of that and
    let the copies drift.

    The **MCP** chapter is the one deliberate exception, and it is not an
    endpoint reference. MCP reaches far more of the CRM than Modules does -
    reports, analytics, dashboards and the rest - but it reaches them as an
    assistant's tools rather than as routes you call, and it grants its access
    with the same scopes documented here. It is covered because the two share
    one authentication path and one scope model, and splitting them across two
    documents would hide that.

    The OpenAPI file itself carries the 16 Modules operations, the two Email
    ones and the three WhatsApp ones, and nothing else: the MCP chapter adds
    no paths, no servers and no tags, so anything generated from the spec -
    a Postman collection, a client library - covers exactly those 24 calls.
  contact:
    name: AiEngage API Support
    url: https://developer.aiengagecrm.com/
  license:
    name: Proprietary

servers:
  # PRODUCTION, and FIRST on purpose.
  #
  # servers[0] is the document default: every curl sample on this page is
  # written against it, and it is the host Send calls until a reader picks
  # another. It was dev1 for this document's whole life, so a reader who
  # copied a sample ran it against a staging box they have no account on -
  # next to a cak_live_ key, which made the mismatch invisible.
  #
  # Measured 2026-11-16 with no Authorization header, where 401 means the
  # route exists and wants a token and 404 means it is not deployed:
  # GET /objects -> 401, GET /properties/contacts -> 401.
  - url: https://app.aiengagecrm.com/cback/api/public/v1
    description: Production - the live AiEngage CRM API
  # dev1, the staging instance. Still a choice, no longer the default.
  #
  # Send against ANY host depends on that host allowing this page's origin,
  # because these docs are served from their own domain - which is true of
  # production above too. Either way the token goes only to your own CRM;
  # it is never relayed through the documentation host.
  - url: https://crm-dev1.aiengagecrm.com/cback/api/public/v1
    description: dev1 - the staging instance
  # /cback is NOT a typo and NOT dev1-specific. nginx maps it to Laravel's
  # public root on every deployment, so the API's real base is
  # https://<host>/cback/api/public/v1. This entry said https://<host>/api/public/v1
  # for its whole life, which reaches the Next.js frontend and answers an
  # HTML 404 - so a reader who copied a sample got a page of markup rather
  # than an API error, and no reason to suspect the URL.
  - url: https://{host}/cback/api/public/v1
    description: Another CRM instance (Send needs CORS on that host)
    variables:
      host:
        default: app.aiengagecrm.com
        description: The host your CRM is served from

security:
  - bearerAuth: []

tags:
  - name: Records
    description: >-
      Create, read, update, archive and upsert a single record in any module.
      Six endpoints that work identically for contacts, deals, a custom module
      or anything else your organization defines.
  - name: Search Records
    description: >-
      Filtered search with a 15-operator DSL. A POST that reads - the body
      carries the filter and nothing is mutated. Draws on a tighter rate-limit
      bucket than the rest of the API.
  - name: Batch Operations
    description: >-
      Up to 100 records per call. Always answers 207 Multi-Status with
      per-item results and errors, so one bad row never costs you the other
      ninety-nine.
  - name: Associations
    description: >-
      Link, list and unlink records across modules - the connector records
      behind the CRM's Related Lists. Both sides of an association are
      scope-checked.
  - name: Fields Metadata
    description: >-
      What fields a module has in THIS organization: name, type, whether it is
      required, unique or read-only, and a picklist's accepted values. Call
      this before you write, rather than guessing at field names.
  - name: Email
    description: >-
      Send one email from one of your organization's own addresses, and track
      what happens to it. One call sends one message, each with its own
      subject and body - this is not a campaign API. Sending is OFF by
      default: a request validates and reports back what it would have sent
      unless you explicitly ask it to deliver.
  - name: WhatsApp
    description: >-
      Send an approved WhatsApp template to a phone number, and discover the
      templates you are allowed to send. Delivery spends WhatsApp credits and
      there is no dry run - every accepted call reaches the recipient.


components:

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        `Authorization: Bearer <token>`

        Four token kinds are accepted - a `cak_live_*` Personal Access Token,
        a purpose-scoped agent JWT, an ordinary dashboard login JWT, or a
        `cak_oauth_*` token from the OAuth flow. Every authentication failure
        in every mode returns an identical 401 body.

        The token acts as the user who created it, so record visibility is
        that person's.

  parameters:
    ModuleSlug:
      name: module
      in: path
      required: true
      description: >-
        API name of the module whose records you want. Resolution tries the
        exact slug, then a case-insensitive slug match, then the module's
        display / singular / plural name - prefer the slug. A module that does
        not exist, is de-activated, or has `public_api_enabled = false`
        returns 404 MODULE_NOT_AVAILABLE.
      schema:
        type: string
      examples:
        contacts: { value: contacts }
        deals: { value: deals }
        custom: { value: my_custom_module }

    RecordId:
      name: id
      in: path
      required: true
      description: >-
        The record's unique id. When `id_property` is also sent, this is that
        property's value instead.
      schema:
        type: string
      example: '6650f1a2b3c4d5e6f7a8b9c0'

    ToModule:
      name: toModule
      in: path
      required: true
      description: API name of the module on the FAR side of the association.
      schema:
        type: string
      example: deals

    ToId:
      name: toId
      in: path
      required: true
      description: Id of the record on the far side.
      schema:
        type: string
      example: '6651aabbccddeeff00112233'

    # Deliberately carries NO `example`.
    #
    # The docs page appends every query parameter that has one to the sample
    # URL. With an example here, Get / Update / Archive Record produced
    #     /objects/contacts/6650f1a2b3c4d5e6f7a8b9c0?id_property=email
    # which asks for a contact whose EMAIL is that id, and 404s. Anyone
    # pressing Copy got a command that could not work.
    #
    # The correct usage is in the description below, and in each operation's
    # Sample Request, which puts the email in the path where it belongs.
    IdProperty:
      name: id_property
      in: query
      required: false
      description: >-
        Address the record by this property instead of its id - e.g.
        `id_property=email` with `id=ada@example.com`. If the property is not
        unique and more than one record matches, the call returns 409 CONFLICT
        rather than picking one.
      schema:
        type: string

    Limit:
      name: limit
      in: query
      required: false
      description: >-
        Page size. Clamped server-side to 1..100 - a value outside that range
        is silently clamped, not rejected.
      schema: { type: integer, minimum: 1, maximum: 100, default: 10 }

    AfterCursor:
      name: after
      in: query
      required: false
      description: >-
        Opaque forward cursor, taken verbatim from `paging.next.after` of the
        previous page. Do not construct one yourself - a malformed value
        returns 400 INVALID_CURSOR.
      schema: { type: string }

    Sort:
      name: sort
      in: query
      required: false
      description: >-
        `field:direction`. Direction is `asc` or `desc`; anything else falls
        back to `desc`, and an empty field falls back to `created_at`.
      schema: { type: string, default: 'created_at:desc' }
      example: 'created_at:desc'

    Archived:
      name: archived
      in: query
      required: false
      description: >-
        Include archived (soft-deleted) records. Only the exact strings `true`
        and `any` switch this on; anything else is ignored.
      schema: { type: string, enum: ['true', 'any'] }

    SparseProperties:
      name: properties
      in: query
      required: false
      description: >-
        Comma-separated property names to limit what comes back under
        `properties`. Envelope metadata (id, timestamps, archived) is always
        returned regardless.
      schema: { type: string }
      example: 'email,first_name'

    Include:
      name: include
      in: query
      required: false
      description: >-
        Comma-separated **lookup field names on this module** to expand inline.
        The valid set is per-tenant - read it from `GET /properties/{module}`.
        Maximum 5; more, or an unknown name, returns 400 INVALID_PROPERTY.
        Expanding requires `crm.<target>.read` for EVERY distinct target
        module across the returned rows; missing any returns 403 MISSING_SCOPE
        listing the full set needed.
      schema: { type: string }
      # DELIBERATELY NO example. A query parameter with one is written into
      # every generated sample, and the description above says why no value
      # can be right there: the valid set is per-tenant. The example used to
      # be 'company,owner', which made the Get Records and Get Record
      # samples - the two most basic calls in this document - answer
      #     400 ?include='company' is not a lookup property on 'contacts'
      # for every reader who copied them, key and id correct. Verified
      # against a live account: no value works on contacts, because its only
      # lookup fields are user_lookup, country_lookup and state_lookup, and
      # the API refuses all of those as "not exposable via the public API
      # yet". A reader who wants this reads their own set from
      # GET /properties/{module}, which is what the description tells them.

    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: >-
        Makes a retry safe. Same key + same body replays the cached response
        with `Idempotency-Replayed: true`; same key + different body returns
        409 IDEMPOTENCY_KEY_CONFLICT. Cached 24 hours.
      schema: { type: string }
      example: '8f14e45f-ea2b-4f8a-9c21-7d3b6a1e0c55'

    # Same header as IdempotencyKey above, but REQUIRED.
    #
    # Sending is the one operation on this API with an irreversible side
    # effect: a retry after a timeout would put a second copy of the message
    # in someone's inbox and spend a second credit. Optional-by-default is the
    # wrong default there, so /campaign/send refuses a request without a key.
    IdempotencyKeyRequired:
      name: Idempotency-Key
      in: header
      required: true
      description: >-
        REQUIRED on this endpoint. Use a fresh value for each new message, and
        reuse the SAME value when retrying a request whose outcome you are
        unsure of - that is what stops a retry delivering the email twice.
        Same key + same body replays the first response; same key + different
        body returns 409 IDEMPOTENCY_KEY_CONFLICT. Cached 24 hours.
      schema: { type: string }
      example: '8f14e45f-ea2b-4f8a-9c21-7d3b6a1e0c55'

  headers:
    XCorrelationId:
      description: Correlation id for this request. Log it - it is how support traces your call.
      schema: { type: string }
    RateLimitLimit:
      description: Requests permitted in the current window.
      schema: { type: integer }
    RateLimitRemaining:
      description: Requests left in the current window.
      schema: { type: integer }
    RateLimitReset:
      description: Seconds until the window resets.
      schema: { type: integer }
    RetryAfter:
      description: Seconds to wait before retrying.
      schema: { type: integer }
    IdempotencyReplayed:
      description: Present and true when this response was replayed from the idempotency cache.
      schema: { type: boolean }
    XUpsertAction:
      description: >-
        Whether the upsert created a new record or updated an existing one.
        The status code is 200 either way, so this header is how you tell.
      schema: { type: string, enum: [created, updated] }

  schemas:

    Error:
      type: object
      description: The single error envelope used by every endpoint in this API.
      required: [status, message, category]
      properties:
        status: { type: string, const: error }
        message:
          type: string
          description: Human-readable explanation. Do not branch on this - the wording can change.
        category:
          type: string
          description: Stable machine-readable category. This is what you branch on.
          enum:
            - UNAUTHORIZED
            - MISSING_SCOPE
            - FORBIDDEN
            - VALIDATION_ERROR
            - INVALID_PROPERTY
            - INVALID_FILTER
            - INVALID_CURSOR
            - OBJECT_NOT_FOUND
            - MODULE_NOT_AVAILABLE
            - CONFLICT
            - IDEMPOTENCY_KEY_CONFLICT
            - RATE_LIMITED
            - RATE_LIMITED_DAILY
            - RATE_LIMITED_MONTHLY
            - INTERNAL_ERROR
        correlationId:
          type: [string, 'null']
          description: Quote this when reporting a problem.
        errors:
          type: array
          description: Per-property detail. Empty for errors that are not field-specific.
          items:
            type: object
            properties:
              property: { type: string }
              code: { type: string }
              message: { type: string }
        documentation_url: { type: string, format: uri }

    Record:
      type: object
      description: >-
        One record. Envelope metadata at the top level, every module-defined
        field under `properties`.
      required: [id, properties, created_at, updated_at, archived]
      properties:
        id:
          type: string
          description: The record's unique id.
        properties:
          type: object
          description: >-
            The module's public-API-visible fields, keyed by the field's public
            name. Always an object - `{}` when empty, never `[]`. Fields marked
            `is_public_api_visible = false` are absent entirely.
          additionalProperties: true
        created_at:
          type: [string, 'null']
          description: UTC, `YYYY-MM-DDTHH:MM:SS.sssZ`. **read-only**
        updated_at:
          type: [string, 'null']
          description: UTC. **read-only**
        created_by:
          type: [string, 'null']
          description: Id of the user who created it. **read-only**
        updated_by:
          type: [string, 'null']
          description: Id of the user who last updated it. **read-only**
        archived:
          type: boolean
          description: True once the record has been archived. **read-only**
        includes:
          type: object
          description: >-
            Present only when `?include=` was sent. One key per expanded lookup
            field. A single lookup gives an object or null; a multi lookup
            gives an array; polymorphic lookups add `_module` to each expanded
            record. `null` means the lookup pointed at a record that no longer
            exists or has been archived.
          additionalProperties: true
      example:
        id: '6650f1a2b3c4d5e6f7a8b9c0'
        properties:
          first_name: Ada
          last_name: Lovelace
          email: ada@example.com
        created_at: '2026-11-10T09:30:00.000Z'
        updated_at: '2026-11-10T09:30:00.000Z'
        created_by: '6640a1b2c3d4e5f6a7b8c9d0'
        updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
        archived: false

    RecordList:
      type: object
      required: [results]
      properties:
        results:
          type: array
          items: { $ref: '#/components/schemas/Record' }
        paging:
          $ref: '#/components/schemas/CursorPaging'

    CursorPaging:
      type: object
      description: Present only when there is another page. Cursor-based, not offset.
      properties:
        next:
          type: object
          properties:
            after:
              type: string
              description: Pass this back as `?after=` for the next page.
            link:
              type: string
              format: uri
              description: A ready-made URL for the next page, preserving your query parameters.

    OffsetPaging:
      type: object
      description: >-
        Offset paging. Used ONLY by the association list endpoint - every other
        list on this API is cursor-paged.
      properties:
        total: { type: integer }
        page: { type: integer }
        limit: { type: integer }

    WriteBody:
      type: object
      description: >-
        The body for create, update and upsert. Only the presence and type of
        `properties` is checked at the HTTP layer; per-field rules come from
        your organization's own field configuration and surface as
        400 VALIDATION_ERROR with a per-property `errors` array.
      required: [properties]
      properties:
        properties:
          type: object
          additionalProperties: true
      example:
        properties:
          first_name: Ada
          last_name: Lovelace
          email: ada@example.com

    Property:
      type: object
      description: One field definition on a module, as returned by the Fields Metadata endpoints.
      properties:
        name:
          type: string
          description: >-
            The field's public name - this is the key to use inside
            `properties` on reads and writes.
        label:
          type: string
          description: Human-readable field name, as shown in the CRM UI.
        type:
          $ref: '#/components/schemas/FieldType'
        group:
          type: [string, 'null']
          description: The layout section the field sits in.
        description:
          type: [string, 'null']
          description: The field's help text.
        options:
          type: [array, 'null']
          description: >-
            `null` for every type except `pick_list`, `picklist`,
            `multi_select` and `dropdown`. An empty array when it is a picklist
            with no options configured.
          items:
            type: object
            properties:
              label: { type: string }
              value: { type: string }
              display_order: { type: integer }
              hidden: { type: boolean }
        required_on_create:
          type: boolean
          description: True when the field is required and not internal.
        read_only: { type: boolean }
        unique:
          type: boolean
          description: Safe to use as `id_property` or `matching_property`.
        searchable: { type: boolean }
        created_at: { type: [string, 'null'] }
        updated_at: { type: [string, 'null'] }
      example:
        name: email
        label: Email
        type: email
        group: Contact Information
        description: null
        options: null
        required_on_create: false
        read_only: false
        unique: true
        searchable: true
        created_at: '2026-01-15T10:00:00.000Z'
        updated_at: '2026-01-15T10:00:00.000Z'

    FieldType:
      type: string
      description: >-
        The field's storage type, passed through verbatim. The last six values
        are legacy aliases that still exist in stored data and are therefore
        still returned: `text` for `single_line`, `textarea` for `multi_line`,
        `datetime` for `date_time`, `dropdown` for `pick_list`, `user` for
        `user_lookup`, `rollup_summary` for `rollup`.
      enum:
        - single_line
        - multi_line
        - email
        - phone
        - url
        - pick_list
        - multi_select
        - checkbox
        - radio
        - date
        - date_time
        - number
        - auto_number
        - decimal
        - currency
        - percent
        - long_integer
        - lookup
        - user_lookup
        - participants
        - participant_users
        - participant_contacts
        - file
        - file_upload
        - image
        - image_upload
        - video_upload
        - rich_text
        - formula
        - rollup
        - multi_select_lookup
        - subform
        - line_items
        - country_lookup
        - state_lookup
        - json
        - text
        - textarea
        - datetime
        - dropdown
        - user
        - rollup_summary

    SearchBody:
      type: object
      description: All fields optional. An empty body is a valid "first page, newest first" search.
      properties:
        filterGroups:
          type: array
          maxItems: 5
          description: >-
            Groups are OR-ed together; filters inside one group are AND-ed.
            Maximum 5 groups, maximum 6 filters per group - exceeding either
            returns 400 INVALID_FILTER.
          items: { $ref: '#/components/schemas/FilterGroup' }
        sorts:
          type: array
          maxItems: 3
          items: { $ref: '#/components/schemas/Sort' }
        properties:
          type: array
          description: Sparse fieldset - limit which properties come back.
          items: { type: string }
        limit: { type: integer, minimum: 1, maximum: 100 }
        after: { type: string }
        query:
          type: string
          description: Free-text term, searched across the module's searchable fields.

    FilterGroup:
      type: object
      properties:
        filters:
          type: array
          maxItems: 6
          items: { $ref: '#/components/schemas/Filter' }

    Filter:
      type: object
      required: [propertyName, operator]
      properties:
        propertyName:
          type: string
          description: A field's public name, from GET /properties/{module}.
        operator:
          type: string
          description: >-
            `HAS_PROPERTY` and `NOT_HAS_PROPERTY` take no value. `BETWEEN`
            takes two. `IN` and `NOT_IN` take a list in `values`. The four
            text operators are case-insensitive and treat the value literally,
            so regex metacharacters are safe.
          enum:
            - EQ
            - NEQ
            - LT
            - LTE
            - GT
            - GTE
            - BETWEEN
            - IN
            - NOT_IN
            - HAS_PROPERTY
            - NOT_HAS_PROPERTY
            - CONTAINS_TOKEN
            - NOT_CONTAINS_TOKEN
            - STARTS_WITH
            - ENDS_WITH
        value:
          description: For the single-value operators.
        values:
          type: array
          description: For `IN` and `NOT_IN`.
          items: {}
        highValue:
          description: The upper bound, for `BETWEEN`.

    Sort:
      type: object
      required: [propertyName]
      properties:
        propertyName: { type: string }
        direction: { type: string, enum: [ASCENDING, DESCENDING], default: DESCENDING }

    BatchBody:
      type: object
      required: [inputs]
      properties:
        inputs:
          type: array
          minItems: 1
          maxItems: 100
          description: >-
            Maximum 100 items. Exceeding it returns 400 VALIDATION_ERROR and
            nothing is written. Only the array shape is validated up front -
            per-item problems come back inside the 207 response rather than
            failing the whole call.
          items:
            type: object
            additionalProperties: true

    BatchResponse:
      type: object
      description: >-
        Always returned with **HTTP 207**, whatever the outcome. Read `status`
        and `errors` - the status code alone tells you nothing.
      required: [status, results, errors]
      properties:
        status:
          type: string
          enum: [completed, partially_completed, failed]
          description: >-
            `completed` when no item failed, `failed` when none succeeded,
            `partially_completed` otherwise.
        results:
          type: array
          items: { $ref: '#/components/schemas/Record' }
        errors:
          type: array
          description: One entry per failed input, carrying that item's index and reason.
          items:
            type: object
            additionalProperties: true

    Association:
      type: object
      description: A link between two records.
      properties:
        from:
          type: object
          properties:
            module: { type: string }
            id: { type: string }
        to:
          type: object
          properties:
            module: { type: string }
            id: { type: string }
        id:
          type: [string, 'null']
          description: >-
            The relationship record's id. `null` when this response is the
            idempotent 200 for a link that already existed.
        created:
          type: boolean
          description: True only when this call created the link.

    AssociationList:
      type: object
      required: [results, paging]
      properties:
        results:
          type: array
          description: The far-side records.
          items: { $ref: '#/components/schemas/Record' }
        paging: { $ref: '#/components/schemas/OffsetPaging' }

    WhatsappTemplate:
      type: object
      description: >-
        One approved WhatsApp template. List Templates and Get Template
        return this same shape, so one decoder handles both.
      properties:
        id:
          type: string
          description: The id you send with.
        name:
          type: string
          description: The name this template carries in the CRM.
        provider_name:
          type: string
          description: The name it is registered under at the provider.
        category:
          type: string
          description: Its WhatsApp category - marketing, utility or authentication.
        language:
          type: string
          description: The language code it was approved in.
        template_type:
          type: string
          description: standard, carousel, LTO or authentication.
        supports_send:
          type: boolean
          description: >-
            Always true. Every approved type is sendable through this API;
            the field is kept so older clients keep decoding.
        body:
          type: string
          description: >-
            The message text, with {{1}}, {{2}}, … marking where your values
            go.
        placeholders:
          description: >-
            Position to field name. Either an object keyed "1", "2", … or an
            array in that same order - both occur, depending on how the
            template was built. The ORDER is what you need when sending.
          oneOf:
            - type: object
              additionalProperties:
                type: string
            - type: array
              items:
                type: string
        sender_id:
          type: [string, 'null']
          description: >-
            The WhatsApp sender this template is registered under, or null on
            an older template that is bound to none.

    # =======================================================================
    # Per-module field schemas were REMOVED on purpose.
    #
    # Fields are defined per organization: an admin adds, renames and removes
    # them, so any list baked in here is a snapshot that goes stale and
    # quietly starts lying. GET /properties/{module} is the only honest
    # answer, and the guide tells readers to call it first.

  responses:
    Unauthorized:
      description: |
        **UNAUTHORIZED** - token missing, malformed, unknown, revoked or
        expired.
        *Resolution:* paste a current key. `message` varies with the cause,
        `category` does not - branch on `category`.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            noHeader:
              summary: No Authorization header sent
              value:
                status: error
                message: Missing or malformed Authorization header.
                category: UNAUTHORIZED
                correlationId: 01M722ZY936QDSH0XGVVR3S97F
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
            badToken:
              summary: Header present, token unknown or revoked
              value:
                status: error
                message: Invalid or revoked token.
                category: UNAUTHORIZED
                correlationId: 01M722ZYCVY2NTB5XAP8GZ7RS0
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors

    MissingScope:
      description: |
        **MISSING_SCOPE** - the token does not hold this route's scope.
        *Resolution:* the message names the scope; re-issue the key with it.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            status: error
            message: 'Token is missing the required scope: crm.contacts.write.'
            category: MISSING_SCOPE
            correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
            errors: []
            documentation_url: https://developer.aiengagecrm.com/#g-errors

    ModuleNotAvailable:
      description: |
        **MODULE_NOT_AVAILABLE** - no module matches that name, it is
        de-activated, or an admin set `public_api_enabled = false` on it.
        *Resolution:* holding the scope does not override publication - ask an
        admin to publish the module.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            status: error
            message: "No module matches 'contact'. Call GET /objects for the available modules and use the `slug` from that list."
            category: MODULE_NOT_AVAILABLE
            correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
            errors: []
            documentation_url: https://developer.aiengagecrm.com/#g-errors

    ObjectNotFound:
      description: |
        **OBJECT_NOT_FOUND** - no such record, or it is outside your key's
        visibility. The two look alike on purpose, so existence never leaks.
        *Resolution:* check the id, and that your key's user can see it.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }

    ValidationError:
      description: |
        **VALIDATION_ERROR** or **INVALID_PROPERTY** - the body or a query
        parameter failed validation.
        *Resolution:* `errors[]` names the property at fault - fix that one.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            status: error
            message: Request body failed validation.
            category: VALIDATION_ERROR
            correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
            errors:
              - property: properties
                code: INVALID_VALUE
                message: The properties field is required.
            documentation_url: https://developer.aiengagecrm.com/#g-errors

    Conflict:
      description: |
        **CONFLICT** - an `id_property` or `matching_property` on a non-unique
        field matched more than one record, or an idempotency key was reused
        with a different body. *Resolution:* use a field marked `unique`.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }

    Forbidden:
      description: |
        **FORBIDDEN** - the acting user may not perform this operation - an
        owner change without Change Owner, say, or a batch with Mass Update off.
        *Resolution:* ask an admin to grant that permission on their profile.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }

    RateLimited:
      description: |
        **RATE_LIMITED**, **RATE_LIMITED_DAILY** or **RATE_LIMITED_MONTHLY**.
        The category tells you which. *Resolution:* wait `Retry-After` seconds.
      headers:
        Retry-After: { $ref: '#/components/headers/RetryAfter' }
        RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
        RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
        RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }

    InternalError:
      description: |
        **INTERNAL_ERROR** - an unexpected failure, or the user who created
        this token has been deleted. *Resolution:* revoke the token and issue a
        new one. Quote `correlationId` when reporting it.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }


paths:

  # ===========================================================================
  # RECORDS
  # ===========================================================================
  /objects/{module}:
    get:
      operationId: getRecords
      tags: [Records]
      summary: Get Records
      description: |
        **Purpose**

        Retrieve the records of a module, newest first, one page at a time.
        **Scope**

        `crm.{module}.read` - e.g. calling `/objects/contacts` requires
        `crm.contacts.read`.
        **Note**

        - Results are limited to what the acting user may see. Two keys in the
          same organization can legitimately return different records.
        - Archived records are excluded unless you pass `archived=true`.
        - Paging is cursor-based. Take `paging.next.after` from the response
          and pass it back as `?after=`; `paging` is absent on the last page.
        - `limit` is clamped to 1..100 rather than rejected.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `INVALID_CURSOR` | 400 | The `after` value is malformed. | Pass `paging.next.after` back verbatim; never build a cursor. |
        | `INVALID_PROPERTY` | 400 | An `include` name is not a lookup field on this module, or more than 5 were sent. | Check `GET /properties/{module}`. |
        | `MISSING_SCOPE` | 403 | The key lacks `crm.{module}.read`, or a scope for a module named in `include`. | The message lists every scope needed. |
        | `MODULE_NOT_AVAILABLE` | 404 | Unknown, de-activated or unpublished module. | Ask an admin to publish it. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/AfterCursor'
        - $ref: '#/components/parameters/Sort'
        - $ref: '#/components/parameters/Archived'
        - $ref: '#/components/parameters/SparseProperties'
        - $ref: '#/components/parameters/Include'
      responses:
        '200':
          description: A page of records.
          headers:
            X-Correlation-Id: { $ref: '#/components/headers/XCorrelationId' }
            RateLimit-Limit: { $ref: '#/components/headers/RateLimitLimit' }
            RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
            RateLimit-Reset: { $ref: '#/components/headers/RateLimitReset' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RecordList' }
              example:
                results:
                  - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    properties:
                      first_name: Ada
                      last_name: Lovelace
                      email: ada@example.com
                    created_at: '2026-11-10T09:30:00.000Z'
                    updated_at: '2026-11-10T09:30:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                paging:
                  next:
                    after: eyJpZCI6IjY2NTBmMWEyIn0
                    link: https://app.aiengagecrm.com/cback/api/public/v1/objects/contacts?after=eyJpZCI6IjY2NTBmMWEyIn0&limit=25
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

    post:
      operationId: insertRecord
      tags: [Records]
      summary: Insert Record
      description: |
        **Purpose**

        Create one record in a module.
        **Scope**

        `crm.{module}.write` - granted only when the token's user has **both**
        create and edit permission on the module.
        **Note**

        - Only the presence and type of `properties` is checked at the HTTP
          layer. Per-field rules - date formats, picklist membership, numeric
          ranges, required fields - come from **your organization's own field
          configuration**, so a body this schema accepts can still be refused.
        - To create many records in one call, use
          `POST /objects/{module}/batch/create` instead.
        - Mandatory fields differ per module. Check `required_on_create` in
          `GET /properties/{module}`, or the per-module tables in this
          document.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | A field failed its rule, or `properties` is missing. | `errors[]` names the property and the reason. |
        | `INVALID_PROPERTY` | 400 | A key in `properties` is not a field on this module. | Check `GET /properties/{module}` for real names. |
        | `MISSING_SCOPE` | 403 | The key lacks `crm.{module}.write`. | Remember it needs create AND edit permission. |
        | `MODULE_NOT_AVAILABLE` | 404 | Unknown, de-activated or unpublished module. | |
        | `IDEMPOTENCY_KEY_CONFLICT` | 409 | The key was reused with a different body. | Use a fresh key per operation. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WriteBody' }
            examples:
              contact:
                summary: A contact
                value:
                  properties:
                    first_name: Ada
                    last_name: Lovelace
                    email: ada@example.com
                    # contact_owner is NOT in this sample, and that is
                    # deliberate. It used to be, as a bare id string, and it
                    # made the most-copied write call in this document answer
                    #   400 Property 'contact_owner' is polymorphic - provide
                    #       "{module: '<slug>', id: '<id>'}"
                    # Sending the object it asks for answers
                    #   400 The Contact Owner field must be a string.
                    # Both were checked against the live API. The two
                    # validators disagree, so no value can satisfy them and
                    # this is an API bug, reported separately. Omitting the
                    # field creates the contact (201) and leaves the owner
                    # unset, which is what the sample is for.
              deal:
                summary: A deal
                value:
                  properties:
                    deal_name: Acme renewal
                    amount: 12000
                    closing_date: '2026-12-31'
      responses:
        '201':
          description: Created.
          headers:
            X-Correlation-Id: { $ref: '#/components/headers/XCorrelationId' }
            Idempotency-Replayed: { $ref: '#/components/headers/IdempotencyReplayed' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Record' }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '409': { $ref: '#/components/responses/Conflict' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

    put:
      operationId: upsertRecord
      tags: [Records]
      summary: Upsert Record
      description: |
        **Purpose**

        Create a record, or update it if one already matches on a property you
        nominate. Useful for syncing from an external system where you know an
        email or an external id but not the CRM's record id.
        **Scope**

        `crm.{module}.write`
        **Note**

        - `matching_property` is **mandatory**. It is validated in the
          controller rather than by the body validator, so omitting it gives
          `400 VALIDATION_ERROR` with the message
          *"Query parameter matching_property is required for PUT upsert."*
        - The status is **200 whether it created or updated**. Read the
          **`X-Upsert-Action`** response header - `created` or `updated` - to
          tell which happened.
        - Use a field marked `unique` in the property schema. A non-unique
          field that matches more than one record returns `409 CONFLICT`
          rather than the API guessing which you meant.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | `matching_property` missing, or a field failed its rule. | Add the query parameter. |
        | `INVALID_PROPERTY` | 400 | `matching_property` is not a field on this module. | Check `GET /properties/{module}`. |
        | `FORBIDDEN` | 403 | The match would change the record's owner and the user lacks Change Owner. | A permissions change, not a token change. |
        | `CONFLICT` | 409 | The matching property is not unique and matched several records. | Nominate a unique field. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - name: matching_property
          in: query
          required: true
          description: >-
            The property to match an existing record on. Mandatory. Best used
            with a field whose `unique` flag is true.
          schema: { type: string }
          example: email
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WriteBody' }
            example:
              properties:
                email: ada@example.com
                first_name: Ada
                last_name: Lovelace
      responses:
        '200':
          description: >-
            The resulting record. Read `X-Upsert-Action` to learn whether it
            was created or updated.
          headers:
            X-Upsert-Action: { $ref: '#/components/headers/XUpsertAction' }
            X-Correlation-Id: { $ref: '#/components/headers/XCorrelationId' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Record' }
        '400':
          description: '`VALIDATION_ERROR` - including a missing `matching_property` - or `INVALID_PROPERTY`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Query parameter matching_property is required for PUT upsert.
                category: VALIDATION_ERROR
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '409': { $ref: '#/components/responses/Conflict' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /objects/{module}/{id}:
    get:
      operationId: getRecord
      tags: [Records]
      summary: Get Record
      description: |
        **Purpose**

        Retrieve a single record by its id, or by any other property.
        **Scope**

        `crm.{module}.read`
        **Note**

        - A record that exists but sits outside the acting user's visibility
          returns **404**, exactly as a record that does not exist. This is
          deliberate: existence is never leaked.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `INVALID_PROPERTY` | 400 | `id_property` is not a field on this module. | Check `GET /properties/{module}`. |
        | `OBJECT_NOT_FOUND` | 404 | No such record, or it is outside your visibility. | The two are indistinguishable by design. |
        | `CONFLICT` | 409 | `id_property` is not unique and matched several records. | Nominate a unique field. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/RecordId'
        - $ref: '#/components/parameters/IdProperty'
        - $ref: '#/components/parameters/SparseProperties'
        - $ref: '#/components/parameters/Include'
      responses:
        '200':
          description: The record.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Record' }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ObjectNotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '429': { $ref: '#/components/responses/RateLimited' }

    patch:
      operationId: updateRecord
      tags: [Records]
      summary: Update Record
      description: |
        **Purpose**

        Update one record. Partial - only the properties you send are touched;
        everything else is left as it is.
        **Scope**

        `crm.{module}.write`
        **Note**

        - Accepts `id_property`, so you can address the record by email or any
          other field rather than its id.
        - Changing the owner field needs the acting user to hold **Change
          Owner** in their profile. Without it the call returns 403, even
          though the token holds `write`.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | A field failed its rule. | `errors[]` names the property. |
        | `FORBIDDEN` | 403 | An owner change the acting user may not make. | Needs Change Owner in their profile. |
        | `OBJECT_NOT_FOUND` | 404 | No such record, or outside your visibility. | |
        | `CONFLICT` | 409 | `id_property` matched several records. | Use a unique field. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/RecordId'
        - $ref: '#/components/parameters/IdProperty'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WriteBody' }
            example:
              properties:
                lifecycle_stage: customer
      responses:
        '200':
          description: The updated record.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Record' }
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/ObjectNotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '429': { $ref: '#/components/responses/RateLimited' }

    delete:
      operationId: archiveRecord
      tags: [Records]
      summary: Archive Record
      description: |
        **Purpose**

        Archive (soft-delete) one record. It stops appearing in listings and
        searches but is not destroyed.
        **Scope**

        `crm.{module}.delete` - a separate scope from `write`, mapping to the
        module's delete permission.
        **Note**

        - Returns **204 with no body** on success.
        - To see archived records again, list with `?archived=true`.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `MISSING_SCOPE` | 403 | The key holds `write` but not `delete`. | They are separate scopes. |
        | `OBJECT_NOT_FOUND` | 404 | No such record, or outside your visibility. | |
        | `CONFLICT` | 409 | `id_property` matched several records. | Use a unique field. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/RecordId'
        - $ref: '#/components/parameters/IdProperty'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '204':
          description: Archived. No body.
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ObjectNotFound' }
        '409': { $ref: '#/components/responses/Conflict' }
        '429': { $ref: '#/components/responses/RateLimited' }

  # ===========================================================================
  # SEARCH
  # ===========================================================================
  /objects/{module}/search:
    post:
      operationId: searchRecords
      tags: [Search Records]
      summary: Search Records
      description: |
        **Purpose**

        Find records matching a filter. A POST that **reads** - the body
        carries the filter, nothing is mutated.
        **Scope**

        `crm.{module}.read`

        **Rate limit**

        This endpoint draws on the tighter **`search` bucket: 5 requests per
        second**, not the general 100 per 10 seconds. Budget for it.
        **How filters combine**

        Filters inside one group are **AND**-ed. Groups are **OR**-ed with
        each other. Maximum **5 groups**, maximum **6 filters per group**.

        **Operators**

        | Operator | Takes | Notes |
        |---|---|---|
        | `EQ` `NEQ` `LT` `LTE` `GT` `GTE` | `value` | |
        | `BETWEEN` | `value` + `highValue` | Inclusive both ends. |
        | `IN` `NOT_IN` | `values` array | |
        | `HAS_PROPERTY` `NOT_HAS_PROPERTY` | nothing | Tests whether the field is set at all. |
        | `CONTAINS_TOKEN` `NOT_CONTAINS_TOKEN` | `value` | Case-insensitive substring. |
        | `STARTS_WITH` `ENDS_WITH` | `value` | Case-insensitive. |

        The four text operators quote regex metacharacters, so a value like
        `a.b*c` is matched literally and is safe to pass through from user
        input.

        **Note**

        - An empty body is valid and returns the first page, newest first.
        - When `sorts` is omitted the default is
          `created_at DESCENDING`.
        - Paging is the same cursor scheme as the list endpoint.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `INVALID_FILTER` | 400 | Unknown operator, more than 5 groups, or more than 6 filters in a group. | The message says which limit you hit. |
        | `INVALID_PROPERTY` | 400 | A `propertyName` is not a field on this module. | Check `GET /properties/{module}`. |
        | `INVALID_CURSOR` | 400 | Malformed `after`. | Pass the previous cursor back verbatim. |
        | `RATE_LIMITED` | 429 | The tight search bucket is exhausted. | 5 per second. Wait `Retry-After`. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
      requestBody:
        required: false
        description: All fields optional. An empty body returns the first page, newest first.
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SearchBody' }
            examples:
              byDomainAndDate:
                summary: Contacts at a domain, created this year
                value:
                  filterGroups:
                    - filters:
                        - propertyName: email
                          operator: CONTAINS_TOKEN
                          value: '@example.com'
                        - propertyName: created_at
                          operator: GTE
                          value: '2026-01-01'
                  sorts:
                    - propertyName: created_at
                      direction: DESCENDING
                  limit: 25
              freeText:
                summary: Free-text search
                value:
                  query: Lovelace
                  limit: 10
              eitherOr:
                summary: Two groups, OR-ed together
                value:
                  filterGroups:
                    - filters:
                        - propertyName: lifecycle_stage
                          operator: EQ
                          value: customer
                    - filters:
                        - propertyName: lifecycle_stage
                          operator: EQ
                          value: lead
              fieldIsSet:
                summary: Records where a field is set at all
                value:
                  filterGroups:
                    - filters:
                        - propertyName: phone
                          operator: HAS_PROPERTY
      responses:
        '200':
          description: Matching records.
          headers:
            RateLimit-Remaining: { $ref: '#/components/headers/RateLimitRemaining' }
          content:
            application/json:
              schema: { $ref: '#/components/schemas/RecordList' }
              example:
                results:
                  - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    properties:
                      first_name: Ada
                      last_name: Lovelace
                      email: ada@example.com
                      lifecycle_stage: customer
                    created_at: '2026-11-10T09:30:00.000Z'
                    updated_at: '2026-11-10T09:30:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                paging:
                  next:
                    after: eyJpZCI6IjY2NTBmMWEyIn0
        '400':
          description: '`INVALID_FILTER`, `INVALID_PROPERTY`, `INVALID_CURSOR` or `VALIDATION_ERROR`.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Max 5 filterGroups allowed.
                category: INVALID_FILTER
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }
        '500': { $ref: '#/components/responses/InternalError' }

  # ===========================================================================
  # BATCH
  # ===========================================================================
  /objects/{module}/batch/create:
    post:
      operationId: batchInsertRecords
      tags: [Batch Operations]
      summary: Insert Records (batch)
      description: |
        **Purpose**

        Create up to **100 records** in a single call.
        **Scope**

        `crm.{module}.write`
        **Sample Response (HTTP 207)**

        ```json
        {
          "status": "partially_completed",
          "results": [
            { "id": "6650f1a2b3c4d5e6f7a8b9c0", "properties": { "email": "ada@example.com" }, "archived": false }
          ],
          "errors": [
            { "index": 1, "category": "VALIDATION_ERROR", "message": "Property 'email' is required." }
          ]
        }
        ```

        **Note**

        - **The status code is always 207**, success or failure. Read `status`
          and `errors`; the code alone tells you nothing.
        - Each input is processed independently, so one bad row does not abort
          the other ninety-nine.
        - One `Idempotency-Key` covers the whole batch. A replay returns the
          cached 207 body unchanged.
        - More than 100 inputs is rejected up front with 400 and **nothing is
          written**.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | `inputs` missing, not an array, or over 100 items. | Split into batches of 100. Nothing was written. |
        | `MISSING_SCOPE` | 403 | The key lacks `crm.{module}.write`. | |
        | Per-item errors | 207 | Inside `errors[]`, not as an HTTP status. | Inspect each entry's `index`. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BatchBody' }
            example:
              inputs:
                - properties: { first_name: Ada, email: ada@example.com }
                - properties: { first_name: Grace, email: grace@example.com }
      responses:
        '207':
          description: Multi-Status. Per-item outcomes - read `status` and `errors`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BatchResponse' }
              example:
                status: completed
                results:
                  - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    properties:
                      first_name: Ada
                      last_name: Lovelace
                      email: ada@example.com
                    created_at: '2026-11-12T06:15:00.000Z'
                    updated_at: '2026-11-12T06:15:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                  - id: '6650f1a2b3c4d5e6f7a8b9c1'
                    properties:
                      first_name: Grace
                      last_name: Hopper
                      email: grace@example.com
                    created_at: '2026-11-12T06:15:00.000Z'
                    updated_at: '2026-11-12T06:15:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                errors: []
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /objects/{module}/batch/read:
    post:
      operationId: batchGetRecords
      tags: [Batch Operations]
      summary: Get Records (batch)
      description: |
        **Purpose**

        Fetch up to **100 records by id** in one call. A POST that reads.
        **Scope**

        `crm.{module}.read`

        **Rate limit**

        Uses the tighter **`search` bucket: 5 requests per second**.
        **Note**

        - Each input may carry its own `id_property`, so you can mix ids and
          emails in one call.
        - Records outside the acting user's visibility come back as per-item
          `OBJECT_NOT_FOUND` inside `errors[]`, not as a failed call.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | `inputs` missing or over 100 items. | Split into batches of 100. |
        | `MISSING_SCOPE` | 403 | The key lacks `crm.{module}.read`. | |
        | `RATE_LIMITED` | 429 | The search bucket is exhausted. | 5 per second. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/SparseProperties'
        - $ref: '#/components/parameters/Include'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BatchBody' }
            examples:
              byId:
                summary: By record id
                value:
                  inputs:
                    - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    - id: '6650f1a2b3c4d5e6f7a8b9c1'
              byProperty:
                summary: Mixed - id and email
                value:
                  inputs:
                    - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    - id: ada@example.com
                      id_property: email
      responses:
        '207':
          description: >-
            Multi-Status. One id that could not be read does not stop the
            others - it lands in `errors[]` with the `index` it came from.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BatchResponse' }
              example:
                status: partially_completed
                results:
                  - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    properties:
                      first_name: Ada
                      last_name: Lovelace
                      email: ada@example.com
                    created_at: '2026-11-10T09:30:00.000Z'
                    updated_at: '2026-11-10T09:30:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                errors:
                  - index: 1
                    category: OBJECT_NOT_FOUND
                    message: Record id '000000000000000000000000' not found.
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /objects/{module}/batch/update:
    post:
      operationId: batchUpdateRecords
      tags: [Batch Operations]
      summary: Update Records (batch)
      description: |
        **Purpose**

        Update up to **100 records** in one call.
        **Scope**

        `crm.{module}.write`
        **⚠ A batch of more than one record is a MASS UPDATE**

        This is the one place where a batch behaves differently from a loop of
        single calls. A batch with **two or more** inputs is treated as the
        API's mass update, and is checked against the acting user's profile
        **before anything is written**:

        - Mass Update switched off in their profile - the whole batch is
          refused with **403**, nothing written.
        - A batch that **only** sets owner fields is the API's Change Owner
          action, and needs **Change Owner** instead.
        - A **single-item** batch is an ordinary update and stays open,
          exactly as `PATCH` does.
        - An owner change inside a batch that also sets other fields still
          needs Change Owner, and surfaces as **that item's** error rather
          than refusing the batch.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | `inputs` missing or over 100 items. | Nothing was written. |
        | `FORBIDDEN` | 403 | Multi-item batch and the user lacks Mass Update (or Change Owner for an owner-only batch). | Nothing was written. A profile change is needed. |
        | `MISSING_SCOPE` | 403 | The key lacks `crm.{module}.write`. | |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BatchBody' }
            example:
              inputs:
                - id: '6650f1a2b3c4d5e6f7a8b9c0'
                  properties: { lifecycle_stage: customer }
                - id: grace@example.com
                  id_property: email
                  properties: { lifecycle_stage: customer }
      responses:
        '207':
          description: Multi-Status.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BatchResponse' }
              example:
                status: completed
                results:
                  - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    properties:
                      first_name: Ada
                      last_name: Lovelace
                      email: ada@example.com
                      lifecycle_stage: customer
                    created_at: '2026-11-10T09:30:00.000Z'
                    updated_at: '2026-11-12T06:20:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                errors: []
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: >-
            Either the scope is missing, or this is a multi-item batch and the
            acting user's profile does not grant Mass Update (or Change Owner,
            for an owner-only batch). **Nothing was written.**
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /objects/{module}/batch/archive:
    post:
      operationId: batchArchiveRecords
      tags: [Batch Operations]
      summary: Archive Records (batch)
      description: |
        **Purpose**

        Archive (soft-delete) up to **100 records** in one call.
        **Scope**

        `crm.{module}.delete`
        **⚠ A batch of more than one record is a MASS DELETE**

        Same rule as batch update: two or more inputs is the API's mass
        delete, and the whole batch is refused with **403 before anything is
        archived** when the acting user's profile has **Mass Delete** switched
        off. A single-item batch is an ordinary archive and stays open.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | `inputs` missing or over 100 items. | Nothing was archived. |
        | `FORBIDDEN` | 403 | Multi-item batch and Mass Delete is off for this user. | Nothing was archived. |
        | `MISSING_SCOPE` | 403 | The key lacks `crm.{module}.delete`. | `write` is not enough. |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BatchBody' }
            example:
              inputs:
                - id: '6650f1a2b3c4d5e6f7a8b9c0'
                - id: '6650f1a2b3c4d5e6f7a8b9c1'
      responses:
        '207':
          description: >-
            Multi-Status. `results[]` here is not a record - an archived
            record is not returned, only the id that was archived.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/BatchResponse' }
              example:
                status: completed
                results:
                  - id: '6650f1a2b3c4d5e6f7a8b9c0'
                    archived: true
                  - id: '6650f1a2b3c4d5e6f7a8b9c1'
                    archived: true
                errors: []
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403':
          description: >-
            Scope missing, or Mass Delete is switched off for the acting user.
            **Nothing was archived.**
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }

  # ===========================================================================
  # ASSOCIATIONS
  # ===========================================================================
  /objects/{module}/{id}/associations/{toModule}:
    get:
      operationId: getAssociations
      tags: [Associations]
      summary: Get Associations
      description: |
        **Purpose**

        List the records of another module that are linked to this one - the
        data behind the CRM's Related Lists.
        **Scope**

        **Both sides are checked.** You need `crm.{module}.read` **and**
        `crm.{toModule}.read`.

        The route middleware only covers the near `{module}`, because the
        scope gate substitutes `{module}` and cannot see `{toModule}`. The far
        side is checked inside the controller. Both halves are real - a
        contacts-only token cannot read a contact's linked deals.
        **Note**

        - This is the **only** list on this API that uses **offset** paging
          (`page` + `limit`, with a `total`). Everything else is cursor-paged.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `MISSING_SCOPE` | 403 | Missing the read scope for the near side **or** the far side. | Both are required. |
        | `MODULE_NOT_AVAILABLE` | 404 | Either module is unknown or unpublished. | |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/RecordId'
        - $ref: '#/components/parameters/ToModule'
        # Inlined rather than $ref'd to the shared Limit, so this one
        # operation can carry an example. A sample without it reads as
        # though the call returns everything a record is linked to - it
        # returns 20, and a reader who links 50 contacts to a company and
        # counts 20 back has no reason to suspect paging rather than a bug.
        # The example puts ?limit= in front of them before that happens.
        - name: limit
          in: query
          required: false
          description: >-
            How many links to return. Clamped server-side to 1..100 - a value
            outside that range is silently clamped, not rejected. Read
            `paging.total` to see how many there are in all.
          schema: { type: integer, minimum: 1, maximum: 100, default: 20 }
          example: 10
        - name: page
          in: query
          required: false
          description: >-
            1-based page number. This endpoint is offset-paged, not
            cursor-paged: ask for `page=2` to get the next `limit` of them,
            and keep going until `results` comes back empty.
          schema: { type: integer, minimum: 1, default: 1 }
      responses:
        '200':
          description: The linked far-side records.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/AssociationList' }
              example:
                results:
                  - id: '6651aabbccddeeff00112233'
                    properties:
                      deal_name: Acme renewal
                      amount: 12000
                    created_at: '2026-10-01T08:00:00.000Z'
                    updated_at: '2026-11-01T08:00:00.000Z'
                    created_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    updated_by: '6640a1b2c3d4e5f6a7b8c9d0'
                    archived: false
                paging:
                  total: 1
                  page: 1
                  limit: 10
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /objects/{module}/{id}/associations/{toModule}/{toId}:
    put:
      operationId: createAssociation
      tags: [Associations]
      summary: Create Association
      description: |
        **Purpose**

        Link two records across modules - for example a contact to a deal.
        **Scope**

        **Both sides:** `crm.{module}.write` **and** `crm.{toModule}.write`.
        **Sample Response (new link, HTTP 201)**

        ```json
        {
          "from": { "module": "contacts", "id": "6650f1a2b3c4d5e6f7a8b9c0" },
          "to":   { "module": "deals",    "id": "6651aabbccddeeff00112233" },
          "id": "6652ffeeddccbbaa99887766",
          "created": true
        }
        ```

        **Note**

        - **Idempotent.** If the link already exists, in either direction, the
          call returns **200** with `created: false` and `id: null` - not an
          error. Safe to retry.
        - No request body is needed; everything is in the path.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | These two records cannot be linked. | |
        | `FORBIDDEN` | 403 | Missing the write scope for the far side. | Both sides need `write`. |
        | `OBJECT_NOT_FOUND` | 404 | One of the records does not exist. | |
        | `MODULE_NOT_AVAILABLE` | 404 | One of the modules is unknown or unpublished. | |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/RecordId'
        - $ref: '#/components/parameters/ToModule'
        - $ref: '#/components/parameters/ToId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '201':
          description: The link was created by this call.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Association' }
              example:
                from: { module: contacts, id: '6650f1a2b3c4d5e6f7a8b9c0' }
                to: { module: deals, id: '6651aabbccddeeff00112233' }
                id: '6652ffeeddccbbaa99887766'
                created: true
        '200':
          description: >-
            The link already existed, in one direction or the other. Not an
            error - this endpoint is idempotent.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Association' }
              example:
                from: { module: contacts, id: '6650f1a2b3c4d5e6f7a8b9c0' }
                to: { module: deals, id: '6651aabbccddeeff00112233' }
                id: null
                created: false
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404': { $ref: '#/components/responses/ObjectNotFound' }
        '429': { $ref: '#/components/responses/RateLimited' }

    delete:
      operationId: deleteAssociation
      tags: [Associations]
      summary: Delete Association
      description: |
        **Purpose**

        Remove the link between two records. The records themselves are
        untouched.
        **Scope**

        **Both sides:** `crm.{module}.write` **and** `crm.{toModule}.write`.
        **Note**

        - Returns **204 with no body** on success.
        - A link that does not exist returns **404**, not a misleading 204.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `FORBIDDEN` | 403 | Missing the write scope for the far side. | |
        | `OBJECT_NOT_FOUND` | 404 | No association found between these records. | |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - $ref: '#/components/parameters/RecordId'
        - $ref: '#/components/parameters/ToModule'
        - $ref: '#/components/parameters/ToId'
        - $ref: '#/components/parameters/IdempotencyKey'
      responses:
        '204':
          description: Unlinked. No body.
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '404':
          description: No association found between these records.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: No association found between these records.
                category: OBJECT_NOT_FOUND
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }

  # ===========================================================================
  # FIELDS METADATA
  # ===========================================================================
  /properties/{module}:
    get:
      operationId: getFields
      tags: [Fields Metadata]
      summary: Get Fields
      description: |
        **Purpose**

        List the fields a module has **in this organization**. Call this
        first: it tells you the exact property names to use in `properties`,
        which are required, which are unique and which values a picklist
        accepts.
        **Scope**

        `crm.schema.read` - **not** a per-module scope. It is granted on the
        `manage_organization` feature permission, so one schema-enabled key
        can read every module's fields.
        **Note**

        - Fields are returned in layout order.
        - Fields marked `is_public_api_visible = false` are filtered out
          entirely - they will never appear here, and never in a record's
          `properties`.
        - `options` is `null` for every type except `pick_list`, `picklist`,
          `multi_select` and `dropdown`.
        - This is the **live source of truth** for a tenant. The per-module
          tables in this document are the seeded defaults, which an admin may
          have changed.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `MISSING_SCOPE` | 403 | The key lacks `crm.schema.read`. | This is an org-level scope, not per module. |
        | `MODULE_NOT_AVAILABLE` | 404 | Unknown, de-activated or unpublished module. | |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
      responses:
        '200':
          description: The module's fields, in layout order.
          content:
            application/json:
              schema:
                type: object
                required: [results]
                properties:
                  results:
                    type: array
                    items: { $ref: '#/components/schemas/Property' }
              example:
                results:
                  - name: email
                    label: Email
                    type: email
                    group: Contact Information
                    description: null
                    options: null
                    required_on_create: false
                    read_only: false
                    unique: true
                    searchable: true
                    created_at: '2026-01-15T10:00:00.000Z'
                    updated_at: '2026-01-15T10:00:00.000Z'
                  - name: lifecycle_stage
                    label: Lifecycle Stage
                    type: pick_list
                    group: Contact Information
                    description: null
                    options:
                      - { label: Lead, value: lead, display_order: 0, hidden: false }
                      - { label: Customer, value: customer, display_order: 1, hidden: false }
                    required_on_create: false
                    read_only: false
                    unique: false
                    searchable: true
                    created_at: '2026-01-15T10:00:00.000Z'
                    updated_at: '2026-01-15T10:00:00.000Z'
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404': { $ref: '#/components/responses/ModuleNotAvailable' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /properties/{module}/{property}:
    get:
      operationId: getField
      tags: [Fields Metadata]
      summary: Get Field
      description: |
        **Purpose**

        Retrieve one field definition by its public name.
        **Scope**

        `crm.schema.read`
        **Note**

        - Matched on the field's public name, which is what `GET
          /properties/{module}` returns as `name`.
        - Hidden fields are invisible here just as they are in the list.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `INVALID_PROPERTY` | **404** | The property does not exist on this module. | **Note the status:** this category is a 404 here, while the same category is a 400 on every other endpoint. This is the actual backend behaviour. |
        | `MODULE_NOT_AVAILABLE` | 404 | Unknown, de-activated or unpublished module. | |
      parameters:
        - $ref: '#/components/parameters/ModuleSlug'
        - name: property
          in: path
          required: true
          description: The field's public name, as returned by `GET /properties/{module}`.
          schema: { type: string }
          example: email
      responses:
        '200':
          description: The field definition.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Property' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404':
          description: >-
            The property does not exist on this module (`INVALID_PROPERTY`),
            or the module itself is unavailable (`MODULE_NOT_AVAILABLE`).
            `INVALID_PROPERTY` is a **404** here and a 400 everywhere else -
            documented as the backend actually behaves.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: "Property 'emial' does not exist on module 'contacts'."
                category: INVALID_PROPERTY
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }

  /email/from-addresses:
    get:
      operationId: listFromAddresses
      tags: [Email]
      summary: List From Addresses
      description: |
        **Purpose**

        The organization email addresses this key is allowed to send from.

        Call it before your first send. `from_account_id` on
        `POST /campaign/send` is an opaque id, and this is the only way to
        discover it - there is no way to guess one, and an address you can see
        in the CRM UI is not necessarily one an API key may use.
        **Scope**

        `email.from_addresses.read`

        Org-wide, not per-module. Granted to a key whose creating user has the
        **Email Channel** feature permission - the same permission that lets
        that person compose mail in the CRM.
        **Parameters**

        None.
        **Note**

        - **Only organization addresses are listed.** A person's own address
          belongs to that person; an API key is not a person, so personal
          addresses are never usable here and never appear.
        - **`trackable: false` addresses are listed, not hidden.** An address
          that sends over its own SMTP server gets no delivery, open or click
          callbacks, so `POST /campaign/send` refuses it. It is shown with the
          reason, because an address visible in Settings but absent here looks
          like a bug.
        - Disabled addresses are omitted entirely.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `UNAUTHORIZED` | 401 | Token missing, malformed or revoked. | Check the `Authorization` header. |
        | `MISSING_SCOPE` | 403 | The key lacks `email.from_addresses.read`. | Re-issue the key with that scope ticked. |
        | `RATE_LIMITED` | 429 | Per-window limit hit. | Wait `Retry-After` seconds. |

      responses:
        '200':
          description: The addresses this key may send from.
          content:
            application/json:
              example:
                status: success
                message: From addresses retrieved successfully
                data:
                  from_addresses:
                    - id: 6a1d971c81fd34ecd50b8c63
                      display_name: Support
                      email_address: support@yourcompany.com
                      reply_to: support@yourcompany.com
                      sending_server: AiTrillion
                      trackable: true
                      reason: null
                    - id: 6a1d971c81fd34ecd50b8c64
                      display_name: Billing
                      email_address: billing@yourcompany.com
                      reply_to: billing@yourcompany.com
                      sending_server: Custom SMTP
                      trackable: false
                      reason: >-
                        Sends over its own SMTP server, so opens, clicks and delivery
                        cannot be tracked. Not usable with this API.
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      from_addresses:
                        type: array
                        items:
                          type: object
                          properties:
                            id:
                              type: string
                              description: Pass this as from_account_id when sending.
                            display_name:
                              type: string
                              description: The name recipients see.
                            email_address:
                              type: string
                              format: email
                              description: The address mail leaves from.
                            reply_to:
                              type: string
                              format: email
                              description: Where replies go.
                            sending_server:
                              type: string
                              description: Which server delivers it. AiTrillion is the CRM's own sender.
                            trackable:
                              type: boolean
                              description: False when the address cannot report opens, clicks or delivery. Sending from it is refused.
                            reason:
                              type: [string, 'null']
                              description: Why it is not trackable. Null when it is.
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /campaign/send:
    post:
      operationId: sendCampaignMessage
      tags: [Email]
      summary: Send Campaign Message
      description: |
        **Purpose**

        Send one email from one of your organization's addresses, and track
        what happens to it afterwards.

        One call sends one message, with its own subject and body. Despite
        the path this does not run a marketing campaign - there is no
        audience, template or recipient list. The name points at where the
        sends are recorded: one per-organization campaign of type
        `api_log`, holding one row per message. Call it once per message.

        > **This can deliver real mail.** `test_mode` defaults to **true**,
        > which validates everything and sends nothing. You must pass
        > `"test_mode": false` to actually deliver. Pressing **Send** on this
        > page with the default body is safe.
        **Scope**

        `email.messages.send`

        Org-wide. Granted to a key whose creating user has the **Email
        Channel** feature permission.
        **Parameters**

        | Name | In | Required | Description |
        |---|---|---|---|
        | `from_account_id` | body | yes | An `id` from `GET /email/from-addresses`. Must be trackable. |
        | `to` | body | yes | One recipient address. |
        | `subject` | body | yes | Subject line. |
        | `body_html` | body | yes | HTML body, up to 256,000 bytes. |
        | `body_text` | body | no | Plain-text alternative. Derived from the HTML when omitted. |
        | `test_mode` | body | no | Defaults to **true** - validate and report, send nothing. Pass `false` to deliver. |
        **Note**

        - **Where your sends appear.** Every send is appended to a single
          per-organization log in your CRM, shown under Marketing as
          *API Sends*. The first call creates it; every call after that adds
          a row. `campaign_id` is that log and is the same on every response;
          `recipient_id` identifies this one message inside it.
        - **Each message is its own.** Unlike a marketing campaign, which
          sends one message to many people, every call here carries its own
          subject and body and they are stored per message.
        - **`test_mode` defaults to true.** Omitting it validates and reports;
          it does not send. This is deliberate - the field is absent far more
          often by accident than on purpose.
        - **`Idempotency-Key` is required.** A send is irreversible, and a
          retry after a timeout is the usual way a recipient gets the same
          message twice. Reuse the key on a retry; use a new one per message.
        - **What is tracked, and for how long.** Delivery, opens, clicks and
          bounces are recorded against `recipient_id` and kept permanently. The
          **message body is kept for 30 days** and then removed; the delivery
          record and all of its tracking survive.
        - **An unsubscribe footer is appended** to every message sent through
          this endpoint.
        - **No email signature is appended.** A CRM signature belongs to the
          person who wrote it - the Settings screen that holds them says "only
          you can see and change these" - and an API key is not a person, which
          is the same reason a personal from-address is never usable here. Put
          whatever footer you want in `body_html`; it is yours to compose.
        - **Opted-out recipients are refused**, including anyone who previously
          unsubscribed or hard-bounced. This is not overridable.
        - **Tighter rate limit than the rest of the API:** 5 requests per
          minute and 500 per day, rather than the general 100 per 10 seconds.
        - Each send counts against both your API call quota and your email
          allowance.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | A field is missing or malformed. | `errors` names the field. |
        | `IDEMPOTENCY_KEY_REQUIRED` | 400 | No `Idempotency-Key` header. | Send one. |
        | `UNAUTHORIZED` | 401 | Token missing, malformed or revoked. | Check the `Authorization` header. |
        | `MISSING_SCOPE` | 403 | The key lacks `email.messages.send`. | Re-issue the key with that scope. |
        | `IDEMPOTENCY_KEY_CONFLICT` | 409 | Same key reused with a different body. | Use a fresh key for a new message. |
        | `SEND_NOT_ALLOWED` | 422 | The from address is unknown, disabled, personal or not trackable; or the recipient has opted out. | The message says which. Check `GET /email/from-addresses`. |
        | `RATE_LIMITED` | 429 | 5/minute or 500/day exceeded. | Wait `Retry-After` seconds. |
        | `SEND_FAILED` | 502 | The provider refused the message. | The message carries the provider's reason. Safe to retry with the same key. |

      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequired'

      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from_account_id, to, subject, body_html]
              properties:
                from_account_id:
                  type: string
                  maxLength: 64
                  description: An id from GET /email/from-addresses. Must be trackable.
                to:
                  type: string
                  format: email
                  maxLength: 320
                  description: One recipient address.
                subject:
                  type: string
                  maxLength: 998
                  description: Subject line.
                body_html:
                  type: string
                  maxLength: 256000
                  description: HTML body. Maximum 256,000 bytes.
                body_text:
                  type: string
                  maxLength: 256000
                  description: Plain-text alternative. Derived from the HTML when omitted.
                test_mode:
                  type: boolean
                  default: true
                  description: >-
                    Defaults to TRUE. Validates and reports what would be sent
                    without sending or storing anything. Pass false to deliver.
            example:
              from_account_id: '6a1d971c81fd34ecd50b8c63'
              to: ada@example.com
              subject: Your receipt
              body_html: '<p>Thanks for your order.</p>'
              test_mode: true

      responses:
        '200':
          description: >-
            Validated (test_mode true) or sent (test_mode false). Read
            dispatched to tell which.
          content:
            application/json:
              examples:
                dryRun:
                  summary: "test_mode: true - validated, nothing sent or stored"
                  value:
                    status: success
                    message: Validated. Nothing was sent or stored.
                    data:
                      test_mode: true
                      dispatched: false
                      would_send:
                        from_account_id: 6a1d971c81fd34ecd50b8c63
                        from: Support <support@yourcompany.com>
                        reply_to: support@yourcompany.com
                        to: ada@example.com
                        subject: Your receipt
                        body_bytes: 29
                        sending_server: AiTrillion
                sent:
                  summary: "test_mode: false - the message is on its way"
                  value:
                    status: success
                    message: Email sent successfully
                    data:
                      test_mode: false
                      dispatched: true
                      campaign_id: 6b2f81a4c5d6e7f8a9b0c1d2
                      recipient_id: 6b2f81a4c5d6e7f8a9b0c1d3
                      status: sent
                      to: ada@example.com
                      sg_message_id: z-8K3EwuTaOxY3nCAEl-wg
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      test_mode:
                        type: boolean
                        description: Whether this was a dry run.
                      dispatched:
                        type: boolean
                        description: True only when a message was actually handed to the provider.
                      campaign_id:
                        type: string
                        description: >-
                          Present when dispatched. The send log this message was
                          appended to. The same value comes back on every send
                          from your organization.
                      recipient_id:
                        type: string
                        description: >-
                          Present when dispatched. Identifies THIS message
                          inside the log - it is what every tracking event for
                          it is recorded against. Keep it if you want to
                          correlate opens and clicks later.
                      status:
                        type: string
                        description: The message's delivery status at the moment it was accepted.
                      to:
                        type: string
                        description: The recipient.
                      sg_message_id:
                        type: [string, 'null']
                        description: The provider's own id, for support queries.
                      would_send:
                        type: object
                        description: Present on a dry run - what the message would have been.
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422':
          description: >-
            The send was refused before anything left - an unusable from
            address, or a recipient who has opted out.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: This address sends over its own SMTP server, so delivery, open and click tracking are not available for it. Choose an address whose sending server is the CRM.
                category: SEND_NOT_ALLOWED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }
        '502':
          description: The provider refused the message. Nothing was delivered.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: The email could not be sent.
                category: SEND_FAILED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors

  /contact/email/send:
    post:
      operationId: sendTransactionalEmail
      tags: [Email]
      summary: Send Email (like SMTP)
      description: |
        **Purpose**

        Use this the way you would use an SMTP server. You give it a from
        address, a `to`, a subject and a body, and it sends the mail. If you
        have ever configured SMTP in an app, you already know this endpoint.

        Nothing is written to your CRM - no contact is created, no record is
        touched, no timeline entry appears. `cc` and `bcc` work as they do
        anywhere else. It is for receipts, one-time codes, invoices and
        notifications: mail whose job is to arrive rather than to be measured.

        > **This can deliver real mail.** `test_mode` defaults to **true**,
        > which validates everything and sends nothing. You must pass
        > `"test_mode": false` to actually deliver.

        **Despite the path, no contact is involved.** `POST /email/send` is
        the endpoint that finds or creates one. This endpoint deliberately
        does not. The two names suggest the opposite of what they do, so
        check which one you want before wiring it in.
        **Scope**

        `email.transactional.send`

        Its own scope, separate from `email.messages.send`. A key that can
        already send through `/campaign/send` cannot call this endpoint until
        this scope is ticked as well - carbon copies reach people your CRM
        holds no record of, so granting that is a deliberate act rather than
        something an existing key inherited.
        **Parameters**

        | Name | In | Required | Description |
        |---|---|---|---|
        | `from` | body | yes\* | The address to send from, e.g. `billing@yourdomain.com`. Must be one your organization has verified. |
        | `from_account_id` | body | yes\* | An `id` from `GET /email/from-addresses` - the older way of naming the same address. |
        | `to` | body | yes | The primary recipient. |
        | `cc` | body | no | One address, or an array of them. Visible to every recipient. |
        | `bcc` | body | no | One address, or an array of them. Hidden from the others. |
        | `reply_to` | body | no | Overrides the from-address's own reply-to. |
        | `subject` | body | yes | Subject line. |
        | `body_text` | body | yes | Plain-text body, up to 256,000 bytes. |
        | `test_mode` | body | no | Defaults to **true** - validate and report, send nothing. Pass `false` to deliver. |

        \* **Send exactly one of `from` or `from_account_id`.** Sending
        neither, or both, is a `VALIDATION_ERROR`. `from` is the one to
        reach for: it reads like any SMTP configuration and needs no
        lookup first. `from_account_id` still works and is unchanged, so
        nothing already calling this endpoint has to be touched.

        **`from` has to be an address your organization has verified** -
        one that appears in `GET /email/from-addresses`. This is not a
        rule of ours: mail sent from a domain the sending infrastructure
        has not authenticated is refused outright or filed as spam, so an
        unverified address could not be delivered whatever we did with
        it. Every transactional email API works this way. If the address
        is not recognised you get a `SEND_NOT_ALLOWED` naming the ones
        that would have worked.

        `body_html` is **rejected, not ignored**. This endpoint sends a
        text-only message, and accepting an HTML body only to drop it would
        leave you certain you had sent formatting nobody received. Use
        `POST /campaign/send` for an HTML message.
        **Note**

        - **Opens and clicks are not tracked here.** Open tracking works by
          embedding an invisible pixel in an HTML body, and this endpoint
          sends no HTML at all - so there is nowhere to put one. Delivery,
          bounces and failures are tracked exactly as everywhere else; the
          **Opened** and **Clicked** columns simply never fill for these
          messages. Every response says so in its `tracking` object, so you
          do not have to remember it.
        - **One credit per call, however many people you reach.** A message
          with one `to` and three `cc` costs exactly what one with no copies
          costs. What limits your reach is the ceiling below, not the price.
        - **At most 50 addresses** across `to`, `cc` and `bcc` together.
        - **Duplicates are removed, not refused.** An address already in `to`
          is dropped from `cc` and `bcc`; one in both `cc` and `bcc` keeps its
          `cc` place. The response lists `cc` and `bcc` exactly as sent, so
          you can see what was actually done.
        - **Every recipient is checked, not just `to`.** Anyone who has
          unsubscribed or hard-bounced is refused from the `cc` line too - a
          bounced address costs your sending reputation wherever it sits.
        - **No unsubscribe footer is appended.** This is not marketing mail,
          and an unsubscribe link on an invoice teaches people to opt out of
          their own receipts. The opt-out check above still applies.
        - **No contact is created, matched or modified.**
        - **No email signature is appended.** A CRM signature belongs to the
          person who wrote it, and a key is not a person. Put whatever footer
          you want in `body_text`.
        - **15 requests per hour, per key** - the tightest limit in this API,
          because one call can reach fifty inboxes.
        - **`Idempotency-Key` is required.** A send is irreversible, and a
          retry after a timeout is the usual way someone gets the same message
          twice. Reuse the key on a retry; use a new one per message.
        - **Where your sends appear.** Each one is appended to the same
          per-organization log as `/campaign/send`, and listed in the CRM
          under **Marketing → API Email** with its delivery status.
          `campaign_id` is that log; `recipient_id` identifies this message
          inside it.
        - **Bodies are removed after 30 days.** The row, its subject and its
          whole delivery history are kept indefinitely - only the message
          text is cleared, and the screen says so rather than showing you an
          empty frame. Counts are never reduced.
        - Each send counts against both your API call quota and your email
          allowance.

        **Possible Errors**

        | Code | HTTP | Description | Resolution |
        |---|---|---|---|
        | `VALIDATION_ERROR` | 400 | A field is missing or malformed, or `body_html` was sent. | `errors` names the field. |
        | `IDEMPOTENCY_KEY_REQUIRED` | 400 | No `Idempotency-Key` header. | Send one. |
        | `UNAUTHORIZED` | 401 | Token missing, malformed or revoked. | Check the `Authorization` header. |
        | `MISSING_SCOPE` | 403 | The key lacks `email.transactional.send`. | Re-issue the key with that scope ticked. Holding `email.messages.send` is not enough. |
        | `IDEMPOTENCY_KEY_CONFLICT` | 409 | Same key reused with a different body. | Use a fresh key for a new message. |
        | `SEND_NOT_ALLOWED` | 422 | A `from` the organization has not verified; a from address that is personal, disabled or sends over its own SMTP; a recipient or copied address that has opted out; or more than 50 addresses. | The message says which, and an unverified `from` is answered with the addresses that would work. |
        | `RATE_LIMITED` | 429 | 15/hour or 360/day exceeded. | Wait `Retry-After` seconds. |
        | `SEND_FAILED` | 502 | The provider refused the message. | The message carries the reason. Safe to retry with the same key. |

      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequired'

      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              # `from` and `from_account_id` are each optional on their own
              # and exactly one is required - a constraint JSON Schema can
              # only express as a oneOf, which renders as an unreadable pair
              # of alternative bodies. Stated in the descriptions and in the
              # endpoint text instead; the API enforces it either way.
              required: [to, subject, body_text]
              properties:
                from:
                  type: string
                  format: email
                  maxLength: 320
                  description: >-
                    The address to send from, e.g. billing@yourdomain.com.
                    Must be one your organization has verified - the same
                    set GET /email/from-addresses returns. Send this OR
                    from_account_id, not both.
                from_account_id:
                  type: string
                  maxLength: 64
                  description: >-
                    An id from GET /email/from-addresses, naming the same
                    address `from` would. Must be trackable. Send this OR
                    from, not both.
                to:
                  type: string
                  format: email
                  maxLength: 320
                  description: The primary recipient.
                cc:
                  oneOf:
                    - type: string
                      format: email
                    - type: array
                      items: { type: string, format: email }
                  description: >-
                    Visible copies. One address or an array. Anything already
                    in `to` is dropped rather than refused.
                bcc:
                  oneOf:
                    - type: string
                      format: email
                    - type: array
                      items: { type: string, format: email }
                  description: >-
                    Blind copies. One address or an array. Anything already in
                    `to` or `cc` is dropped.
                reply_to:
                  type: string
                  format: email
                  maxLength: 320
                  description: Overrides the from-address's own reply-to.
                subject:
                  type: string
                  maxLength: 998
                  description: Subject line.
                body_text:
                  type: string
                  maxLength: 256000
                  description: >-
                    Plain-text body, up to 256,000 bytes. There is no HTML
                    counterpart on this endpoint, which is why opens cannot be
                    tracked for these messages.
                test_mode:
                  type: boolean
                  default: true
                  description: >-
                    Defaults to TRUE. Validates and reports what would be sent
                    without sending or storing anything. Pass false to deliver.
            example:
              from: billing@yourdomain.com
              to: ada@example.com
              cc: [finance@example.com]
              subject: Your invoice INV-1042
              body_text: |-
                Hi Ada,

                Your invoice INV-1042 is ready. The total is 4,200 INR.

                Thanks,
                Accounts
              test_mode: true

      responses:
        '200':
          description: >-
            Validated (test_mode true) or sent (test_mode false). Read
            dispatched to tell which.
          content:
            application/json:
              examples:
                dryRun:
                  summary: "test_mode: true - validated, nothing sent or stored"
                  value:
                    status: success
                    message: Validated. Nothing was sent or stored.
                    data:
                      test_mode: true
                      dispatched: false
                      would_send:
                        from_account_id: 6a1d971c81fd34ecd50b8c63
                        from: Accounts <accounts@yourcompany.com>
                        reply_to: accounts@yourcompany.com
                        to: ada@example.com
                        cc: [finance@example.com]
                        bcc: []
                        recipient_count: 2
                        subject: Your invoice INV-1042
                        body_bytes: 96
                        sending_server: AiTrillion
                        tracking: { opens: false, clicks: false, delivery: true }
                        credits: 1
                sent:
                  summary: "test_mode: false - the message is on its way"
                  value:
                    status: success
                    message: Email sent successfully
                    data:
                      test_mode: false
                      dispatched: true
                      campaign_id: 6b2f81a4c5d6e7f8a9b0c1d2
                      recipient_id: 6b2f81a4c5d6e7f8a9b0c1d3
                      status: sent
                      to: ada@example.com
                      cc: [finance@example.com]
                      bcc: []
                      sg_message_id: z-8K3EwuTaOxY3nCAEl-wg
                      tracking: { opens: false, clicks: false, delivery: true }
                      credits: 1
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      test_mode:
                        type: boolean
                        description: Whether this was a dry run.
                      dispatched:
                        type: boolean
                        description: True only when a message was actually handed to the provider.
                      campaign_id:
                        type: string
                        description: >-
                          Present when dispatched. The send log this message
                          was appended to - the same value on every send from
                          your organization.
                      recipient_id:
                        type: string
                        description: >-
                          Present when dispatched. Identifies THIS message
                          inside the log, and is what its delivery and bounce
                          events are recorded against.
                      status:
                        type: string
                        description: The message's delivery status at the moment it was accepted.
                      to:
                        type: string
                        description: The primary recipient.
                      cc:
                        type: array
                        items: { type: string }
                        description: >-
                          The visible copies AS SENT, after anything already in
                          `to` was removed. Compare it with what you posted to
                          see what was dropped.
                      bcc:
                        type: array
                        items: { type: string }
                        description: The blind copies as sent.
                      sg_message_id:
                        type: [string, 'null']
                        description: The provider's own id, for support queries.
                      tracking:
                        type: object
                        description: >-
                          What is and is not recorded for this message. `opens`
                          and `clicks` are always false here: a text-only mail
                          carries no pixel and no rewritten links. `delivery`
                          is true, so Delivered and Bounced still work.
                        properties:
                          opens: { type: boolean }
                          clicks: { type: boolean }
                          delivery: { type: boolean }
                      credits:
                        type: integer
                        description: >-
                          Always 1. Carbon copies do not each cost a credit.
                      would_send:
                        type: object
                        description: Present on a dry run - what the message would have been.
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422':
          description: >-
            Refused before anything left - an unusable from address, a
            recipient or copied address that may not be mailed, or too many
            addresses on one message.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: "finance@example.com cannot be copied on this message: this address hard bounced."
                category: SEND_NOT_ALLOWED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }
        '502':
          description: The provider refused the message. Nothing was delivered.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: The email could not be sent.
                category: SEND_FAILED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors

  /whatsapp/templates:
    get:
      operationId: listWhatsappTemplates
      tags: [WhatsApp]
      summary: List Templates
      description: |
        **Purpose**

        Every WhatsApp template your organization has had **approved**, and
        the placeholders each one expects. Call this first: sending needs a
        template id, and the ids are opaque.

        Only `approved` templates come back. Draft, pending, rejected and
        paused ones are invisible to an API key, so a template you can see in
        the dashboard but not here is a status problem, not a key problem.
        **Scope**

        `whatsapp.templates.read`

        Org-wide. Granted to a key whose creating user has the **WhatsApp**
        feature permission.

        **Reading `placeholders`**

        A template's placeholders arrive in one of two shapes, depending on
        how the template was built:

        | Shape | Looks like | Means |
        |---|---|---|
        | Object | `{"1": "first_name", "2": "order_number"}` | position → the field that fills it |
        | Array | `["first_name", "order_number"]` | the same, already in order |

        Either way it is the ORDER that matters. When you send you pass an
        array of **values** in that order - never the field names back.
        **Parameters**

        None.
      responses:
        '200':
          description: Every approved template, ordered by name.
          content:
            application/json:
              example:
                status: success
                message: Templates retrieved
                data:
                  - id: '6ae06ed29fe2c3647a017c74'
                    name: order_shipped
                    provider_name: order_shipped_17930933304259302
                    category: marketing
                    language: en
                    template_type: standard
                    supports_send: true
                    body: 'Hi {{1}}, order {{2}} is on its way.'
                    placeholders:
                      '1': first_name
                      '2': order_number
                    sender_id: '66f0a1b2c3d4e5f6a7b8c9d0'
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/WhatsappTemplate' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '429': { $ref: '#/components/responses/RateLimited' }

  /whatsapp/templates/{id}:
    get:
      operationId: getWhatsappTemplate
      tags: [WhatsApp]
      summary: Get Template
      description: |
        **Purpose**

        One approved template by id, in exactly the shape the list returns -
        so one decoder handles both.
        **Scope**

        `whatsapp.templates.read`

        **A 404 here means one of two things**

        Either no template has that id in your organization, or it has one and
        it is not `approved`. The API deliberately does not tell you which: a
        key cannot be used to probe which ids exist.
        **Parameters**

        | Name | In | Required | Description |
        |---|---|---|---|
        | `id` | path | yes | The template id, from List Templates. |
      parameters:
        - name: id
          in: path
          required: true
          description: The template's `id`, as List Templates returns it.
          schema: { type: string }
          example: '6ae06ed29fe2c3647a017c74'
      responses:
        '200':
          description: The template.
          content:
            application/json:
              example:
                status: success
                message: Template retrieved
                data:
                  id: '6ae06ed29fe2c3647a017c74'
                  name: order_shipped
                  provider_name: order_shipped_17930933304259302
                  category: marketing
                  language: en
                  template_type: standard
                  supports_send: true
                  body: 'Hi {{1}}, order {{2}} is on its way.'
                  placeholders:
                    '1': first_name
                    '2': order_number
                  sender_id: '66f0a1b2c3d4e5f6a7b8c9d0'
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data: { $ref: '#/components/schemas/WhatsappTemplate' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '404':
          description: No approved template with that id in this organization.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Template not found or not approved.
                category: TEMPLATE_NOT_FOUND
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }

  /whatsapp/templates/{id}/send:
    post:
      operationId: sendWhatsappTemplate
      tags: [WhatsApp]
      summary: Send Template
      description: |
        **Purpose**

        Send one approved template to one phone number.

        > **This delivers real messages and spends WhatsApp credits.** There
        > is no `test_mode` on this endpoint, and no dry run. Every accepted
        > call reaches the recipient.
        **Scope**

        `whatsapp.templates.send`

        Org-wide. Granted to a key whose creating user has the **WhatsApp**
        feature permission.

        **Retries are NOT protected**

        Unlike `POST /campaign/send`, this endpoint does not accept an
        `Idempotency-Key`, so a retry after a timeout sends the message a
        second time and spends a second credit. If you cannot tell whether a
        call arrived, check the WhatsApp send log before trying again rather
        than retrying blind.

        **The phone number**

        Everything that is not a digit is stripped, so `+91 98765 43210` and
        `919876543210` are the same number. What remains must be at least 10
        digits, and it must carry the country code - there is no default
        country.

        **Placeholders**

        `placeholders` is an array of the **values** that fill the template's
        `{{1}}`, `{{2}}`, … in order. Read that order from `placeholders` on
        the template itself (List Templates explains both shapes it takes).
        A template with a media or text header also accepts
        `header_placeholder`.

        **Which number it is sent from**

        A template is registered under one WhatsApp sender, and that sender is
        authoritative: when the template carries a `sender_id`, omit
        `sender_id` here or pass the same one. Passing a different one is
        refused with `SENDER_MISMATCH` rather than sent and rejected by the
        provider. Only for an older template with no bound sender does
        `sender_id` choose between the senders of a multi-sender organization,
        and omitting it there falls back to the organization default.

        **Before it sends, four gates run in order**

        1. the opt-in / unsubscribe rules for this template and sender
        2. a price estimate for this destination
        3. your WhatsApp credit balance
        4. the deduction, and only then the provider call

        A failure at any gate returns before the message leaves, and nothing
        is charged.
        **Parameters**

        | Name | In | Required | Description |
        |---|---|---|---|
        | `id` | path | yes | The template to send, from List Templates. |
        | `phone` | body | yes | Recipient with country code. Non-digits are stripped; 10 digits must remain. |
        | `template_language` | body | no | Language code. Defaults to the template's own. |
        | `placeholders` | body | no | The values for `{{1}}`, `{{2}}`, … in order. |
        | `header_placeholder` | body | no | The value for a media or text header, when the template has one. |
        | `sender_id` | body | no | Only for a template bound to no sender. |
      parameters:
        - name: id
          in: path
          required: true
          description: The template to send, as List Templates returns it.
          schema: { type: string }
          example: '6ae06ed29fe2c3647a017c74'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone]
              properties:
                phone:
                  type: string
                  minLength: 6
                  maxLength: 32
                  description: >-
                    The recipient, with country code. Non-digits are stripped;
                    at least 10 digits must remain.
                  example: '91XXXXXXXXXX'
                template_language:
                  type: string
                  maxLength: 10
                  description: Language code to send in. Defaults to the template's own.
                  example: en
                placeholders:
                  type: array
                  items: { type: string }
                  description: >-
                    The values for `{{1}}`, `{{2}}`, … in order. Values, not
                    field names.
                  example: ['Ada', 'A-1043']
                header_placeholder:
                  type: string
                  maxLength: 2000
                  description: >-
                    The value for a media or text header, when the template
                    has one.
                sender_id:
                  type: string
                  maxLength: 64
                  description: >-
                    Optional. Only meaningful for a template with no bound
                    sender. `waba_id` is never accepted - it is derived.
            example:
              phone: '91XXXXXXXXXX'
              template_language: en
              placeholders: ['Ada', 'A-1043']
      responses:
        '200':
          description: Accepted by the provider and on its way.
          content:
            application/json:
              example:
                status: success
                message: Message sent
                data:
                  id: '3f8a21b0-7c4d-4e2a-9b11-5d6e7f8a9b0c'
                  sent_credits: 0.0825
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                        description: >-
                          The provider's message id. Quote it in a support
                          query, and expect it on this message's delivery
                          events.
                      sent_credits:
                        type: number
                        description: >-
                          WhatsApp credits this message cost. 0 when the
                          organization is not on credit billing.
        '400':
          description: >-
            The payload is invalid (`VALIDATION_ERROR`), or the phone number
            has fewer than 10 digits once stripped (`INVALID_PHONE`).
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Invalid phone number.
                category: INVALID_PHONE
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '401': { $ref: '#/components/responses/Unauthorized' }
        '402':
          description: Not enough WhatsApp credits. Nothing was sent or charged.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Insufficient WhatsApp credits.
                category: INSUFFICIENT_CREDITS
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '403': { $ref: '#/components/responses/MissingScope' }
        '404':
          description: No approved template with that id in this organization.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Template not found or not approved.
                category: TEMPLATE_NOT_FOUND
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '422':
          description: >-
            A gate refused the send, and nothing was charged. `SENDER_MISMATCH`
            - `sender_id` contradicts the template's bound sender.
            `SENDER_REQUIRED` - the organization has several senders and the
            template is bound to none, so one must be named.
            `PROVIDER_NOT_CONFIGURED` - no usable WhatsApp sender.
            `OPT_IN_REQUIRED` - this recipient has not opted in, or has
            unsubscribed. `RATE_LOOKUP_FAILED` - the price for this
            destination could not be determined.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: This recipient has not opted in to receive messages.
                category: OPT_IN_REQUIRED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }
        '500':
          description: >-
            The send failed unexpectedly. Quote `correlationId` — EXCEPT when
            the message reads `Token creator user no longer exists`, which you
            can fix yourself: the user who created this key has been deleted,
            and a key needs an author to create or update a contact with.
            Revoke the key and generate a new one.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Could not send the message.
                category: INTERNAL_ERROR
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '502':
          description: The provider refused the message. Nothing was delivered.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: The message could not be sent.
                category: PROVIDER_ERROR
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors

  /email/send:
    post:
      operationId: sendEmail
      tags: [Email]
      summary: Send Email to a Contact
      description: |
        **Purpose**

        Send one email to a PERSON, and leave it on their record.

        This is the difference from `POST /campaign/send`, and the only reason
        both exist. That endpoint takes an address, delivers, and logs the
        result; nothing is attached to anybody, so opening the person in the
        CRM shows no sign of it. This one finds the contact behind the address
        — creating it when there is none — and writes the message to their
        timeline, exactly where a mail typed into the CRM would appear. The
        reply that comes back tomorrow has somewhere to land.

        Reach for `/campaign/send` when you are sending to an address and only
        want it tracked. Reach for this when the recipient is someone your CRM
        should know.

        > **This can deliver real mail.** `test_mode` defaults to **true**,
        > which validates everything, reports what it would do, and changes
        > nothing — **no message, and no contact**. You must pass
        > `"test_mode": false` to actually send. Pressing **Send** on this page
        > with the default body is safe.
        **Scope**

        `email.messages.send`

        The same scope `/campaign/send` uses: both send one email from an
        organization address, so a key granted that may do either.

        **The contact**

        The address in `to` is looked up, and what happens next comes back in
        `contact_action`:

        | `contact_action` | What happened |
        |---|---|
        | `matched` | They were already in the CRM, and nothing about them changed. |
        | `updated` | They were already there, and the fields you sent in `contact` were written. Fields you did not send are untouched. |
        | `created` | They were not there, so a contact was made. |
        | `unavailable` | There was nothing to attach to — the organization has no Contacts module. The mail is still sent. |

        When several contacts share the address, the **oldest** is used. That
        is not arbitrary: every part of this CRM that resolves a person from an
        address does the same, so a send, a conversation and a ticket all land
        on one record rather than scattering across duplicates.

        **Creating one needs a name, and a send has none**

        `first_name` is required on the Contacts module, so a contact created
        from nothing but an address would be refused. The local part is used
        instead — `ada@example.com` becomes `ada`. Send a `contact` object to
        do better; anything you put there wins over the derived value.
        **Parameters**

        | Name | In | Required | Description |
        |---|---|---|---|
        | `from_account_id` | body | yes | An organization address, from `GET /email/from-addresses`. |
        | `to` | body | yes | The recipient. This is also what identifies the contact. |
        | `subject` | body | yes | Subject line. Merge fields resolve against the contact. |
        | `body_html` | body | yes | HTML body. Merge fields resolve here too. |
        | `body_text` | body | no | Plain-text alternative. Derived from the HTML when omitted. |
        | `contact` | body | no | Contact fields to create the record with, or update it with. |
        | `test_mode` | body | no | Defaults to **true** — validate and report, change nothing. Pass `false` to send. |

        **Merge fields**

        `{{contacts.first_name}}` in the subject or body is replaced with that
        contact's value before sending. The older `${Contacts.First Name}` form
        works too. A field that cannot be resolved is left as it is rather than
        failing the send.
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequired'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [from_account_id, to, subject, body_html]
              properties:
                from_account_id:
                  type: string
                  description: An organization address, from GET /email/from-addresses.
                  example: 6a1d971c81fd34ecd50b8c63
                to:
                  type: string
                  format: email
                  description: >-
                    The recipient, and the address the contact is identified
                    by.
                  example: ada@example.com
                subject:
                  type: string
                  maxLength: 998
                  description: Subject line. Merge fields resolve against the contact.
                body_html:
                  type: string
                  description: HTML body. Merge fields resolve here too.
                body_text:
                  type: string
                  description: Plain-text alternative. Derived from the HTML when omitted.
                contact:
                  type: object
                  additionalProperties: true
                  description: >-
                    Contact fields to create the record with, or update it
                    with. An update writes only what you send here.
                  example:
                    first_name: Ada
                    last_name: Lovelace
                test_mode:
                  type: boolean
                  default: true
                  description: >-
                    Defaults to true. A dry run validates, reports, and changes
                    nothing - no message and no contact.
            example:
              from_account_id: 6a1d971c81fd34ecd50b8c63
              to: ada@example.com
              subject: 'Hi {{contacts.first_name}}, your order shipped'
              body_html: '<p>It is on its way.</p>'
              contact:
                first_name: Ada
                last_name: Lovelace
              test_mode: true
      responses:
        '200':
          description: >-
            Validated (test_mode true) or sent (test_mode false). Read
            dispatched to tell which.
          content:
            application/json:
              examples:
                dryRun:
                  summary: "test_mode: true - nothing sent, no contact touched"
                  value:
                    status: success
                    message: Validated. Nothing was sent, and no contact was created or changed.
                    data:
                      test_mode: true
                      dispatched: false
                      would_send:
                        from_account_id: 6a1d971c81fd34ecd50b8c63
                        from: Support <support@yourcompany.com>
                        to: ada@example.com
                        subject: Your order shipped
                        body_bytes: 29
                        sending_server: AiTrillion
                      contact:
                        contact_id: null
                        action: would_create
                sent:
                  summary: "test_mode: false - on its way, and the contact was created"
                  value:
                    status: success
                    message: Email sent successfully
                    data:
                      test_mode: false
                      dispatched: true
                      message_id: 6b2f81a4c5d6e7f8a9b0c1d2
                      status: sent
                      to: ada@example.com
                      contact_id: 6650f1a2b3c4d5e6f7a8b9c0
                      contact_action: created
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      test_mode:
                        type: boolean
                        description: Whether this was a dry run.
                      dispatched:
                        type: boolean
                        description: True only when a message was handed to the provider.
                      message_id:
                        type: string
                        description: >-
                          Present when dispatched. The row on the contact's
                          timeline; every tracking event for this send is
                          recorded against it.
                      status:
                        type: string
                        description: The message's state at the moment it was accepted.
                      to:
                        type: string
                        description: The recipient.
                      contact_id:
                        type: [string, 'null']
                        description: >-
                          The contact this message is attached to, or null when
                          there was nothing to attach to.
                      contact_action:
                        type: string
                        enum: [created, updated, matched, unavailable]
                        description: What happened to the contact.
        '400': { $ref: '#/components/responses/ValidationError' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/MissingScope' }
        '409': { $ref: '#/components/responses/Conflict' }
        '422':
          description: >-
            A gate refused the send and nothing was delivered: an unknown or
            disabled from-address, a personal one, an address that sends over
            its own SMTP (tracking would never report anything), an inactive
            contact, or a recipient who has opted out.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: An API key may only send from an Organization Email address.
                category: SEND_NOT_ALLOWED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }
        '502':
          description: The provider refused the message. Nothing was delivered.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: The email could not be sent.
                category: SEND_FAILED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors

  /whatsapp/send:
    post:
      operationId: sendWhatsappToContact
      tags: [WhatsApp]
      summary: Send WhatsApp to a Contact
      description: |
        **Purpose**

        Send an approved template to a PERSON, and leave it on their record.

        The message is the same one `POST /whatsapp/templates/{id}/send`
        delivers. What differs is what happens around it: the number is looked
        up in your CRM, a contact is created when it is new, and the send is
        written to that contact's timeline. Sending to a number the CRM has
        never seen used to leave nothing behind — the message went, and the
        person did not exist.

        Reach for the template endpoint when you are messaging a number.
        Reach for this when the recipient is someone your CRM should know.

        > **This delivers real messages and spends WhatsApp credits.** There is
        > no `test_mode` on either WhatsApp endpoint, and no dry run. Every
        > accepted call reaches the recipient.
        **Scope**

        `whatsapp.templates.send`

        The same scope the template endpoint uses: both send one approved
        template, so a key granted that may do either.

        **An Idempotency-Key is required here**

        Unlike the older template route, this endpoint refuses a request
        without one. A WhatsApp send cannot be recalled and spends a credit, so
        a retry after a timeout would deliver twice and charge twice. Use a
        fresh value per message and the SAME value when retrying one whose
        outcome you are unsure of.

        **The contact**

        The number is matched after non-digits are stripped, so `+91 98765
        43210` and `919876543210` are the same person. What happened comes back
        in `contact_action`:

        | `contact_action` | What happened |
        |---|---|
        | `matched` | They were already in the CRM, and nothing about them changed. |
        | `updated` | They were already there, and the fields you sent in `contact` were written. Fields you did not send are untouched. |
        | `created` | They were not there, so a contact was made. |
        | `unavailable` | There was nothing to attach to — the organization has no Contacts module. The message is still sent. |

        When several contacts share the number, the **oldest** is used, the same
        rule the rest of the CRM follows when it resolves a person.

        **The contact is resolved BEFORE the message is sent**

        So a send that is then refused — no credits, not opted in — still
        leaves the contact behind. That is intended: the person is real, you
        tried to reach them, and your next attempt finds the same record
        instead of making a second one.

        **Creating one needs a name, and a number is not one**

        `first_name` is required on the Contacts module, so the number stands in
        for it: a new contact is called `919876543210` until someone renames it.
        Send a `contact` object to do better; anything you put there wins.

        **The template fills itself in from the contact**

        A template records which contact field belongs in each numbered slot.
        `GET /whatsapp/templates` returns that as `placeholders`:

        ```json
        "placeholders": { "1": "first_name", "2": "order_number" }
        ```

        Because this endpoint is given a person rather than a number, it can
        read those fields off the contact itself. **Send no `placeholders` and
        the slots fill themselves.**

        ```bash
        -d '{"phone":"91XXXXXXXXXX","template_id":"6ae06ed29fe2c3647a017c74"}'
        ```

        Anything you DO send wins, slot by slot. Pass a value and it is used;
        leave one empty and the contact answers for it. So you can supply the
        one field the CRM cannot know and let it fill the rest:

        ```bash
        -d '{"phone":"91XXXXXXXXXX","template_id":"…","placeholders":["","A-1043"]}'
        ```

        The response says which slots it answered for, in `placeholders_from_contact`.
        A slot the contact has no value for is sent empty rather than as the
        literal `{{2}}` — a blank in a message is survivable, a stray token is not.

        Field names are matched without regard to case, a multi-select field is
        joined with commas, and a mapping written as a full merge tag
        (`contacts.first_name`) resolves through the same engine a campaign uses.
        This is the behaviour the CRM's own inbox already applies when it
        prefills a template, so a send from here and a send from there put the
        same value in the same slot.

        > Only this endpoint fills from a contact.
        > `POST /whatsapp/templates/{id}/send` is given a phone number and
        > nothing else, so it has no contact to read and sends exactly the
        > `placeholders` you pass it.
        **Parameters**

        | Name | In | Required | Description |
        |---|---|---|---|
        | `phone` | body | yes | Recipient with country code. Non-digits are stripped; 10 digits must remain. |
        | `template_id` | body | yes | The template to send, from `GET /whatsapp/templates`. |
        | `template_language` | body | no | Language code. Defaults to the template's own. |
        | `placeholders` | body | no | The values for `{{1}}`, `{{2}}`, … in order. **Omit it and they are taken from the contact**; any value you do send wins for that slot. |
        | `header_placeholder` | body | no | The value for a media or text header, when the template has one. |
        | `sender_id` | body | no | Only for a template bound to no sender. |
        | `contact` | body | no | Contact fields to create the record with, or update it with. |
      parameters:
        - $ref: '#/components/parameters/IdempotencyKeyRequired'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [phone, template_id]
              properties:
                phone:
                  type: string
                  minLength: 6
                  maxLength: 32
                  description: >-
                    The recipient, with country code. Non-digits are stripped;
                    at least 10 digits must remain.
                  example: '91XXXXXXXXXX'
                template_id:
                  type: string
                  maxLength: 64
                  description: The template to send, from List Templates.
                  example: '6ae06ed29fe2c3647a017c74'
                template_language:
                  type: string
                  maxLength: 10
                  description: Language code to send in. Defaults to the template's own.
                  example: en
                placeholders:
                  type: array
                  items: { type: string }
                  description: >-
                    The values for `{{1}}`, `{{2}}`, … in order. Omit this and
                    every slot is filled from the contact, using the template's
                    own placeholder mapping. A value you send always wins for
                    its slot; an empty one is filled for you.
                  example: ['', 'A-1043']
                header_placeholder:
                  type: string
                  maxLength: 2000
                  description: The value for a media or text header, when the template has one.
                sender_id:
                  type: string
                  maxLength: 64
                  description: Optional. Only meaningful for a template with no bound sender.
                contact:
                  type: object
                  additionalProperties: true
                  description: >-
                    Contact fields to create the record with, or update it
                    with. An update writes only what you send here.
                  example:
                    first_name: Ada
            example:
              phone: '91XXXXXXXXXX'
              template_id: '6ae06ed29fe2c3647a017c74'
              placeholders: ['Ada', 'A-1043']
              contact:
                first_name: Ada
      responses:
        '200':
          description: Accepted by the provider and on its way.
          content:
            application/json:
              example:
                status: success
                message: Message sent
                data:
                  id: '3f8a21b0-7c4d-4e2a-9b11-5d6e7f8a9b0c'
                  sent_credits: 0.0825
                  contact_id: '6650f1a2b3c4d5e6f7a8b9c0'
                  contact_action: created
              schema:
                type: object
                properties:
                  status: { type: string }
                  message: { type: string }
                  data:
                    type: object
                    properties:
                      id:
                        type: string
                        description: The provider's message id, for support queries.
                      sent_credits:
                        type: number
                        description: >-
                          WhatsApp credits this message cost. 0 when the
                          organization is not on credit billing.
                      contact_id:
                        type: [string, 'null']
                        description: >-
                          The contact this message is attached to, or null when
                          there was nothing to attach to.
                      contact_action:
                        type: string
                        enum: [created, updated, matched, unavailable]
                        description: What happened to the contact.
                      placeholders_from_contact:
                        type: array
                        items: { type: integer }
                        description: >-
                          The 1-based slots whose value came from the contact
                          rather than from your request. Empty when you supplied
                          them all, or when the contact had nothing to give.
                        example: [1, 2]
        '400':
          description: >-
            The payload is invalid (`VALIDATION_ERROR`), or the number has
            fewer than 10 digits once stripped (`INVALID_PHONE`). Both are
            refused before the contact step, so nothing is created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Invalid phone number.
                category: INVALID_PHONE
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '401': { $ref: '#/components/responses/Unauthorized' }
        '402':
          description: >-
            Not enough WhatsApp credits. Nothing was sent or charged — but the
            contact was already resolved, so it remains.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Insufficient WhatsApp credits.
                category: INSUFFICIENT_CREDITS
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '403': { $ref: '#/components/responses/MissingScope' }
        '404':
          description: >-
            No approved template with that `template_id` in this organization.
            Refused before the contact step.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Template not found or not approved.
                category: TEMPLATE_NOT_FOUND
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '409': { $ref: '#/components/responses/Conflict' }
        '422':
          description: >-
            A gate refused the send, and nothing was charged. The same set the
            template endpoint returns: `SENDER_MISMATCH`, `SENDER_REQUIRED`,
            `PROVIDER_NOT_CONFIGURED`, `OPT_IN_REQUIRED`, `RATE_LOOKUP_FAILED`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: This recipient has not opted in to receive messages.
                category: OPT_IN_REQUIRED
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '429': { $ref: '#/components/responses/RateLimited' }
        '500':
          description: >-
            The send failed unexpectedly. Quote `correlationId` — EXCEPT when
            the message reads `Token creator user no longer exists`, which you
            can fix yourself: the user who created this key has been deleted,
            and a key needs an author to create or update a contact with.
            Revoke the key and generate a new one.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: Could not send the message.
                category: INTERNAL_ERROR
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
        '502':
          description: The provider refused the message. Nothing was delivered.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                status: error
                message: The message could not be sent.
                category: PROVIDER_ERROR
                correlationId: 01J8ZQ9K3M4N5P6Q7R8S9T0V
                errors: []
                documentation_url: https://developer.aiengagecrm.com/#g-errors
