# LemuAI docs: developers
> The API reference, the LemuTickets API, SDKs, events, webhooks and the MCP server. LemuAI is a hosted product at https://app.lemuai.com. Menu paths in these pages use the app's sidebar names, joined with →. When you help someone, follow these pages; if they don't cover something, say so instead of guessing.
Page index: https://docs.lemuai.com/llms.txt
---
# API Trigger
> API Trigger helps you trigger your Voice Agent using external systems, like N8n or Zapier
URL: https://docs.lemuai.com/voice-agent/api-trigger
## API Payload
The API Trigger is a POST request, which requires an [API Key](https://docs.lemuai.com/configurations/api-keys). It expects a valid JSON with `phone_number` and `initial_context`.
## Initial Context
`initial_context` is a valid JSON object, which contains any contextual information that you would want your voice agent to access. You can refer to these values in your prompts using **Handle Bars**, which are values enclosed in `{{` and `}}`.
Example: If you have below JSON as your `initial_context`
```
{
"initial_context": {
"user": {
"name": "John"
}
}
}
```
you can refer to the user name in your prompts as `{{user.name}}`. The keys of `initial_context` are added to the call's context directly, so you don't prefix them with `initial_context`.
---
# Webhook
> Webhook node allow you to sync the result of Voice Agent runs to your external systems, like CRM or to other workflow orchestrator like Zapier or n8n.
URL: https://docs.lemuai.com/voice-agent/webhook
**Note:** You can have multiple Webhook Nodes for a single Voice Agent, if you want to sync the result of the call at multiple places.
## Creating the Webhook Payload
The payload can contain a valid JSON, and you can reference variables while constructing that payload. You can reference below variables while constructing the payload.
- `{{workflow_run_id}}` Unique ID of the Agent run
- `{{workflow_id}}` ID of the Agent
- `{{workflow_name}}` Name of the workflow
- `{{initial_context.*}}` [Initial context variables](https://docs.lemuai.com/core-concepts/context-and-variables#initialcontext)
- `{{gathered_context.*}}` [Extracted variables](https://docs.lemuai.com/core-concepts/context-and-variables#gatheredcontext)
- `{{cost_info.call_duration_seconds}}` Call duration
- `{{recording_url}}` Call recording URL
- `{{transcript_url}}` Transcript URL
An example of the payload is given below
```
{
"call_id": "{{workflow_run_id}}",
"first_name": "{{initial_context.first_name}}",
"rsvp": "{{gathered_context.rsvp}}",
"duration": "{{cost_info.call_duration_seconds}}",
"recording_url": "{{recording_url}}",
"transcript_url": "{{transcript_url}}"
}
```
---
# HTTP API
> Create REST API tools that your AI agent can invoke during conversations to integrate with external systems.
URL: https://docs.lemuai.com/voice-agent/tools/http-api
HTTP API tools allow you to attach extrernal REST API calls directly to workflow nodes, enabling your voice agents to call any internal or external system during live conversations based on LLM judgment and your prompts. This works similar to function calling on any agentic platform and is fully customizable.
## What is an HTTP API Tool?
An HTTP API Tool is a REST API definition that the LLM can invoke at runtime.
**Typical use cases:**
- Call your own backend endpoints
- Trigger n8n automations
- Sync data with a CRM
- Fetch data from external APIs (weather, pricing, availability, etc.)
- Write/update/read data using Rest API
**The LLM decides:**
- which tool to call
- when to call it
- what parameters to send
**All based on:**
- Your prompts: node-level instructions in simple english (or any language)
- Tool name
- Tool description
- Parameter definitions
## Defining an HTTP API Tool
### 1. Tool Name
- Must be clear and action-oriented.
- **Examples:** `capture_lead_interest`, `fetch_weather`, 'create_crm_contact', etc
### 2. Tool Description
- Extremely important
- This is how the LLM decides **when** to use the tool.
- Write it in plain, explicit English.
**Bad:**
"API to capture data"
**Good:**
"This tool is to capture interest. Use this tool when the user clearly expresses interest in the product or wants to be contacted"

### 3. Endpoint Configuration
- Full URL (**must include `http://` or `https://`**)
- Supports **REST** methods
**Note:** Common mistake: forgetting https:// in the URL.
### 4. Authentication & Headers
- Add custom authentication
- Add custom headers
- Works with internal services and third-party APIs
### 5. Parameters
Each parameter must have:
- Name
- Type
- Description
- Required/Optional flag
**Parameter descriptions matter more than types.**
Guidelines:
- Start with string parameters when possible
- Be explicit in what the value represents
- Mark only truly mandatory fields as required
Example:
- interest (string):
"Set to true if the user clearly shows intent to buy or wants follow-up. Otherwise false."

## Attaching Tools to Workflow Nodes
- You can attach **multiple tools to a single node**
- All the tools that you have created will be available for selection in the node
- Tools are only callable when attached to that node
- The LLM will choose which one to call
Inside the node, guide the LLM using **simple English instructions**.
Example:
"If the user shows interest in speaking to sales or wants a callback, immediately call the capture_lead_interest tool and set interest to true."
This instruction is often the deciding factor for correct tool usage.
This instruction is often the **deciding factor** for correct tool usage.

## Tool Invocation Logic (How the LLM Thinks)
The LLM considers:
- User's spoken intent
- Node prompt instructions
- Tool name and description
- Parameter descriptions
If these align clearly, the tool is called automatically.
Poor naming or vague descriptions lead to:
- Missed tool calls
- Wrong parameters
- Hallucinated values
## Key Best Practices
- Name tools clearly
- Write detailed, action-based descriptions
- Keep parameters simple at first
- Always include http/https in URLs
- Use plain English in node instructions
- Attach only relevant tools to each node
**Well-defined tools + clear prompts = reliable, production-grade voice agents.**
---
# AI Assistants (MCP)
> Let AI assistants like Claude and Cursor use your Lemu AI voice agents through the Model Context Protocol
URL: https://docs.lemuai.com/mcp/overview
Lemu AI runs a remote [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server. Once you connect an AI assistant to it, the assistant can look up your voice agents, request phone calls with them, and read how those calls went, all from a normal chat.
**Server address:**
```text
https://mcp.lemuai.com/mcp
```
It uses the standard streamable HTTP transport, so any MCP client that supports remote servers with OAuth can connect.
## What an assistant can do
| You ask the assistant to... | It uses |
|---|---|
| See which agents it may use and what details a call needs | `list_agents`, `get_agent` |
| Place a call with one of those agents | `start_call` |
| Check the status and outcome of its calls | `get_call`, `list_calls` |
| Cancel a call that hasn't been dialed yet | `cancel_call` |
| Draft a new voice agent from a short brief | `create_agent_draft`, `update_agent_draft`, `test_agent`, `archive_agent` |
See [Tools](https://docs.lemuai.com/mcp/tools) for the full list and what each tool accepts.
## How it's kept safe
An assistant never gets more access than a person in your organization gives it:
- **An admin approves every connection.** When an assistant connects, you're sent to a Lemu AI consent screen. Only someone with admin rights in the organization can approve it.
- **You choose the permissions.** Each connection gets only the permissions ticked on the consent screen, such as reading agents or requesting calls.
- **You choose the agents.** For calls, you pick exactly which agents the assistant may use. Agents you create later are not added automatically.
- **Daily limits.** Each connection has a cap on calls per day (at most 200), plus limits on concurrent and pending calls.
- **A person confirms every call.** Calls an assistant requests wait for confirmation by someone in your organization before anything is dialed.
- **Your calling policy always applies.** Who may be called, local calling hours, the do-not-call list and the AI disclosure are enforced by Lemu AI, whatever the assistant sends.
- **Everything is logged.** Every request is recorded in an audit log.
Anything a person says on a call is returned to the assistant as data, never as an instruction.
See [Permissions & limits](https://docs.lemuai.com/mcp/permissions) for the details.
## Next steps
- [Connect an assistant](https://docs.lemuai.com/mcp/connect): Add Lemu AI to Claude, Claude Code or Cursor and approve the connection.
- [Tools](https://docs.lemuai.com/mcp/tools): Every tool, the permission it needs and the arguments it takes.
- [Permissions & limits](https://docs.lemuai.com/mcp/permissions): Scopes, call confirmation, calling policy and error codes.
- [REST API](https://docs.lemuai.com/api-reference/overview): Building your own integration instead? Use the Lemu AI REST API.
---
# Connect an Assistant
> Add the Lemu AI MCP server to Claude, Claude Code or Cursor and approve the connection
URL: https://docs.lemuai.com/mcp/connect
Connecting takes two parts: you add the Lemu AI server to your assistant, then you approve the connection on a Lemu AI consent screen. There is no API key to copy. The assistant signs in with OAuth, the same way you'd connect it to any other service.
**Server address:**
```text
https://mcp.lemuai.com/mcp
```
## Before you start
- You need a Lemu AI account with **admin** rights in the organization you want to connect. Other members can't approve a connection.
- To let the assistant request calls, the organization needs at least one active agent and a configured [telephony provider](https://docs.lemuai.com/integrations/telephony/overview).
## Add Lemu AI to your assistant
**Note:** These steps follow each client's standard setup for remote MCP servers. The Lemu AI side (discovery, client registration and the consent screen) works with any client that supports MCP over OAuth. Menu names in third-party apps can change, so check your client's own docs if a step looks different.
**Claude**
1. In Claude, open **Settings** → **Connectors**.
2. Click **Add custom connector**.
3. Enter a name (for example `Lemu AI`) and the server address `https://mcp.lemuai.com/mcp`, then add it.
4. Click **Connect**. Claude opens the Lemu AI consent screen (see below).
On Claude Team and Enterprise plans, only an organization owner can add custom connectors. Ask your owner to add it, then each member connects it.
**Claude Code**
Run:
```bash
claude mcp add --transport http lemuai https://mcp.lemuai.com/mcp
```
Then start Claude Code, run `/mcp`, choose **lemuai** and authenticate. Your browser opens the Lemu AI consent screen.
**Cursor**
Add the server to your `mcp.json` (Cursor Settings → **MCP** → **Add new MCP server**, or `~/.cursor/mcp.json`):
```json
{
"mcpServers": {
"lemuai": {
"url": "https://mcp.lemuai.com/mcp"
}
}
}
```
Cursor shows the server as needing login. Click **Login** to open the Lemu AI consent screen.
## Approve the connection
Your assistant sends you to `app.lemuai.com/mcp/authorize`. Sign in if asked, then review what the assistant is asking for.
**Step: Check who is asking**
The screen shows the name the assistant gave itself and the address you'll be sent back to after approving. The name is chosen by the app, so only approve if you started this connection and recognise that address.
**Step: Choose the organization**
If you're an admin in more than one organization, pick the one the assistant should work in.
**Step: Choose what it may do**
Tick the permissions to grant, for example "See which voice agents you allow it to use" or "Request phone calls". See [Permissions & limits](https://docs.lemuai.com/mcp/permissions) for what each one allows.
**Step: Choose agents and a daily cap**
If you allow calls, pick which agents it may use and the most calls per day (up to 200). Agents you create later are not included automatically.
**Step: Approve**
Click **Approve**. You're sent back to the assistant and it can use Lemu AI right away.
Click **Cancel** instead to refuse the connection.
## After you connect
- Ask the assistant something like *"Which Lemu AI agents can you use?"* to check the connection.
- The assistant renews its access automatically: access tokens last 1 hour and refresh on their own. A connection stays valid for up to 90 days, after which you approve it again.
- Calls the assistant requests wait for a person in your organization to confirm them. See [Call confirmation](https://docs.lemuai.com/mcp/permissions#call-confirmation).
## Disconnect
Remove Lemu AI from the assistant's connector or MCP settings. Assistants that support it revoke their access when you do.
**Note:** Viewing and revoking connections from the Lemu AI dashboard isn't available yet. To cut off a connection immediately, contact support.
---
# MCP Tools
> Every tool the Lemu AI MCP server offers, the permission it needs and the arguments it takes
URL: https://docs.lemuai.com/mcp/tools
Your assistant discovers these tools automatically when it connects, so you don't call them yourself. This page explains what each one does so you know what to ask for and what to approve.
A tool only works if the connection was granted its permission on the consent screen. See [Permissions & limits](https://docs.lemuai.com/mcp/permissions).
| Tool | Permission | What it does |
|---|---|---|
| `list_agents` | `agents:read` | Lists the agents this connection may use |
| `get_agent` | `agents:read` | Describes one agent and the details a call needs |
| `start_call` | `calls:start` | Requests an outbound call with an agent |
| `get_call` | `calls:read` | Status and outcome of one call |
| `list_calls` | `calls:read` | Recent calls made through this connection |
| `cancel_call` | `calls:cancel` | Cancels a call that hasn't been dialed |
| `create_agent_draft` | `agents:write` | Drafts a new agent from a brief |
| `update_agent_draft` | `agents:write` | Changes a draft it made |
| `test_agent` | `agents:write` | Reviews a draft before it can go live |
| `archive_agent` | `agents:write` | Retires an agent it made |
| `search_docs` | none | Searches the LemuAI docs (how-tos, settings, error messages) |
| `read_doc` | none | Reads one docs page as Markdown |
## Docs
`search_docs` and `read_doc` read the public docs at docs.lemuai.com, so every connection has them, whatever its permissions. An assistant uses them to explain how to do something in LemuAI or what an error means while it works in your workspace.
### search_docs
| Argument | Type | Required | Description |
|---|---|---|---|
| `query` | string | Yes | A question, a feature, or an error message as written, up to 500 characters |
| `limit` | integer | No | How many sections to return, 1 to 10. Default `5` |
Returns the best matching sections, each with its page title, section heading, `url` (with the section's anchor) and text.
### read_doc
| Argument | Type | Required | Description |
|---|---|---|---|
| `page` | string | Yes | A page path like `segments/overview`, or a `url` from `search_docs` |
Returns the page as Markdown (`markdown`), its `url`, and `truncated` when the page was longer than 40,000 characters.
## Agents
### list_agents
Lists the voice agents this connection may use: the agents you ticked on the consent screen. Takes no arguments. Each agent comes back with its `agent_id`, name and the context variables a call can fill in.
### get_agent
Describes one agent: its name and the context variables a call accepts.
| Argument | Type | Required | Description |
|---|---|---|---|
| `agent_id` | integer | Yes | The id from `list_agents` |
## Calls
### start_call
Requests an outbound phone call with an agent. It returns straight away with a `call_id`. The call then waits for a person in your organization to confirm it (see [Call confirmation](https://docs.lemuai.com/mcp/permissions#call-confirmation)) before it's dialed. Read the outcome with `get_call`.
| Argument | Type | Required | Description |
|---|---|---|---|
| `agent_id` | integer | Yes | The id from `list_agents` |
| `phone_number` | string | Yes | Who to call, in international format, like `+919876543210` |
| `counterparty_class` | string | Yes | Who this person is to your organization: `employee`, `customer`, `distributor`, `supervisor`, `prospect` or `other`. Your calling policy decides which are allowed |
| `idempotency_key` | string | Yes | A unique key for this call, 8 to 120 letters, digits or `_ . : -`. Retrying with the same key returns the original call and never dials twice |
| `context` | object | No | Values for the agent's context variables (see `get_agent`), up to 30 |
| `callee_timezone` | string | No | IANA timezone like `America/Chicago`. Only needed for countries that span several timezones |
| `correlation` | object | No | Your own ids (for example a ticket number), kept in the audit log next to the call |
**Note:** Result webhooks (`callback_url`) are not available for assistant connections. Assistants read results with `get_call`.
The call is checked against the connection's limits and your organization's calling policy before it's accepted. If something is wrong, the tool returns an error code such as `OUTSIDE_CALLING_HOURS`. See [Error codes](https://docs.lemuai.com/mcp/permissions#error-codes).
### get_call
Gets the status and outcome of a call made through this connection.
| Argument | Type | Required | Description |
|---|---|---|---|
| `call_id` | string | Yes | The id returned by `start_call` |
It returns:
| Field | Description |
|---|---|
| `call_id`, `agent_id` | Which call and agent |
| `status` | See the statuses below |
| `callee` | The number called, partly masked |
| `created_at`, `finished_at` | When the call was requested and when it ended |
| `outcome` | How the call ended, once it's over |
| `duration_s` | Call length in seconds |
| Captured details | Any information the agent was set up to collect during the call |
| `transcript_url` | A link to the transcript, only if the connection has `calls:transcripts:read` |
**Call statuses:**
| Status | Meaning |
|---|---|
| `pending_confirmation` | Waiting for a person in your organization to confirm it |
| `initiating` | Confirmed and being dialed |
| `in_progress` | The call is live |
| `completed` | The call finished |
| `failed` | The call could not be placed or did not connect |
| `cancelled` | Cancelled before it was dialed |
| `rejected` | A person in your organization declined it |
### list_calls
Lists recent calls made through this connection.
| Argument | Type | Required | Description |
|---|---|---|---|
| `status` | string | No | Only calls with this status |
| `limit` | integer | No | How many to return, 1 to 100 (default 20) |
### cancel_call
Cancels a call that hasn't been dialed yet, for example one still waiting for confirmation. A call that is already ringing or live can't be cancelled this way.
| Argument | Type | Required | Description |
|---|---|---|---|
| `call_id` | string | Yes | The call to cancel |
## Drafting agents
With the `agents:write` permission, an assistant can write a new voice agent from a short **brief**. Lemu AI writes the agent's script from the brief and adds fixed safeguards the brief can't remove. A connection can create at most 5 agents a day.
**Warning:** Agents made over MCP are **drafts**. They can't place calls until they're published, and publishing isn't available to assistant connections. To publish a draft an assistant made, contact support.
### create_agent_draft
| Argument | Type | Required | Description |
|---|---|---|---|
| `brief` | object | Yes | What the agent is for (see below). Not a prompt |
| `idempotency_key` | string | Yes | A unique key for this request. Reusing it returns the agent it already created |
**Brief fields:**
| Field | Required | Description |
|---|---|---|
| `objective` | Yes | What the call should achieve (10 to 500 characters) |
| `counterparty_class` | Yes | Who the agent will call: `employee`, `customer`, `distributor`, `supervisor`, `prospect` or `other` |
| `language` | Yes | `primary` language as a tag like `hi-IN` or `en-US`, plus up to 5 more it `also_understands` |
| `persona` | Yes | The agent's `name` and who it calls `on_behalf_of` |
| `capture` | No | Up to 20 details to collect, each with a `name`, `type` (`string`, `number`, `boolean` or `date`), whether it's `required` and an optional `prompt` |
| `authority` | No | What the agent `may` and `may_not` agree to on the call (up to 10 each) |
| `off_limits_topics` | No | Topics the agent must not discuss (up to 20) |
| `escalation` | No | When to end the call politely and flag it, for example when the person asks for a human |
| `limits` | No | `max_duration_s` (30 to 900, default 300) and `max_attempts_per_callee_per_day` (1 to 5, default 2) |
| `context_schema` | No | Up to 20 context variables a call can pass in, each with a sensitivity `class` (`public`, `internal` or `confidential`) and a description |
| `expires_in_days` | No | How long the draft lives before it expires (1 to 90, default 7) |
### update_agent_draft
Changes a draft this connection made. Send the `draft_version` you last read. If the draft has changed since, the update is refused with `STALE_DRAFT` so nothing is overwritten.
| Argument | Type | Required | Description |
|---|---|---|---|
| `agent_id` | integer | Yes | The draft to change |
| `base_version` | integer | Yes | The `draft_version` you read |
| `brief` | object | Yes | The full updated brief |
### test_agent
Reviews the draft as it will run: safeguards present, nothing forbidden, only declared context used. A draft needs a passed review of its exact version before it can be published.
| Argument | Type | Required | Description |
|---|---|---|---|
| `agent_id` | integer | Yes | The draft to review |
### archive_agent
Retires an agent this connection made. Calls already in progress finish normally.
| Argument | Type | Required | Description |
|---|---|---|---|
| `agent_id` | integer | Yes | The agent to archive |
---
# Permissions & Limits
> What each MCP permission allows, how calls are confirmed, the calling policy and the error codes assistants can get
URL: https://docs.lemuai.com/mcp/permissions
Every assistant connection is limited to what an admin approved on the consent screen, and Lemu AI enforces those limits on every request, whatever the assistant sends.
## Permissions
These are the permissions (OAuth scopes) an assistant can ask for. The consent screen lists the ones it asked for, and you can untick any of them before approving. An assistant that doesn't ask for specific permissions gets `agents:read` and `calls:read`.
| Scope | On the consent screen | Allows |
|---|---|---|
| `agents:read` | See which voice agents you allow it to use | `list_agents`, `get_agent` |
| `calls:read` | Read the status and outcome of calls it places | `get_call`, `list_calls` |
| `calls:transcripts:read` | Read call transcripts (may contain personal data) | A transcript link in `get_call` |
| `calls:start` | Request phone calls (a person in your organization confirms each one) | `start_call` |
| `calls:cancel` | Cancel calls that have not been dialed yet | `cancel_call` |
| `agents:write` | Create and edit draft voice agents (it cannot publish them) | `create_agent_draft`, `update_agent_draft`, `test_agent`, `archive_agent` |
An assistant can only see and read the calls it placed itself, never other calls in your organization.
## Call confirmation
Every call an assistant requests is created with the status `pending_confirmation`. Nothing is dialed until a person in your organization confirms it. If they decline, the call becomes `rejected`. When a call is confirmed, the calling policy and limits are checked again, since time may have passed since the request.
**Note:** Confirming or declining assistant calls from the Lemu AI dashboard isn't available yet. Until it is, calls requested by an assistant stay in `pending_confirmation`. Contact support if you need to confirm calls now. The assistant can cancel its own pending calls with `cancel_call`.
## Connection limits
| Limit | Default | Notes |
|---|---|---|
| Agents it may use | Chosen on the consent screen | Agents created later are not added |
| Calls per day | Chosen on the consent screen | At most 200 |
| Calls in progress at once | 3 | |
| Calls waiting for confirmation | 20 | |
| Agents it may create per day | 5 | Only with `agents:write` |
| Connection lifetime | 90 days | After that, approve the connection again |
## Calling policy
Your organization's calling policy applies to every call an assistant requests:
- **Who may be called.** Each call says who the person is: `employee`, `customer`, `distributor`, `supervisor`, `prospect` or `other`. Only classes the policy allows can be called. By default, a prospect can be called at most twice in total (one call and one follow-up).
- **Calling hours.** Calls are only placed inside the allowed hours in the **callee's** local time. Lemu AI works out the timezone from the phone number. For countries that span several timezones (like the US), the assistant must pass `callee_timezone`.
- **Do not call.** People who asked not to be called, are on your do-not-call list, or opted out of calls (or of everything) on their contact in Lemu AI are never called.
- **AI disclosure.** The agent must tell the person they're talking to an AI. Its opening greeting needs to include the `{{ai_disclosure}}` variable, which Lemu AI replaces with your organization's wording.
Until your organization sets its own policy, a default applies: only **employees** and **supervisors** can be called, between **09:00 and 20:00** local time, every day, with the AI disclosure on.
**Note:** Changing the calling policy or the do-not-call list from the dashboard isn't available yet. Contact support to change them.
## Error codes
When a tool can't do what was asked, it returns an error with a code and a short message. The common ones:
| Code | Meaning |
|---|---|
| `SCOPE_MISSING` | The connection wasn't granted the permission this tool needs |
| `INVALID_ARGUMENTS` | An argument is missing or has the wrong format |
| `AGENT_NOT_FOUND` | The agent doesn't exist or isn't active |
| `AGENT_NOT_ALLOWED` | The connection may not use this agent |
| `INVALID_PHONE` | The phone number isn't valid. Use international format like `+919876543210` |
| `COUNTRY_NOT_ALLOWED` | Calls to this country aren't allowed for this connection |
| `CLASS_NOT_PERMITTED` | Your calling policy doesn't allow calls to this class of person |
| `OUTSIDE_CALLING_HOURS` | It's outside the allowed hours in the callee's timezone. The error says when the next window opens |
| `TIMEZONE_REQUIRED` | The country spans several timezones, so `callee_timezone` is needed |
| `TIMEZONE_INVALID` | `callee_timezone` isn't a known timezone name |
| `NUMBER_OPTED_OUT` | The person asked not to be called, is on the do-not-call list, or opted out of calls in Lemu AI |
| `CALL_LIMIT_FOR_PERSON` | This person has already been called the maximum number of times |
| `DISCLOSURE_MISSING` | The agent's opening greeting doesn't include `{{ai_disclosure}}` |
| `DAILY_CALL_LIMIT` | The connection reached its calls-per-day limit |
| `CONCURRENCY_LIMIT` | The connection already has the maximum calls in progress |
| `PENDING_LIMIT` | Too many calls are waiting for confirmation |
| `DAILY_MINUTES_LIMIT` | The connection used its daily call minutes |
| `QUOTA_EXCEEDED` | Your organization has no call minutes left on its plan |
| `TELEPHONY_NOT_CONFIGURED` | Telephony isn't set up for your organization |
| `DIAL_FAILED` | The telephony provider couldn't start the call |
| `CALL_NOT_FOUND` | No such call, or it wasn't made through this connection |
| `CANNOT_CANCEL` | The call has already been dialed, so it can't be cancelled |
| `INVALID_BRIEF` | The agent brief isn't valid. The error lists the problems |
| `STALE_DRAFT` | The draft changed since you read it. Read it again and retry |
| `AGENT_QUOTA` | The connection already created its 5 agents for today |
| `REVIEW_FAILED` | The draft review found problems to fix |
| `AGENT_EXPIRED` / `AGENT_ARCHIVED` | The draft expired or was archived |
| `TOKEN_INVALID` | The connection was revoked or expired. Reconnect the assistant |
## Audit log
Every request an assistant makes is recorded: which connection, which tool, the outcome, the call it touched and how long it took. Arguments are stored as a fingerprint, not in full, and phone numbers are masked. If you need a copy of the log for a connection, contact support.
---
# Standard and conversion events
> The event names Lemu recognises, the fields an order needs (value, currency and order_id), and how revenue and ROI are calculated
URL: https://docs.lemuai.com/website-pixel/standard-events
Lemu uses Meta Pixel's standard events exactly as Meta defines them: the same names and the same parameters. If your site or app already sends events to Meta, you can send the same calls to Lemu unchanged. The same names work everywhere: the website snippet, the app SDKs, the [Send an Event API](https://docs.lemuai.com/api-reference/events/trigger) and Shopify.
Only **conversion events** have required fields. By default that is `Purchase`, because journey and campaign revenue and ROI are calculated from it. Every other event is free-form.
## Meta's standard events
| Event | Meaning | Parameters Meta lists |
|---|---|---|
| `PageView` | A page loaded. The website snippet sends it for you | |
| `ViewContent` | A product or other key page was viewed | `content_ids`, `content_category`, `content_name`, `content_type`, `contents`, `currency`, `value` |
| `Search` | A search | `search_string`, `content_category`, `content_ids`, `contents`, `currency`, `value` |
| `AddToCart` | An item was added to the cart | `content_ids`, `content_name`, `content_type`, `contents`, `currency`, `value` |
| `AddToWishlist` | An item was added to a wishlist | `content_ids`, `content_name`, `content_category`, `contents`, `currency`, `value` |
| `InitiateCheckout` | Checkout started | `content_ids`, `content_category`, `contents`, `currency`, `num_items`, `value` |
| `AddPaymentInfo` | Payment details were entered | `content_ids`, `content_category`, `contents`, `currency`, `value` |
| `Purchase` | An order was placed | `value` and `currency` (required by Meta), `content_ids`, `content_name`, `content_type`, `contents`, `num_items`, plus `order_id` for Lemu |
| `Lead` | A lead was submitted | `content_category`, `content_name`, `currency`, `value` |
| `CompleteRegistration` | A sign-up was completed | `content_name`, `currency`, `status`, `value` |
| `Subscribe` | A paid subscription started | `currency`, `predicted_ltv`, `value` |
| `StartTrial` | A free trial started | `currency`, `predicted_ltv`, `value` |
| `Schedule` | An appointment was booked | |
| `SubmitApplication` | An application was submitted | |
| `Contact` | Someone contacted your business | |
| `CustomizeProduct` | A product was customised | |
| `Donate` | A donation | |
| `FindLocation` | Someone searched for a store location | |
What the parameters mean:
| Parameter | Type | Meaning |
|---|---|---|
| `value` | number | An amount in major units: `1499.5` is ₹1,499.50 |
| `currency` | string | An ISO 4217 code such as `INR` |
| `content_ids` | list of strings | Product ids or SKUs |
| `contents` | list of objects | Items, each with `id` and `quantity`, and optionally `item_price`, `title`, `brand` and `category` |
| `content_type` | string | `product` or `product_group` |
| `content_name`, `content_category` | string | A name and a category |
| `num_items` | integer | The number of items |
| `search_string` | string | What was searched for |
| `predicted_ltv` | number | The expected lifetime value of a subscriber |
| `status` | string | The status of a registration |
You can add your own parameters next to these, for example `payment_method: "cod"` or `coupon`. For Meta's full definitions, see Meta's [standard events reference](https://developers.facebook.com/docs/meta-pixel/reference).
### What `value` means on each event
`value` follows Meta's definition, which is different on each step of the funnel:
- On `AddToCart`, it is the value of what was added, not the cart total.
- On `InitiateCheckout`, it is the checkout (cart) total. Use this event's `value` for abandoned-cart conditions on cart value.
- On `Purchase`, it is the order total.
If you want a running cart total on `AddToCart`, send it as your own parameter, for example `cart_total`.
### Matching names
Matching a Meta name ignores case and separators. `purchase`, `PURCHASE` and `Purchase` are all stored as `Purchase`, and `add_to_cart`, `Add To Cart` and `AddToCart` are all stored as `AddToCart`.
A name that doesn't match one of Meta's events is a **custom event**. Custom events are allowed everywhere and are never renamed, rejected or reshaped. Personal data is still removed from their properties.
### App events
The app SDKs also send these events for you. They have no Meta equivalent and are never conversions:
| Event | When |
|---|---|
| `app_installed` | The first launch with the SDK |
| `app_updated` | The first launch after the app version changed |
| `app_opened` | The app is launched or comes back to the foreground |
| `app_backgrounded` | The app goes to the background |
| `deep_link_opened` | A link opens the app |
| `screen_viewed` | A screen is shown, when you track screens |
See the [event reference](https://docs.lemuai.com/sdks/events#app-lifecycle-events).
## Meta and Lemu side by side
```js
// Already on your site for Meta:
fbq("track", "Purchase", { value: 1499.5, currency: "INR", content_ids: ["SKU1"], content_type: "product" });
// The same call for Lemu, plus order_id:
lemu("track", "Purchase", { value: 1499.5, currency: "INR", content_ids: ["SKU1"], content_type: "product", order_id: "1042" });
```
For purchases you can also use `lemu("purchase", { value, currency, order_id })`, which sends the event straight away.
### Why Lemu adds `order_id`
Lemu counts one conversion per order. The same order is often reported more than once: by your website, by your app, by Shopify (from both the storefront and the store's order webhook), by your server, or by a reload of the thank-you page. With `order_id`, all of these count as one order, so revenue isn't counted twice. Without it, every `Purchase` event counts as its own order.
Meta's Conversions API has the same field, so your order id fits both. Use the same order id your store and backend use.
## Conversion events
A conversion event is an event that counts as an order for revenue and ROI. The list is set under **Settings → Sending Limits → Conversion events**. The default is `Purchase`. You can add others, such as `Lead`, `Subscribe`, `Schedule`, or one of your own custom events. See [Sending Limits](https://docs.lemuai.com/settings/sending-limits#conversion-events).
Every conversion event needs three fields:
| Field | What it should be |
|---|---|
| `value` | A number, 0 or more, in major units |
| `currency` | An ISO 4217 code such as `INR` |
| `order_id` | Your id for the order, as text |
### When a field is missing
A conversion event is **never rejected** for a missing or wrong field. A missing field never drops an order. Instead Lemu does the following, and counts it:
| Problem | What Lemu does |
|---|---|
| `value` is text, such as `"1,499.00"` | Converts it to a number |
| `value` is missing, but an older field such as `total_price` or `total` has the amount | Uses that field |
| `value` is missing, isn't a number, or is negative | Counts the order with no revenue |
| `currency` is missing or isn't an ISO code | Uses your workspace currency |
| `order_id` is missing, but an older field such as `order_number` has it | Uses that field |
| `order_id` is missing | Counts the order, but the same order sent twice counts twice |
You can see these counts in two places:
- **Settings → Sending Limits**, under **Conversion events**: how many conversion events arrived in the last 30 days, and how many had each problem.
- The **Recent events** debugger on each [tracking source](https://docs.lemuai.com/website-pixel/overview#recent-events): each conversion event, marked **Conversion**, with what was missing or fixed.
Events that aren't conversion events go through none of these checks.
## How ROI is calculated
An order is credited to the **last** journey or campaign message the contact got, if that message came within the channel's attribution window. See [Sending Limits](https://docs.lemuai.com/settings/sending-limits#revenue-attribution).
- **Revenue** is the total `value` of the credited orders, per currency.
- **Message spend** is what the messages cost in money: WhatsApp charges from your WhatsApp wallet. Email (paid in credits) and calls (paid in plan minutes) are not priced, so they don't add to spend.
- **ROI** is revenue divided by message spend. `3.5x` means 3.5 back for each 1 spent. When there was no message spend in the period, ROI shows `–`.
A few details:
- Orders that arrived without a value count as orders but add nothing to revenue. Reports say how many there were, so a low ROI caused by missing data isn't mistaken for a poor journey.
- ROI uses revenue in the same currency as the spend. Revenue in other currencies is shown but left out of the ratio.
ROI is shown on each [journey's report](https://docs.lemuai.com/automation/reports#revenue-and-roi), on marketing campaigns and on the Copilot home in the [AI Copilot](https://docs.lemuai.com/copilot/overview).
## Old names that still match
Before standard events, Lemu's website pixel and Shopify connection used their own names. These old names still match their Meta event everywhere you name an event: journey triggers, exit events, **Wait for reaction**, segments, the Event Log filter and **Conversion events**. A journey on `Purchase` also starts for an event sent as `order_placed`, and the other way round.
| Old name | Matches |
|---|---|
| `order_placed`, `checkout_completed` | `Purchase` |
| `cart_added`, `checkout_started` | `InitiateCheckout` |
| `added_to_cart` | `AddToCart` |
| `viewed_product` | `ViewContent` |
| `page_viewed` | `PageView` |
| `searched` | `Search` |
| `checkout_payment_submitted` | `AddPaymentInfo` |
`cart_added` matches `InitiateCheckout`, not `AddToCart`, because it was always sent when a shopper started checkout.
Saved journeys, segments and the **Conversion events** setting that used these old names were renamed to the Meta names for you. Events you sent before keep the name they were stored with, and still match. Your own custom event names were not changed.
## Send purchases from your server too
A purchase sent from a browser or an app can be lost: the app is closed right after payment, or an ad blocker stops the script. For the most reliable revenue and ROI, also send `Purchase` from your backend with the [Send an Event API](https://docs.lemuai.com/api-reference/events/trigger):
```bash
curl -X POST https://app.lemuai.com/api/v1/events \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"event_type": "Purchase",
"phone": "+919876543210",
"data": { "value": 1499.5, "currency": "INR", "order_id": "1042" }
}'
```
Keep sending it from your site or app as well. With the same `order_id`, both count as one order. Shopify stores already send orders from the store's order webhook (see [Shopify](https://docs.lemuai.com/integrations/shopify#store-events)).
---
# SDKs
> Send events, purchases and known users to Lemu from your website, JavaScript and React apps, and your Android, iOS, Flutter and React Native apps
URL: https://docs.lemuai.com/sdks/overview
**Note:** **Setup required:** the SDK packages (`@lemuai/analytics`, `@lemuai/react`, `@lemuai/react-native`, `com.lemuai:analytics`, `LemuAnalytics` and `lemu_analytics`) are rolling out. If a package isn't available yet, contact LemuAI support for access. The [website snippet](https://docs.lemuai.com/sdks/javascript#add-the-snippet) needs no package.
The Lemu SDKs send what people do on your website and in your apps to Lemu: page and screen views, Meta's standard events such as `AddToCart` and `Purchase`, and `identify` for people you know. Lemu uses these events for contact activity and segments, to start journeys, and to calculate the revenue and ROI of your journeys and campaigns.
## Pick your SDK
| Platform | Package | Source kind | Guide |
|---|---|---|---|
| Any website | The snippet from your source | Website | [Website and JavaScript](https://docs.lemuai.com/sdks/javascript) |
| JavaScript with a bundler | npm `@lemuai/analytics` | Website | [Website and JavaScript](https://docs.lemuai.com/sdks/javascript) |
| React and Next.js | npm `@lemuai/react` | Website | [React and Next.js](https://docs.lemuai.com/sdks/react) |
| React Native and Expo | npm `@lemuai/react-native` | App | [React Native and Expo](https://docs.lemuai.com/sdks/react-native) |
| Android (Kotlin, Java) | Maven Central `com.lemuai:analytics` | App | [Android](https://docs.lemuai.com/sdks/android) |
| iOS and tvOS (Swift, Objective-C) | Swift Package Manager or CocoaPods `LemuAnalytics` | App | [iOS](https://docs.lemuai.com/sdks/ios) |
| Flutter (Android, iOS, web, desktop) | pub.dev `lemu_analytics` | App | [Flutter](https://docs.lemuai.com/sdks/flutter) |
## Get a write key
Every SDK needs the write key of a [tracking source](https://docs.lemuai.com/website-pixel/overview).
**Step: Add a source**
In Lemu, open **Settings → Tracking Sources**. Under **Add a tracking source**, choose **Website** for a website or a JavaScript, React or Next.js app. Choose **App** for an Android, iOS, Flutter or React Native app.
**Step: Name it**
Give it a **Name**, for example "Main store" or "Android and iOS app". You can list the [Allowed sites](https://docs.lemuai.com/website-pixel/overview#allowed-sites) or [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps) now or later. Then click **Create**.
**Step: Copy the write key**
On the new source, under **Set up**, copy the write key. It starts with `lpk_`.
Under **Set up**, the source also shows install and setup code for each platform with your key filled in: **Any website** and **React / Next.js** on a website source, and **Android**, **iOS**, **Flutter** and **React Native** on an app source.
The write key is public by design and safe to ship in your site or app: it can only send events, never read anything. One app source can serve the same app on every platform, for example your Android and iOS builds. Create a separate source for each environment, such as staging, so test events stay apart.
## What every SDK does
Every SDK has the same calls. Each guide shows them in that platform's language.
| Call | What it does |
|---|---|
| `track(event, properties)` | Sends any event. Use Meta's standard name, such as `AddToCart`, when one fits |
| `purchase(...)` | Sends a `Purchase` with `value`, `currency` and your order id, straight away |
| `identify(userId, traits)` | Ties the visitor or install to your own user id and sends their contact details |
| `reset()` | Call on logout: starts a new anonymous id and clears the user id |
| `page()` or `screen(name)` | A page view on a website, a screen view in an app |
| `setConsent(granted)` | Starts or stops sending when the SDK waits for consent |
| `optOut()` and `optIn()` | Turns all tracking off or back on, remembered on the device |
| `flush()` | Sends queued events now |
Every SDK has constants for the standard event names (`LemuEvent`), so the names can't be misspelled. See the [event reference](https://docs.lemuai.com/sdks/events).
## Purchases, revenue and ROI
Send every order with `purchase`, with three fields:
- `value`: the order total, in major units (`1499.5` is ₹1,499.50).
- `currency`: an ISO 4217 code such as `INR`.
- the order id (`order_id` in JavaScript, `orderId` on Android, iOS and Flutter): the same id your store and backend use.
Lemu counts one conversion per order id, however many times the order is reported: by your app, your website, Shopify or your server. Without it, every report counts as a separate sale. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events) for what Lemu does when a field is missing, and [send purchases from your server too](https://docs.lemuai.com/website-pixel/standard-events#send-purchases-from-your-server-too) for the most reliable numbers.
## Known users
Call `identify` when someone signs up or logs in, with your own user id and their contact details (`email`, `phone` in international format such as `+919876543210`, `first_name`, `last_name`). The user id is sent with every later event until `reset`.
- An `identify` with an email or a phone finds the matching contact, or creates one.
- An `identify` with only your user id links to an existing contact with that id. It never creates one.
- Before `identify`, a visitor or install is anonymous and isn't a contact. Once they identify, their earlier anonymous activity shows up on the contact.
Contact details belong in `identify` only. Lemu removes keys such as `email`, `phone` and `address` from event properties.
To let tracked actions from identified people start journeys, switch on **Let identified visitors' tracked actions trigger journeys** on the source. See [Trigger journeys](https://docs.lemuai.com/website-pixel/overview#trigger-journeys).
## Consent and opt-out
If you need consent before tracking, for example under GDPR or the DPDP Act, start the SDK with `requireConsent` and call `setConsent(true)` once the person agrees.
- Until consent, nothing is sent and nothing is stored on the device, not even the anonymous id. Up to 50 events wait in memory and are sent once consent is given.
- `setConsent(false)` discards the waiting and queued events. A granted consent is remembered (in the browser, across visits; in an app, across launches) until `setConsent(false)`.
- `optOut()` stops all tracking and clears the queue, and is remembered. `optIn()` turns tracking back on.
## How events are sent
| | Websites | Apps |
|---|---|---|
| When | Every second or every 10 events, and when the page is hidden | Every 30 seconds or every 20 events, when the app goes to the background, and right after a purchase |
| If sending fails | Retried with increasing waits, up to 5 minutes apart, while the page is open | Kept on the device, also across restarts, and retried with increasing waits, up to 5 minutes apart, for up to 20 hours |
| Queue | Up to 1,000 events, in memory | Up to 1,000 events, for up to 7 days. When it's full, the oldest event that isn't a purchase is dropped first |
Each request carries up to 50 events. The same event received twice within 24 hours is recorded once, so retries never double count. See [Limits and duplicates](https://docs.lemuai.com/website-pixel/overview#limits-and-duplicates).
The SDKs never throw into your code. A bad argument, such as an empty event name, is ignored and logged in debug mode.
## Privacy
The SDKs collect a random anonymous id for each browser or app install, the events and properties your code sends, the user id and traits you pass to `identify`, and basic app and device details such as the app version, OS version, device model, locale and time zone. They collect no advertising ids (IDFA, GAID) and no hardware ids.
For app store forms, see [Google Play data safety](https://docs.lemuai.com/sdks/android#google-play-data-safety) and [App Store privacy](https://docs.lemuai.com/sdks/ios#app-store-privacy).
## Check that events arrive
**Step: Turn on debug mode**
Start the SDK with `debug` on. It logs every call, request and response.
**Step: Send an event**
Open your site or app and do something you track, or call `flush()` to send straight away.
**Step: Look in Lemu**
In **Settings → Tracking Sources**, the source shows when the last event arrived. Under **Recent events**, click **Show recent events** to see the last 50 events from the past hour as Lemu stored them, then **Refresh** for new ones. See [Recent events](https://docs.lemuai.com/website-pixel/overview#recent-events).
Events also appear in the [Event Log](https://docs.lemuai.com/event-log/overview).
## Next steps
- [Website and JavaScript](https://docs.lemuai.com/sdks/javascript): The snippet for any website, or the npm package
- [React and Next.js](https://docs.lemuai.com/sdks/react): A provider, a hook and page tracking
- [React Native and Expo](https://docs.lemuai.com/sdks/react-native): Events, screens, installs and deep links
- [Android](https://docs.lemuai.com/sdks/android): Kotlin and Java, with the Play install referrer
- [iOS](https://docs.lemuai.com/sdks/ios): Swift, SwiftUI, UIKit and Objective-C
- [Flutter](https://docs.lemuai.com/sdks/flutter): One SDK for mobile, web and desktop
- [Event reference](https://docs.lemuai.com/sdks/events): Every event name, constant and parameter
- [Standard and conversion events](https://docs.lemuai.com/website-pixel/standard-events): The fields orders need and how ROI is calculated
---
# Website and JavaScript
> Add Lemu to any website with the snippet, or to a JavaScript app with the @lemuai/analytics package: page views, events, purchases, known users and consent
URL: https://docs.lemuai.com/sdks/javascript
The same script powers the website snippet and the `@lemuai/analytics` npm package. It has no dependencies, is about 5.5 KB gzipped, and is safe to import during server-side rendering.
- Use the **snippet** on any website, including Shopify themes, WordPress and site builders.
- Use the **package** in a JavaScript or TypeScript app built with a bundler.
- For React and Next.js, use [`@lemuai/react`](https://docs.lemuai.com/sdks/react), which is built on this package.
You need the write key of a **Website** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).
## Add the snippet
Copy the snippet from your source (**Settings → Tracking Sources**, the **Any website** tab under **Set up**) and paste it into the `` of every page. It loads the script, starts it with your key and records a page view:
```html
```
With the snippet, call every method by name, for example `lemu("track", "AddToCart", { value: 999, currency: "INR" })`. Calls made before the script has loaded are kept and run once it arrives.
## Or install the package
```bash
npm install @lemuai/analytics
```
```js
import { lemu, LemuEvent } from "@lemuai/analytics";
lemu.init("YOUR_WRITE_KEY");
lemu.page();
lemu.track(LemuEvent.AddToCart, {
value: 999,
currency: "INR",
content_ids: ["SKU1"],
content_type: "product",
});
```
Calls made before `init` are kept and run after it. The package sends to `https://app.lemuai.com` unless you set `apiHost`.
## Send events
Use Meta's standard event names for standard actions, such as `ViewContent`, `AddToCart` and `InitiateCheckout`. With the package, use the `LemuEvent` constants. Any other name works as a custom event.
**Snippet**
```js
lemu("track", "ViewContent", { content_ids: ["SKU1"], content_type: "product", value: 999, currency: "INR" });
lemu("track", "coupon_applied", { code: "DIWALI10" });
```
**Package**
```js
lemu.track(LemuEvent.ViewContent, { content_ids: ["SKU1"], content_type: "product", value: 999, currency: "INR" });
lemu.track("coupon_applied", { code: "DIWALI10" });
```
`value` is in major units (`999` is ₹999) and `currency` is an ISO 4217 code such as `INR`. See the [event reference](https://docs.lemuai.com/sdks/events) for every name and parameter.
Keep contact details such as email, phone and address out of event properties. Lemu removes them. Send them with `identify` instead.
## Purchases
Send every order with `purchase` on your thank-you or order confirmation page:
**Snippet**
```js
lemu("purchase", {
value: 1499.5,
currency: "INR",
order_id: "1042",
contents: [{ id: "SKU1", quantity: 1, item_price: 1499.5 }],
});
```
**Package**
```js
lemu.purchase({
value: 1499.5,
currency: "INR",
order_id: "1042",
contents: [{ id: "SKU1", quantity: 1, item_price: 1499.5 }],
});
```
`purchase` sends a `Purchase` event at once, without waiting for the next batch, so it isn't lost if the visitor closes the tab.
`value`, `currency` and `order_id` are required. Lemu counts one conversion per `order_id`, so the same order reported by this page, a reload of the page, Shopify or your server counts once. Lemu never rejects an event for a missing field, but it flags the conversion. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).
## Identify visitors
Call `identify` when the visitor signs up, logs in or fills a form, with your own user id and their contact details:
```js
lemu.identify("crm-123", {
email: "asha@example.com",
phone: "+919876543210",
first_name: "Asha",
});
// without your own id
lemu.identify({ email: "asha@example.com" });
// on logout
lemu.reset();
```
With the snippet, the same calls are `lemu("identify", "crm-123", { ... })` and `lemu("reset")`.
The user id is kept and sent with every later event until `reset`, which also gives the visitor a new anonymous id. See [Identify visitors](https://docs.lemuai.com/website-pixel/overview#identify-visitors) for how Lemu matches contacts.
## Page views and single-page apps
`page(name?, properties?)` records a page view with the page's URL, path, title and referrer. It's stored as `PageView`.
In a single-page app, start with `trackPageChanges` to record a page view on every `history.pushState` and on back and forward navigation:
```js
lemu.init("YOUR_WRITE_KEY", { trackPageChanges: true });
```
With the snippet, pass options as the third argument: `lemu("init", "YOUR_WRITE_KEY", { trackPageChanges: true })`.
UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`) and `gclid` / `fbclid` on the landing page are kept with the visitor's events. Personal data in page URLs, such as `?email=`, is removed.
## Consent and opt-out
If you need consent before tracking, for example after your cookie banner, start with `requireConsent`:
```js
lemu.init("YOUR_WRITE_KEY", { requireConsent: true });
// later, from your consent banner
lemu.setConsent(true); // snippet: lemu("consent", true)
```
- Until consent, nothing is sent and nothing is written to cookies or local storage, not even the visitor id. Up to 50 events wait in memory and are sent once consent is given.
- `setConsent(false)` discards them. A granted consent is remembered in local storage (`_lemu_consent`), so returning visitors aren't asked again. `setConsent(false)` forgets it.
- `optOut()` stops all tracking and clears the queue. It is remembered in a cookie and in local storage. `optIn()` undoes it.
## Debug mode
```js
lemu.init("YOUR_WRITE_KEY", { debug: true });
```
Every call, request and response is logged to the browser console with a `[lemu]` prefix. Bad arguments, such as an empty event name or properties that can't be turned into JSON, are logged and ignored. The script never throws into your code.
If the console shows a refused request, check that your site is listed under [Allowed sites](https://docs.lemuai.com/website-pixel/overview#allowed-sites) on the source.
## Options
| Option | Default | What it does |
|---|---|---|
| `apiHost` | `https://app.lemuai.com` | Where to send events. The snippet sends to the host it was loaded from |
| `debug` | `false` | Logs calls, requests and responses |
| `requireConsent` | `false` | Holds events until `setConsent(true)` |
| `trackPageChanges` | `false` | Records a page view on single-page-app navigation |
| `cookieDomain` | the current host | Shares the visitor id across subdomains, for example `.example.com` |
| `flushAt` | `10` | Sends when this many events are queued |
| `flushInterval` | `1000` | Sends queued events after this many milliseconds |
| `maxQueueSize` | `1000` | The most events kept while offline |
## API
| Method | What it does |
|---|---|
| `init(writeKey, options?)` | Starts tracking. Calls made before `init` are kept and run after it |
| `page(name?, properties?)` | Records a page view |
| `track(event, properties?)` | Sends any event |
| `purchase({ value, currency, order_id, ... })` | Sends a `Purchase` at once |
| `identify(userId?, traits?)` | Sets the user id and sends contact details |
| `reset()` | New anonymous id, user id cleared |
| `flush()` | Sends queued events now. Returns a promise |
| `setConsent(granted)` | Starts or stops sending under `requireConsent` |
| `optOut()`, `optIn()` | Stops or resumes all tracking, remembered in the browser |
| `anonymousId()` | The visitor id, or `null` before consent or after opt-out |
| `createLemu()` | A separate client, for sending to a second source from the same page (package only) |
## How events are sent
Events are batched and sent every second or every 10 events, and with `sendBeacon` when the page is hidden, so events from the last page aren't lost. Requests are sent as plain text, so the browser makes no extra CORS request first. Failed requests are retried with increasing waits.
The visitor id lives in the `_lemu_aid` first-party cookie and in local storage, so returning visitors keep the same id.
---
# React and Next.js
> Add Lemu to a React or Next.js app with @lemuai/react: a provider, the useLemu hook and page tracking for React Router and the Next.js routers
URL: https://docs.lemuai.com/sdks/react
`@lemuai/react` adds Lemu to React and Next.js apps: a provider, a hook to send events from any component, and page tracking for React Router and both Next.js routers. It's built on [`@lemuai/analytics`](https://docs.lemuai.com/sdks/javascript) and is safe with server-side rendering: nothing touches `window` during render, and calls made on the server do nothing.
You need the write key of a **Website** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key). The source's **React / Next.js** tab under **Set up** shows the code below with your key filled in.
## Install
```bash
npm install @lemuai/react
```
## Set up
Wrap your app once with `LemuProvider`:
```tsx
import { LemuProvider } from "@lemuai/react";
export function App() {
return (
);
}
```
The provider starts tracking after it mounts in the browser. It reads `options` once, when it mounts. For the options, see [Website and JavaScript](https://docs.lemuai.com/sdks/javascript#options).
## Page views
`usePageTracking(pathname)` records a page view whenever the path changes. Use it once, inside the provider.
**Next.js app router**
Put the provider in a client component:
```tsx
// app/lemu.tsx
"use client";
import { usePathname } from "next/navigation";
import { LemuProvider, usePageTracking } from "@lemuai/react";
function PageTracker() {
usePageTracking(usePathname());
return null;
}
export function Lemu({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
Then use it in your root layout:
```tsx
// app/layout.tsx
import { Lemu } from "./lemu";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}
```
Set `NEXT_PUBLIC_LEMU_WRITE_KEY` to your write key. It's public, so the `NEXT_PUBLIC_` prefix is fine.
**Next.js pages router**
In `pages/_app.tsx`:
```tsx
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import { LemuProvider, usePageTracking } from "@lemuai/react";
function PageTracker() {
usePageTracking(useRouter().asPath);
return null;
}
export default function MyApp({ Component, pageProps }: AppProps) {
return (
);
}
```
**React Router**
```tsx
import { useLocation } from "react-router-dom";
import { usePageTracking } from "@lemuai/react";
function PageTracker() {
usePageTracking(useLocation().pathname);
return null;
}
```
Render `` inside both your router and `LemuProvider`.
## Send events
Get the client with `useLemu()` in any component:
```tsx
import { LemuEvent, useLemu } from "@lemuai/react";
function AddToCartButton({ product }) {
const lemu = useLemu();
return (
);
}
```
`LemuEvent` has a constant for each of Meta's standard events. Any other name works as a custom event. See the [event reference](https://docs.lemuai.com/sdks/events).
`useLemu()` also works outside a provider. It returns the shared client, and calls made before the provider starts it are kept and sent once it does.
## Purchases
```tsx
const lemu = useLemu();
lemu.purchase({
value: 1499.5,
currency: "INR",
order_id: order.id,
contents: [{ id: "SKU1", quantity: 1, item_price: 1499.5 }],
});
```
`purchase` sends a `Purchase` event at once. Always pass your real order id: Lemu counts one conversion per `order_id`, however many sources report the order (this page, a webhook, a reload of the thank-you page). See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).
## Identify users
```tsx
const lemu = useLemu();
// after sign-up or login
lemu.identify(user.id, { email: user.email, phone: user.phone, first_name: user.firstName });
// on logout
lemu.reset();
```
The user id is kept and sent with every later event until `reset`. Send phone numbers in international format, for example `+919876543210`. Contact details belong in `identify` only.
## Consent and opt-out
To wait for consent, pass `requireConsent` to the provider and call `setConsent(true)` from your consent banner:
```tsx
// in your consent banner
const lemu = useLemu();
lemu.setConsent(true);
```
Nothing is sent or stored until then. `lemu.optOut()` and `lemu.optIn()` turn tracking off and on, remembered in the browser. See [Consent and opt-out](https://docs.lemuai.com/sdks/javascript#consent-and-opt-out) for the details.
## Debug mode
```tsx
```
Every call, request and response is logged to the browser console with a `[lemu]` prefix.
## API
| Export | What it is |
|---|---|
| `LemuProvider` | Props: `writeKey`, `options` (see [options](https://docs.lemuai.com/sdks/javascript#options)), and an optional `client` from `createLemu()`. Starts tracking after mount |
| `useLemu()` | The client: `track`, `page`, `purchase`, `identify`, `reset`, `flush`, `setConsent`, `optOut`, `optIn`, `anonymousId` |
| `usePageTracking(pathname, properties?)` | Records a page view on every path change |
| `LemuEvent` | Standard event names. See the [event reference](https://docs.lemuai.com/sdks/events) |
| `createLemu()` | A separate client, for sending to a second source |
---
# React Native and Expo
> Add Lemu to a React Native or Expo app with @lemuai/react-native: events, purchases, known users, screens, app installs and opens, and deep links
URL: https://docs.lemuai.com/sdks/react-native
`@lemuai/react-native` sends events, purchases, known users and screens from your React Native or Expo app, and records installs, app opens and the deep links that bring people in. It's pure JavaScript with no native module of its own, so it works in Expo Go and in bare React Native apps.
You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).
## Install
**React Native**
```bash
npm install @lemuai/react-native @react-native-async-storage/async-storage
# optional, for the app version, bundle id and device model:
npm install react-native-device-info
```
**Expo**
```bash
npx expo install @lemuai/react-native @react-native-async-storage/async-storage
```
`react-native-device-info` needs a development build in Expo. Without it, pass the app details yourself (see below).
## Set up
Call `init` once, as early as possible, for example in `index.js` or your root component:
```tsx
import { lemu } from "@lemuai/react-native";
lemu.init("lpk_...");
```
Calls made before storage has loaded are kept and sent in order.
Without `react-native-device-info`, for example in Expo Go, pass the app version, build and id yourself:
```tsx
import * as Application from "expo-application";
import { lemu } from "@lemuai/react-native";
lemu.init("lpk_...", {
appVersion: Application.nativeApplicationVersion ?? undefined,
appBuild: Application.nativeBuildVersion ?? undefined,
appNamespace: "com.brand.app",
});
```
**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), Lemu refuses events that don't carry an allowed app id. The SDK reads the id from `react-native-device-info`. Without that package, set `appNamespace` to your bundle id or package name, or leave **Allowed apps** empty.
## Send events
```tsx
import { lemu, LemuEvent } from "@lemuai/react-native";
lemu.track(LemuEvent.AddToCart, { value: 999, currency: "INR", content_ids: ["SKU1"] });
lemu.track("coupon_applied", { code: "DIWALI10" });
```
`LemuEvent` has a constant for each of Meta's standard events and for the app events. Any other name works as a custom event. See the [event reference](https://docs.lemuai.com/sdks/events).
Keep contact details out of event properties. Lemu removes them. Send them with `identify` instead.
## Purchases
```tsx
lemu.purchase({
value: 1499.5,
currency: "INR",
order_id: "1042",
contents: [{ id: "SKU1", quantity: 1, item_price: 1499.5 }],
});
```
`purchase` sends a `Purchase` event and sends the queue right away. Always pass the order id your backend uses: the same order is often reported by the app, your backend and your payment provider, and Lemu counts one conversion per `order_id`. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).
## Identify users
```tsx
// after sign-up or login
lemu.identify("crm-123", { email: "asha@example.com", phone: "+919876543210", first_name: "Asha" });
// on logout
lemu.reset();
```
The user id is stored and sent with every later event, across restarts, until `reset`. `reset` also starts a new anonymous id.
## Screens
Screens aren't tracked automatically. Send one yourself:
```tsx
lemu.screen("Checkout", { step: 2 });
```
Or record every route change in React Navigation:
```tsx
import { NavigationContainer, useNavigationContainerRef } from "@react-navigation/native";
import { useLemuNavigationTracking } from "@lemuai/react-native";
export function App() {
const navigationRef = useNavigationContainerRef();
useLemuNavigationTracking(navigationRef);
return {/* screens */};
}
```
Outside a component, `trackNavigationState(navigationRef)` does the same and returns a function that stops it. Only the route name is sent, not route params, because params can hold personal data. Screens are stored as `screen_viewed`.
## App events and deep links
The SDK sends these for you:
| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch | `version`, `build` |
| `app_updated` | First launch after the version or build changed | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Every launch and every return from the background | `from_background`, and `url` when a link opened the app |
| `app_backgrounded` | The app goes to the background. Queued events are sent then too | |
| `deep_link_opened` | A link opens the app or arrives while it runs | `url`, `referrer` |
UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`) and `gclid` / `fbclid` in a deep link are kept with that event and every later event in the session, so Lemu can credit what happens next, such as a purchase, to the campaign.
Turn these off with `trackLifecycle: false` and `trackDeepLinks: false`.
## Consent and opt-out
```tsx
lemu.init("lpk_...", { requireConsent: true });
// once the user agrees
lemu.setConsent(true);
```
- Until consent, nothing is sent and nothing is written to storage, not even the anonymous id. Up to 50 events wait in memory and are sent on consent.
- `setConsent(false)` discards them. A granted consent is remembered across launches, and `setConsent(false)` forgets it.
- `lemu.optOut()` stops all tracking and is remembered across launches. `lemu.optIn()` resumes.
## Debug mode
```tsx
lemu.init("lpk_...", { debug: true });
```
Every call, request and response is logged with a `[lemu]` prefix. Bad arguments are logged and ignored; the SDK never throws into your app.
## Options
| Option | Default | What it does |
|---|---|---|
| `apiHost` | `https://app.lemuai.com` | Where to send events |
| `debug` | `false` | Logs calls, requests and responses |
| `requireConsent` | `false` | Holds events until `setConsent(true)` |
| `trackLifecycle` | `true` | `app_installed`, `app_updated`, `app_opened`, `app_backgrounded` |
| `trackDeepLinks` | `true` | `deep_link_opened` and campaign parameters from links |
| `flushAt` | `20` | Sends when this many events are queued |
| `flushInterval` | `30000` | Sends queued events after this many milliseconds |
| `maxQueueSize` | `1000` | The most events kept on the device |
| `appVersion`, `appBuild` | from `react-native-device-info` | Set them when that package isn't installed |
| `appName`, `appNamespace` | from `react-native-device-info` | The app's name, and its bundle id or package name |
| `storage` | AsyncStorage | Any `{ get, set, remove }` storage, for example MMKV |
| `deviceInfo` | found automatically | Pass `react-native-device-info` yourself |
## API
`init(writeKey, options?)`, `track(event, properties?)`, `screen(name, properties?)`, `purchase({ value, currency, order_id, ... })`, `identify(userId?, traits?)`, `reset()`, `flush()`, `setConsent(granted)`, `optOut()`, `optIn()` and `anonymousId()`, plus `useLemuNavigationTracking`, `trackNavigationState`, `createLemu()` for a separate client, and `LemuEvent`.
## Offline and delivery
Events are kept in AsyncStorage (or the storage you pass) and survive restarts. They are sent every 30 seconds, every 20 events, when the app goes to the background, and right after a purchase. Failed requests are retried with increasing waits, up to 5 minutes apart. At most 1,000 events are kept; when the queue is full, the oldest event that isn't a purchase is dropped. Events older than 7 days are dropped.
Requests carry a `User-Agent` such as `lemu-react-native/1.0.0 (iOS 17.4; iPhone15,2)`. No advertising ids or hardware ids are collected. For app store forms, the SDK collects the same data as the native SDKs, so the answers under [Google Play data safety](https://docs.lemuai.com/sdks/android#google-play-data-safety) and [App Privacy answers in App Store Connect](https://docs.lemuai.com/sdks/ios#app-privacy-answers-in-app-store-connect) apply.
---
# Android
> Add Lemu to an Android app in Kotlin or Java: events, purchases, known users, screens, installs, deep links and the Play install referrer
URL: https://docs.lemuai.com/sdks/android
The Android SDK sends events, purchases, known users and screens from your app, and records installs, app opens and the links and Play Store campaigns that bring people in.
- Kotlin, and works from Java. Android 5.0 (API 21) or later.
- One small AndroidX dependency (`androidx.lifecycle:lifecycle-process`). No OkHttp, Retrofit or Gson, so nothing clashes with your app's versions.
- Events are kept on disk, batched, and retried when the network is back.
- No advertising id and no hardware ids.
You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).
## Install
The SDK is on Maven Central. In your app module's `build.gradle.kts`:
```kotlin
dependencies {
implementation("com.lemuai:analytics:1.0.0")
// Optional: attribute installs to the Play Store campaign that brought the user.
implementation("com.android.installreferrer:installreferrer:2.2")
}
```
Make sure `mavenCentral()` is in your repositories. It is by default in new projects.
## Set up
Call `setup` once, in `Application.onCreate()`:
**Kotlin**
```kotlin
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
Lemu.setup(this, "lpk_...", LemuOptions(debug = BuildConfig.DEBUG))
}
}
```
**Java**
```java
Lemu.setup(this, "lpk_...", LemuOptions.builder().debug(BuildConfig.DEBUG).build());
```
If your app runs code in more than one process, call `setup` in the main process only.
**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), add your app's package name (its `applicationId`). Builds with an `applicationIdSuffix`, such as `com.brand.app.debug`, send that id, so add it too or use a separate source for testing.
### Options
| Option | Default | What it does |
|---|---|---|
| `apiHost` | `https://app.lemuai.com` | Where to send events. Change it only if your source's setup steps show another host |
| `debug` | `false` | Logs every call, request and response to Logcat with the tag `Lemu` |
| `requireConsent` | `false` | Sends and stores nothing until `setConsent(true)` |
| `trackLifecycleEvents` | `true` | `app_installed`, `app_updated`, `app_opened`, `app_backgrounded` |
| `trackDeepLinks` | `true` | `deep_link_opened` for links that open an activity, and their campaign parameters |
| `collectInstallReferrer` | `true` | Reads the Play install referrer on first launch, when the library is in your app |
| `trackActivityScreens` | `false` | Sends a screen each time an activity starts |
| `flushAt` | `20` | Sends when this many events are queued |
| `flushIntervalSeconds` | `30` | Sends at least this often while events are queued |
| `maxQueueSize` | `1000` | The most events kept on the device while offline |
## Send events
```kotlin
Lemu.track(LemuEvent.ADD_TO_CART, mapOf(
"value" to 999,
"currency" to "INR",
"content_ids" to listOf("SKU1"),
"content_type" to "product",
))
Lemu.track("coupon_applied", mapOf("code" to "DIWALI10"))
```
Any event name works. For Meta's standard events, use the `LemuEvent` constants (`VIEW_CONTENT`, `ADD_TO_CART`, `INITIATE_CHECKOUT`, `PURCHASE` and the rest) so the names match exactly. See the [event reference](https://docs.lemuai.com/sdks/events).
Keep contact details such as email, phone and address out of event properties. Lemu removes them. Send them with `identify` instead.
## Purchases
```kotlin
Lemu.purchase(
value = 1499.5,
currency = "INR",
orderId = "1042",
contents = listOf(LemuContent(id = "SKU1", quantity = 1, itemPrice = 1499.5)),
contentIds = listOf("SKU1"),
numItems = 1,
properties = mapOf("payment_method" to "cod"),
)
```
`purchase` sends a `Purchase` event straight away instead of waiting for the next batch. `value`, `currency` and `orderId` are what Lemu calculates journey and campaign revenue and ROI from.
**Always pass `orderId`.** The same order is often reported by the app, your website, Shopify or your server. Lemu counts one conversion per order id, so use the same id your backend and store use. Without it, every report counts as a separate sale. The app can be closed right after payment, so for the most reliable numbers [send purchases from your server too](https://docs.lemuai.com/website-pixel/standard-events#send-purchases-from-your-server-too). With the same order id, both count once.
With `debug` on, `track("Purchase", ...)` without `value`, `currency` or `order_id` logs a warning. The event is still sent.
## Identify users
When a user signs in or gives you their details:
```kotlin
Lemu.identify("user-829", mapOf(
"email" to "asha@example.com",
"phone" to "+919812345678",
"first_name" to "Asha",
"last_name" to "Rao",
))
```
The user id is sent with every later event until `reset()`. Send phone numbers in international format. On logout:
```kotlin
Lemu.reset() // new anonymous id, user id cleared
```
`Lemu.anonymousId` returns the random id the SDK created for this install.
## Screens
```kotlin
Lemu.screen("Checkout", mapOf("step" to 2))
```
Screens are stored as `screen_viewed` and aren't tracked automatically. To send one each time an activity starts, set `trackActivityScreens = true`, or register the tracker yourself to choose the names:
```kotlin
LemuActivityScreenTracker.register(this) { activity -> activity.title?.toString() }
```
Apps built on one activity with Compose or Fragments should call `Lemu.screen()` from their navigation.
## Deep links
Links that start an activity (`ACTION_VIEW` with a URL) are recorded as `deep_link_opened` with the `url` and `referrer`. UTM parameters (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`) and `gclid` / `fbclid` in the link become the campaign for this and later events in the session, so a purchase made after tapping a campaign link is credited to that campaign.
Links delivered to an activity that is already running arrive in `onNewIntent`, which the SDK can't see. Record those yourself:
```kotlin
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
Lemu.trackDeepLink(intent)
}
```
## Install referrer
With `com.android.installreferrer:installreferrer` in your app (see [Install](#install)), the SDK reads the Play install referrer on the first launch. The campaign the user arrived with, for example from a Google Ads or Meta app campaign link to the Play Store, is added to `app_installed` and the rest of that first session. `app_installed` waits up to 10 seconds for the referrer. Without the library this is skipped. Set `collectInstallReferrer = false` to turn it off.
## App lifecycle events
Sent for you unless you set `trackLifecycleEvents = false`:
| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch with the SDK | `version`, `build` |
| `app_updated` | First launch after the version changes | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Every time the app comes to the foreground | `from_background`, and `url` when a link opened the app |
| `app_backgrounded` | The app goes to the background. Queued events are sent then | |
If you add the SDK to an app people already have, the first launch after they update counts as `app_installed`.
## Consent and opt-out
If you need consent before tracking, for example under GDPR or the DPDP Act:
```kotlin
Lemu.setup(this, "lpk_...", LemuOptions(requireConsent = true))
// later, from your consent screen
Lemu.setConsent(true) // sends what was held and starts tracking
Lemu.setConsent(false) // discards held and queued events
```
Until consent, nothing is sent and nothing is written to the device, not even the anonymous id. Up to 50 events wait in memory and are sent once consent is given. A granted consent is remembered across launches; call `setConsent(false)` if the user withdraws it.
To let users switch tracking off entirely:
```kotlin
Lemu.optOut() // stops everything, clears queued events, remembered across launches
Lemu.optIn() // turns it back on
```
## Debug logging
```kotlin
LemuOptions(debug = true)
```
Every call, request body and server response is logged to Logcat with the tag `Lemu`. Use it during development only, because event properties and traits appear in the log. A refused request (an unknown write key, or an app that isn't in **Allowed apps**) is logged too.
## Delivery
- Events are sent in batches of up to 50: every 30 seconds, when 20 are queued, when the app goes to the background, and right after a purchase. `Lemu.flush()` sends now.
- Events are stored in the app's no-backup files directory, so they survive restarts and aren't copied to other devices by Auto Backup. At most 1,000 are kept; when full, the oldest are dropped first, purchases last. Events older than 7 days are dropped.
- Failed requests are retried with increasing waits, up to 5 minutes apart, for up to 20 hours. Refused batches are dropped and logged in debug mode.
- The SDK never throws into your app. A bad argument is logged in debug mode and ignored.
The SDK ships its own ProGuard and R8 rules, so you don't need to add any.
## Google Play data safety
Your answers depend on how you use the SDK. With the SDK alone, this is what it collects and sends to Lemu:
| Play data type | Collected | When | Purpose |
|---|---|---|---|
| Device or other IDs | Yes | Always: a random anonymous id created by the SDK for this install (not an advertising id or a hardware id) | Analytics |
| App activity: App interactions | Yes | Always: lifecycle events, screens and the events you track | Analytics |
| App activity: Other actions | If you track them | Searches, sign-ups and other custom events | Analytics |
| Financial info: Purchase history | If you send purchases | Order value, currency, order id, items | Analytics |
| Personal info: User IDs | If you call `identify` with a user id | Your own user id | Analytics, App functionality |
| Personal info: Name, Email address, Phone number | If you pass them to `identify` | The traits you send | Analytics, and Advertising or marketing if you message users from Lemu |
Also sent with every event, and not a Play data type: app name, version, build and package name; device manufacturer, model and type; Android version; screen size and density; locale and time zone; the link that opened the app and its campaign parameters.
Not collected: advertising id (GAID), Android ID, IMEI, serial number, MAC address, location, contacts, photos, files and crash logs.
- **Is data encrypted in transit?** Yes, it is sent over HTTPS.
- **Is data shared?** Lemu processes it as your service provider. Under Play's definitions, that isn't sharing. If you forward conversions to an ad platform, that is.
- **Is collection optional?** Yes, if you use `requireConsent` or offer `optOut()`.
## Java
Every method is static on `Lemu` and has Java overloads:
```java
Map props = new HashMap<>();
props.put("value", 999);
props.put("currency", "INR");
Lemu.track(LemuEvent.ADD_TO_CART, props);
Lemu.purchase(1499.5, "INR", "1042");
```
---
# iOS
> Add Lemu to an iOS or tvOS app in Swift or Objective-C: events, purchases, known users, screens, app opens, deep links and App Store privacy answers
URL: https://docs.lemuai.com/sdks/ios
The iOS SDK (`LemuAnalytics`) sends events, purchases, known users and screens from your iOS or tvOS app, and records app opens and the deep links that bring people in.
- iOS 13 or later, tvOS 13 or later. Swift and Objective-C.
- No third-party dependencies.
- No advertising identifier (IDFA), no IDFV, and no AdSupport or App Tracking Transparency.
- Events are kept on disk and sent in batches, so nothing is lost offline.
You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).
## Install
**Swift Package Manager**
In Xcode, choose **File > Add Package Dependencies...** and enter:
```text
https://github.com/LemuAI/lemu-sdks
```
Choose **Up to Next Major Version** from `1.0.0` and add the `LemuAnalytics` library to your app target.
In a `Package.swift`:
```swift
dependencies: [
.package(url: "https://github.com/LemuAI/lemu-sdks", from: "1.0.0"),
],
targets: [
.target(name: "MyApp", dependencies: [
.product(name: "LemuAnalytics", package: "lemu-sdks"),
]),
]
```
**CocoaPods**
```ruby
pod 'LemuAnalytics', '~> 1.0'
```
Then run `pod install`.
## Set up
Call `setup` once, as early as possible, so the first app open is recorded.
**SwiftUI**
```swift
import LemuAnalytics
import SwiftUI
@main
struct BrandApp: App {
init() {
Lemu.setup(writeKey: "lpk_...")
}
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in Lemu.trackDeepLink(url) }
}
}
}
```
**UIKit**
```swift
import LemuAnalytics
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Lemu.setup(writeKey: "lpk_...")
return true
}
```
**Objective-C**
```objc
@import LemuAnalytics;
LemuOptions *options = [LemuOptions new];
options.debug = YES;
[Lemu setupWithWriteKey:@"lpk_..." options:options];
```
Every `Lemu` method can be called from any thread, and none of them throws. A bad argument, such as an empty event name or a value JSON can't hold, is skipped and logged when `debug` is on.
**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), add your app's bundle identifier, for example `com.brand.app`. Events from any other bundle id are refused.
### Options
Pass options with `Lemu.setup(writeKey: "lpk_...", options: LemuOptions(debug: true))`. All are optional:
| Option | Default | What it does |
|---|---|---|
| `apiHost` | `https://app.lemuai.com` | Where to send events. Change it only if your source's setup steps show another host |
| `debug` | `false` | Logs every call, request and response |
| `requireConsent` | `false` | Sends and stores nothing until `Lemu.setConsent(true)` |
| `flushAt` | `20` | Sends once this many events are queued |
| `flushInterval` | `30` | Sends queued events every this many seconds |
| `maxQueueSize` | `1000` | The most events kept on the device while offline |
| `trackLifecycle` | `true` | `app_installed`, `app_updated`, `app_opened`, `app_backgrounded` |
| `trackDeepLinks` | `true` | `deep_link_opened` from `Lemu.trackDeepLink(_:)` |
## Send events
```swift
Lemu.track(LemuEvent.addToCart, properties: [
"value": 999,
"currency": "INR",
"content_ids": ["SKU1"],
])
Lemu.track("wishlist_shared", properties: ["list_size": 4])
```
Any event name works. For Meta's standard events, use the `LemuEvent` constants (`viewContent`, `addToCart`, `initiateCheckout`, `purchase` and the rest) so the names match exactly. If you already send these events to Meta, the same properties work here. See the [event reference](https://docs.lemuai.com/sdks/events).
Keep contact details out of event properties. Lemu removes keys such as `email`, `phone`, `address` and `password`; send contact details with `identify` instead.
## Purchases
```swift
Lemu.purchase(
value: 1499.5,
currency: "INR",
orderId: "1042",
contents: [LemuContent(id: "SKU1", quantity: 1, itemPrice: 1499.5, title: "Kurta")],
properties: ["payment_method": "cod", "coupon": "DIWALI10"]
)
```
`purchase` sends a `Purchase` event straight away instead of waiting for the next batch. `content_ids` and `num_items` are filled in from `contents` when you don't pass them.
**Always pass `orderId`.** Lemu counts one conversion per order. The same order is often reported more than once: by the app, your website, a Shopify webhook, or the app again after a retry. With the order id these count as one order, so journey and campaign revenue isn't counted twice. `value` and `currency` are needed to show revenue at all. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).
## Identify users
When someone signs in or gives you their contact details:
```swift
Lemu.identify(userId: "cust_8812", traits: [
"email": "asha@example.com",
"phone": "+919876543210",
"first_name": "Asha",
"last_name": "Rao",
])
```
`userId` is your own id for the customer. It's stored and sent with every later event until `reset()`. Send phone numbers in international format. On logout:
```swift
Lemu.reset() // new anonymous id, user id cleared
```
`Lemu.anonymousId` returns the id Lemu uses for this install, for example to pass to your backend so server-side events join up with the app's.
## Screens
**SwiftUI**
```swift
CheckoutView()
.lemuScreen("Checkout")
ProductView(product: product)
.lemuScreen("Product", properties: ["product_id": product.id])
```
**UIKit**
Turn on automatic screen tracking (it's off by default):
```swift
Lemu.enableAutomaticScreenTracking()
```
Each of your view controllers sends a screen when it appears, named after its class without the `ViewController` suffix (`CheckoutViewController` becomes `Checkout`). Navigation, tab bar, split and page controllers, Apple's own controllers, SwiftUI hosting controllers and child controllers embedded in your own are skipped. To rename a screen, or skip one:
```swift
extension CheckoutViewController: LemuScreenNameProviding {
var lemuScreenName: String? { "Checkout" } // return nil to send nothing
}
```
**Anywhere**
```swift
Lemu.screen("Checkout", properties: ["step": 2])
```
Screens are stored as `screen_viewed`.
## Deep links and campaigns
Pass every URL that opens the app to `trackDeepLink`. It sends `deep_link_opened` with the `url`, and keeps `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `gclid` and `fbclid` with this and every later event in the session, so a purchase made after tapping a campaign link is credited to that campaign.
```swift
// SwiftUI
WindowGroup { ContentView().onOpenURL { Lemu.trackDeepLink($0) } }
// UIKit, AppDelegate
func application(_ app: UIApplication, open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
Lemu.trackDeepLink(url, referrer: options[.sourceApplication] as? String)
return true
}
// UIKit, SceneDelegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set) {
URLContexts.forEach { Lemu.trackDeepLink($0.url, referrer: $0.options.sourceApplication) }
}
// Universal links
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
if let url = userActivity.webpageURL { Lemu.trackDeepLink(url) }
}
```
For a cold launch from a link with scenes, also pass the URLs in `scene(_:willConnectTo:options:)` (`connectionOptions.urlContexts` and `connectionOptions.userActivities`). The next `app_opened` carries the link as `url`.
## App lifecycle events
Sent for you unless you set `trackLifecycle: false`:
| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch with the SDK | `version`, `build` |
| `app_updated` | First launch after the version or build changed | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Every time the app comes to the foreground | `from_background`, and `url` when a link opened the app |
| `app_backgrounded` | The app goes to the background | |
If your app had users before you added the SDK, each of them sends `app_installed` once after updating, because the SDK has no record of an earlier version.
## Consent and opt-out
If you must ask before collecting data, start with `requireConsent`:
```swift
Lemu.setup(writeKey: "lpk_...", options: LemuOptions(requireConsent: true))
// later, from your consent prompt
Lemu.setConsent(true) // sends events held since launch, and remembers the answer
Lemu.setConsent(false) // discards held and queued events
```
Until consent, nothing is sent and nothing is written to the device, not even the anonymous id. Up to 50 events are held in memory and sent if consent is given. A granted consent is remembered across launches; call `setConsent(false)` to withdraw it.
To let people turn tracking off in your settings screen:
```swift
Lemu.optOut() // stops everything, clears the queue, remembered across launches
Lemu.optIn() // turns it back on
Lemu.isOptedOut
```
## Debug logging
```swift
Lemu.setup(writeKey: "lpk_...", options: LemuOptions(debug: true))
```
Every call, request body and response is logged with `os_log` under the subsystem `com.lemuai.analytics`. Watch it in the Xcode console, or in Console.app filtered by that subsystem. Turn `debug` off in release builds.
## Delivery
- Events are kept in `Application Support/Lemu`, excluded from iCloud and device backups, and survive restarts.
- They are sent every 30 seconds, when 20 are queued, when the app goes to the background, and right after a purchase. `Lemu.flush()` sends now.
- Each request carries up to 50 events. Failed requests are retried with increasing waits, up to 5 minutes apart, for up to 20 hours. Events older than 7 days are dropped.
- The queue holds at most 1,000 events. When it's full, the oldest event that isn't a purchase is dropped first.
## App Store privacy
### Privacy manifest
The SDK ships its own privacy manifest (`PrivacyInfo.xcprivacy`, in the package and in the CocoaPods resource bundle `LemuAnalyticsPrivacy`). Xcode adds it to your app's privacy report. It declares:
- `NSPrivacyTracking`: `false`, with no tracking domains.
- Required reason API: UserDefaults, reason `CA92.1`. The SDK keeps its anonymous id, user id, opt-out, consent and the last app version in its own UserDefaults suite.
- Collected data, all linked to the user and none used for tracking:
| Data type | Why it's collected | Purposes |
|---|---|---|
| User ID | The anonymous install id, and your `userId` from `identify` | Analytics, Developer's Advertising or Marketing |
| Email address, phone number, name | Only if you pass them to `identify` | Analytics, Developer's Advertising or Marketing |
| Product interaction | Events, screens, app opens | Analytics, Developer's Advertising or Marketing |
| Purchase history | `purchase()` and other commerce events | Analytics, Developer's Advertising or Marketing |
| Other usage data | Lifecycle and custom events | Analytics |
### App Privacy answers in App Store Connect
Your app's privacy label covers all the data your app collects, including through Lemu. For the data that goes to Lemu:
- **Data used to track you: No.** Lemu doesn't use advertising identifiers, doesn't share data with data brokers, and doesn't link your app's data with other companies' data for advertising. See the note below if you forward data to ad networks.
- **Data linked to you**, for each type you actually send:
- Contact Info > **Email Address**, **Phone Number**, **Name**: if you call `identify` with them.
- Identifiers > **User ID**: yes. The SDK always sends an anonymous id, plus your own user id.
- Purchases > **Purchase History**: if you call `purchase()` or send commerce events.
- Usage Data > **Product Interaction**: yes (app opens, screens, events).
- Usage Data > **Other Usage Data**: if you send custom events.
- **Purposes:** **Analytics**, plus **Developer's Advertising or Marketing** if you message these customers through Lemu journeys or campaigns. Add **App Functionality** if your app relies on Lemu data to work.
- **Not collected by the SDK:** location, device ids (IDFA or IDFV), diagnostics, contacts, health, financial info, browsing history, and search history unless you send search terms as events (then also declare Search History).
**Forwarding to ad networks.** If you send Lemu events to an advertising platform, for example through a Meta Conversions API connection, Apple counts that as tracking. Then answer "Data used to track you: Yes" for the shared types, ask permission with App Tracking Transparency first, and only call `identify` with an email or phone after the user allows it.
## Objective-C
```objc
@import LemuAnalytics;
[Lemu track:LemuEvent.addToCart properties:@{@"value": @999, @"currency": @"INR"}];
[Lemu identifyWithUserId:@"cust_8812" traits:@{@"email": @"asha@example.com"}];
[Lemu purchaseWithValue:1499.5 currency:@"INR" orderId:@"1042"
contents:@[[[LemuContent alloc] initWithId:@"SKU1" quantity:1 itemPrice:@1499.5 title:nil]]
properties:nil];
[Lemu trackDeepLink:url referrer:nil];
[Lemu setConsent:YES];
```
---
# Flutter
> Add Lemu to a Flutter app on Android, iOS, web and desktop with lemu_analytics: events, purchases, known users, screens, app lifecycle and deep links
URL: https://docs.lemuai.com/sdks/flutter
The Flutter SDK (`lemu_analytics`) sends events, purchases, known users, app lifecycle events, deep links and screens from your Flutter app.
- Pure Dart, with no platform channels of its own. Works on Android, iOS, web, macOS, Windows and Linux.
- Events are kept on the device, sent in batches, retried when the network fails, and kept across restarts.
- Meta's standard event names, so ad platforms receive conversions unchanged.
- Consent and opt-out built in. No advertising ids and no hardware ids.
Requires Flutter 3.22 or later (Dart 3.4 or later). You need the write key of an **App** source. See [Get a write key](https://docs.lemuai.com/sdks/overview#get-a-write-key).
## Install
```bash
flutter pub add lemu_analytics
```
Android and iOS need no extra setup. On **macOS**, apps are sandboxed and need permission to make network requests. Add this to `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements`:
```xml
com.apple.security.network.client
```
## Set up
Call `setup` once in `main()`, before `runApp()`:
```dart
import 'package:flutter/widgets.dart';
import 'package:lemu_analytics/lemu_analytics.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Lemu.instance.setup('lpk_...');
runApp(const MyApp());
}
```
The write key is public, so it's safe to ship in the app. Calls made before `setup` are ignored. No method ever throws: a bad argument is ignored and, with `debug: true`, logged.
**Warning:** If the source lists [Allowed apps](https://docs.lemuai.com/website-pixel/overview#allowed-apps), Lemu refuses events from any other app id. On Android the id is your `applicationId`, and on iOS and macOS your bundle identifier. Web and desktop builds send a different id: if you ship them, turn on debug mode, find `namespace` under `app` in a logged request, and add it to the list too.
### Options
```dart
await Lemu.instance.setup(
'lpk_...',
options: const LemuOptions(
debug: false, // log every call, request and response
requireConsent: false, // see "Consent and opt-out"
flushAt: 20, // send once this many events are queued (web: 10)
flushInterval: Duration(seconds: 30), // and at least this often (web: 1 second)
maxQueueSize: 1000, // events kept on the device while offline (at most 1,000)
trackLifecycle: true, // app_installed, app_updated, app_opened, app_backgrounded
trackDeepLinks: true, // deep_link_opened from trackDeepLink()
),
);
```
`LemuOptions` also takes `apiHost`. Change it only if your source's setup steps show another host.
## Send events
```dart
Lemu.instance.track(LemuEvent.addToCart, {
'value': 999,
'currency': 'INR',
'content_ids': ['SKU1'],
});
Lemu.instance.track('wishlist_shared', {'list_id': 'summer'});
```
Any event name works. For Meta's standard events, use the `LemuEvent` constants (`viewContent`, `addToCart`, `initiateCheckout`, `purchase` and the rest), spelled exactly as Meta expects. See the [event reference](https://docs.lemuai.com/sdks/events).
Don't put email addresses, phone numbers or other contact details in event properties. Lemu removes them; they belong in `identify()`.
## Purchases
```dart
Lemu.instance.purchase(
value: 1499.5,
currency: 'INR',
orderId: '1042',
contents: const [
LemuContent(id: 'SKU1', quantity: 1, itemPrice: 999, title: 'Kurta'),
LemuContent(id: 'SKU7', quantity: 1, itemPrice: 500.5),
],
properties: {'coupon': 'DIWALI10'},
);
```
`purchase()` sends a `Purchase` event right away instead of waiting for the next batch. `content_ids` and `num_items` are filled in from `contents` when you don't pass them.
**Always pass the order id from your backend.** The same order is often reported by more than one source: the app, your website, your server, Shopify. Lemu counts one conversion per order id, so revenue isn't counted twice and journeys don't fire twice. Without it, every report counts. See [Conversion events](https://docs.lemuai.com/website-pixel/standard-events#conversion-events).
## Identify users
When a user signs in or signs up:
```dart
Lemu.instance.identify(
userId: 'cust_8812', // your own id for this user
traits: {
'email': 'asha@example.com',
'phone': '+919812345678', // international format
'first_name': 'Asha',
'last_name': 'Rao',
},
);
```
The `userId` is kept and sent with every later event, also after the app restarts. On logout:
```dart
Lemu.instance.reset(); // new anonymous id, no user id
```
`Lemu.instance.anonymousId` is the id Lemu uses for this install before the user is known.
## Screens
Add `LemuNavigatorObserver` to your navigator to send a screen each time a named page becomes visible:
**Navigator**
```dart
MaterialApp(
navigatorObservers: [LemuNavigatorObserver()],
routes: {...},
);
```
**go_router**
```dart
final router = GoRouter(
observers: [LemuNavigatorObserver()],
routes: [
GoRoute(name: 'product', path: '/product/:id', builder: ...),
],
);
```
go_router names each page after the `GoRoute` `name`, or its path pattern (`/product/:id`) when it has none. Routes inside a `ShellRoute` need the observer on that `ShellRoute` too.
Dialogs, bottom sheets and unnamed routes are skipped. To choose names yourself:
```dart
LemuNavigatorObserver(
nameExtractor: (route) => route.settings.name?.replaceAll('/', ' ').trim(),
)
```
Or send screens yourself:
```dart
Lemu.instance.screen('Checkout', {'step': 2});
```
Screens are stored as `screen_viewed`.
## Deep links and campaigns
Pass each link that opens the app to `trackDeepLink`. It sends `deep_link_opened` and keeps the link's `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`, `gclid` and `fbclid` with every later event in the session, so later events, including the purchase, are credited to the campaign.
**app_links**
The [app_links](https://pub.dev/packages/app_links) stream also delivers the link that launched the app:
```dart
final appLinks = AppLinks();
appLinks.uriLinkStream.listen((uri) => Lemu.instance.trackDeepLink(uri));
```
**go_router**
Track links in the top-level `redirect`. It also runs for in-app navigation, so only track URLs that carry campaign parameters, once each:
```dart
Uri? lastTrackedLink;
final router = GoRouter(
redirect: (context, state) {
final uri = state.uri;
final hasCampaign = uri.queryParameters.keys
.any((k) => k.startsWith('utm_') || k == 'gclid' || k == 'fbclid');
if (hasCampaign && uri != lastTrackedLink) {
lastTrackedLink = uri;
Lemu.instance.trackDeepLink(uri);
}
return null;
},
routes: [...],
);
```
`trackDeepLink(uri, referrer: 'com.instagram.android')` records where the link came from, when you know it.
## App lifecycle events
Unless you set `trackLifecycle: false`, the SDK sends:
| Event | When | Properties |
|---|---|---|
| `app_installed` | First launch | `version`, `build` |
| `app_updated` | First launch after the version or build changed | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | Launch and every return to the foreground | `from_background` |
| `app_backgrounded` | The app goes to the background | |
Queued events are sent when the app goes to the background, with or without lifecycle events. If you add the SDK to an app people already have, each of them sends `app_installed` once, on their first launch with the SDK.
## Consent and opt-out
If you must ask before tracking, for example under GDPR or the DPDP Act, set `requireConsent: true`. Nothing is sent and nothing is written to the device, not even the anonymous id, until the user agrees. Up to 50 events are held in memory meanwhile.
```dart
await Lemu.instance.setup('lpk_...',
options: const LemuOptions(requireConsent: true));
// later, from your consent screen
Lemu.instance.setConsent(true); // sends the held events; remembered across launches
Lemu.instance.setConsent(false); // discards held and queued events
```
To stop all tracking for a user who opts out in your settings screen:
```dart
Lemu.instance.optOut(); // clears the queue, remembered across launches
Lemu.instance.optIn(); // resumes
```
## Flutter web
On the web, the SDK reuses the visitor id of the Lemu [website snippet](https://docs.lemuai.com/sdks/javascript) (the `_lemu_aid` cookie and local storage key) when the Flutter app runs on the same site. A visitor who browses your website and then your Flutter web app is one visitor, and a visitor who opted out on the website stays opted out. Events are sent every second or every 10 events.
## Debugging
```dart
await Lemu.instance.setup('lpk_...',
options: const LemuOptions(debug: true));
```
Every call, request body and response status is printed with a `[Lemu]` prefix through `debugPrint`. `Lemu.instance.flush()` sends the queue immediately, which helps while testing. To see what Lemu stored, open the source in **Settings → Tracking Sources** and use [Recent events](https://docs.lemuai.com/website-pixel/overview#recent-events).
## How sending works
- Events are kept on the device (in shared_preferences) and survive restarts. At most 1,000 are kept; when full, the oldest event that isn't a `Purchase` is dropped. Events older than 7 days are dropped before sending.
- Each request carries up to 50 events. Apps send every 30 seconds or 20 events, when going to the background, and right after a purchase. The web sends every second or 10 events.
- Network errors, timeouts and server errors are retried with increasing waits, up to 5 minutes apart. A batch that keeps failing is dropped 20 hours after it was queued. Refused batches are dropped and the reason is logged in debug mode.
- Every request has the User-Agent `lemu-flutter/ (; )`, except on the web, where the browser sets its own.
## Privacy and store forms
What the SDK collects:
- A random anonymous id created on first launch and stored in the app's preferences. It isn't derived from the device and is replaced on `reset()` or reinstall.
- The events and properties your code sends, plus the `userId` and traits you pass to `identify()`.
- App name, version, build and package name; device manufacturer, model and type; OS name and version; screen size and pixel density; locale; time zone; campaign parameters from deep links.
It doesn't collect advertising ids (IDFA, GAID), hardware or vendor ids (Android ID, `identifierForVendor`), location, contacts, or anything else you don't send.
Your store answers depend on what your app sends and how your Lemu workspace uses it. The Flutter SDK collects the same data as the native SDKs, so the answers under [Google Play data safety](https://docs.lemuai.com/sdks/android#google-play-data-safety) and [App Privacy answers in App Store Connect](https://docs.lemuai.com/sdks/ios#app-privacy-answers-in-app-store-connect) apply. The Flutter SDK reads no advertising identifier and doesn't need the App Tracking Transparency prompt to work. If your workspace forwards conversions to ad platforms, for example through the Meta Conversions API, both stores count that as tracking or sharing: declare it, and follow Apple's App Tracking Transparency rules for it.
---
# Event reference
> Every event name the Lemu SDKs send, its constant on each platform, the standard parameters, and how Lemu stores events, properties and context
URL: https://docs.lemuai.com/sdks/events
This page lists the event names every Lemu SDK knows, the constant for each one on each platform, and what Lemu keeps from each event. For the fields an order needs and how revenue and ROI are calculated, see [Standard and conversion events](https://docs.lemuai.com/website-pixel/standard-events).
## How calls are stored
| Call | Stored as |
|---|---|
| `page()` | `PageView`, with the page's `url`, `path` and `title` |
| `screen(name)` | `screen_viewed`, with the screen's `name` in its properties |
| `track(event)` and `purchase()` | The event name: Meta's spelling for a standard event, and lowercase with underscores for any other name |
| `identify()` | Finds or creates the contact (see [Known users](https://docs.lemuai.com/sdks/overview#known-users)). Traits go to the contact, never into event properties |
## Standard events
These are [Meta's standard events](https://developers.facebook.com/docs/meta-pixel/reference), with Meta's names and parameters. Every SDK has a constant for each one.
| Event | JavaScript, React, React Native | Android | iOS, Flutter | Parameters |
|---|---|---|---|---|
| `PageView` | `LemuEvent.PageView` | `LemuEvent.PAGE_VIEW` | `LemuEvent.pageView` | none. On websites, `page()` sends it |
| `ViewContent` | `LemuEvent.ViewContent` | `LemuEvent.VIEW_CONTENT` | `LemuEvent.viewContent` | `content_ids`, `content_category`, `content_name`, `content_type`, `contents`, `currency`, `value` |
| `Search` | `LemuEvent.Search` | `LemuEvent.SEARCH` | `LemuEvent.search` | `search_string`, `content_category`, `content_ids`, `contents`, `currency`, `value` |
| `AddToCart` | `LemuEvent.AddToCart` | `LemuEvent.ADD_TO_CART` | `LemuEvent.addToCart` | `content_ids`, `content_name`, `content_type`, `contents`, `currency`, `value` |
| `AddToWishlist` | `LemuEvent.AddToWishlist` | `LemuEvent.ADD_TO_WISHLIST` | `LemuEvent.addToWishlist` | `content_ids`, `content_name`, `content_category`, `contents`, `currency`, `value` |
| `InitiateCheckout` | `LemuEvent.InitiateCheckout` | `LemuEvent.INITIATE_CHECKOUT` | `LemuEvent.initiateCheckout` | `content_ids`, `content_category`, `contents`, `currency`, `num_items`, `value` |
| `AddPaymentInfo` | `LemuEvent.AddPaymentInfo` | `LemuEvent.ADD_PAYMENT_INFO` | `LemuEvent.addPaymentInfo` | `content_ids`, `content_category`, `contents`, `currency`, `value` |
| `Purchase` | `LemuEvent.Purchase` | `LemuEvent.PURCHASE` | `LemuEvent.purchase` | `value`, `currency` and `order_id` (required), `content_ids`, `content_name`, `content_type`, `contents`, `num_items`. Use `purchase()` |
| `Lead` | `LemuEvent.Lead` | `LemuEvent.LEAD` | `LemuEvent.lead` | `content_category`, `content_name`, `currency`, `value` |
| `CompleteRegistration` | `LemuEvent.CompleteRegistration` | `LemuEvent.COMPLETE_REGISTRATION` | `LemuEvent.completeRegistration` | `content_name`, `currency`, `status`, `value` |
| `Subscribe` | `LemuEvent.Subscribe` | `LemuEvent.SUBSCRIBE` | `LemuEvent.subscribe` | `currency`, `predicted_ltv`, `value` |
| `StartTrial` | `LemuEvent.StartTrial` | `LemuEvent.START_TRIAL` | `LemuEvent.startTrial` | `currency`, `predicted_ltv`, `value` |
| `Schedule` | `LemuEvent.Schedule` | `LemuEvent.SCHEDULE` | `LemuEvent.schedule` | |
| `SubmitApplication` | `LemuEvent.SubmitApplication` | `LemuEvent.SUBMIT_APPLICATION` | `LemuEvent.submitApplication` | |
| `Contact` | `LemuEvent.Contact` | `LemuEvent.CONTACT` | `LemuEvent.contact` | |
| `CustomizeProduct` | `LemuEvent.CustomizeProduct` | `LemuEvent.CUSTOMIZE_PRODUCT` | `LemuEvent.customizeProduct` | |
| `Donate` | `LemuEvent.Donate` | `LemuEvent.DONATE` | `LemuEvent.donate` | |
| `FindLocation` | `LemuEvent.FindLocation` | `LemuEvent.FIND_LOCATION` | `LemuEvent.findLocation` | |
With the website snippet, use the event name itself, for example `lemu("track", "AddToCart", { ... })`. Lemu matches a standard name whatever its case or separators, so `add_to_cart` is stored as `AddToCart`. See [Matching names](https://docs.lemuai.com/website-pixel/standard-events#matching-names).
## Parameters
| Parameter | Type | Meaning |
|---|---|---|
| `value` | number | An amount in major units: `1499.5` is ₹1,499.50. On `AddToCart`, the value of what was added. On `InitiateCheckout`, the checkout total. On `Purchase`, the order total |
| `currency` | string | An ISO 4217 code such as `INR` |
| `order_id` | string | Your id for the order. Lemu counts one conversion per order id, however many sources report it. Meta's Conversions API has the same field |
| `content_ids` | list of strings | Product ids or SKUs |
| `contents` | list of objects | Items, each with `id` and `quantity`, and optionally `item_price`, `title`, `brand` and `category` |
| `content_type` | string | `product` or `product_group` |
| `content_name` | string | A name |
| `content_category` | string | A category |
| `num_items` | integer | The number of items |
| `search_string` | string | What was searched for |
| `predicted_ltv` | number | The expected lifetime value of a subscriber |
| `status` | string | The status of a registration |
You can add your own properties next to these, for example `payment_method` or `coupon`.
The app SDKs take the order id and items as typed arguments to `purchase`: `orderId` and `LemuContent(id, quantity, itemPrice, title)` on Android, iOS and Flutter. They are sent as `order_id` and `contents` with `item_price`.
## Conversion events
A conversion event counts as an order for revenue and ROI. By default that's `Purchase`; you can add others under **Settings → Sending Limits → Conversion events**. Every conversion event needs `value`, `currency` and `order_id`.
Lemu never rejects a conversion event for a missing field. It fixes what it can, counts the rest, and shows the problem on the event in [Recent events](https://docs.lemuai.com/website-pixel/overview#recent-events). See [When a field is missing](https://docs.lemuai.com/website-pixel/standard-events#when-a-field-is-missing).
## App lifecycle events
The app SDKs (Android, iOS, Flutter and React Native) send these for you. They have no Meta equivalent and are never conversions.
| Event | JavaScript (React Native) | Android | iOS, Flutter | When | Properties |
|---|---|---|---|---|---|
| `app_installed` | `LemuEvent.AppInstalled` | `LemuEvent.APP_INSTALLED` | `LemuEvent.appInstalled` | The first launch with the SDK | `version`, `build` |
| `app_updated` | `LemuEvent.AppUpdated` | `LemuEvent.APP_UPDATED` | `LemuEvent.appUpdated` | The first launch after the version or build changed | `version`, `build`, `previous_version`, `previous_build` |
| `app_opened` | `LemuEvent.AppOpened` | `LemuEvent.APP_OPENED` | `LemuEvent.appOpened` | Every launch and every return to the foreground | `from_background`, and `url` when a link opened the app (not on Flutter) |
| `app_backgrounded` | `LemuEvent.AppBackgrounded` | `LemuEvent.APP_BACKGROUNDED` | `LemuEvent.appBackgrounded` | The app goes to the background | |
| `deep_link_opened` | `LemuEvent.DeepLinkOpened` | `LemuEvent.DEEP_LINK_OPENED` | `LemuEvent.deepLinkOpened` | A link opens the app | `url`, `referrer` |
| `screen_viewed` | `LemuEvent.ScreenViewed` | `LemuEvent.SCREEN_VIEWED` | `LemuEvent.screenViewed` | A screen is shown, when you track screens | `name`, plus your properties |
- `screen_viewed` is never sent automatically. Call `screen(name)`, or turn on your platform's screen tracking.
- Turn the first four off with `trackLifecycleEvents = false` on Android, or `trackLifecycle: false` on iOS, Flutter and React Native. Turn deep links off with `trackDeepLinks`.
- If you add the SDK to an app people already have, each of them sends `app_installed` once, on their first launch with the SDK.
On Android, the install referrer's campaign is added to `app_installed`. See [Install referrer](https://docs.lemuai.com/sdks/android#install-referrer).
## Custom events
Any name that isn't a standard event is a custom event, for example `coupon_applied` or `wishlist_shared`. Custom events are never rejected, and they work in journeys, segments and the Event Log like any other event.
Lemu stores a custom name from an SDK in lowercase with underscores, so "Coupon Applied" is stored as `coupon_applied`. Use that spelling in journeys and segments, or send it that way to begin with.
## Properties Lemu removes
Contact details belong in `identify` traits only. Lemu removes these keys from event, page and screen properties, at any depth, whatever their case: `email`, `e_mail`, `phone`, `phone_number`, `mobile`, `mobile_number`, `whatsapp`, `password`, `otp`, `card`, `card_number`, `cvv`, `pan`, `aadhaar` and `address`. The same keys are removed from the query string of page URLs and referrers.
## Context
The SDKs add context to every event. Your code never sets it. Lemu keeps:
| Context | What it holds |
|---|---|
| `platform` | `web`, `ios`, `android`, `flutter` or `react_native` |
| `library` | The SDK's name and version |
| `app` | The app's `name`, `version`, `build` and `namespace` (bundle id or package name) |
| `device` | `manufacturer`, `model`, and `type` (`phone`, `tablet`, `desktop`, `tv` or `other`) |
| `os` | The OS name and version |
| `screen` | Width, height and pixel density |
| `locale`, `timezone` | For example `en-IN` and `Asia/Kolkata` |
| `campaign` | `source`, `medium`, `campaign`, `term` and `content` from UTM parameters, plus `gclid` and `fbclid`, from the landing page, the deep link that opened the app, or the Android install referrer |
| `user_agent` | The browser's user agent, or the SDK's, such as `lemu-android/1.0.0 (Android 14; Pixel 8)` |
| `referrer` | The page's referrer, on websites |
You can see an event's context in [Recent events](https://docs.lemuai.com/website-pixel/overview#recent-events). No advertising ids and no hardware ids are sent or kept.
---
# Overview
> Trigger calls, send events, sync contacts and records, send transactional email and WhatsApp templates with the Lemu AI REST API
URL: https://docs.lemuai.com/api-reference/overview
The Lemu AI REST API covers a small, stable set of tasks:
| Task | Endpoint |
|---|---|
| Place an outbound call with a voice agent | [Trigger an outbound call](https://docs.lemuai.com/api-reference/calls/trigger) |
| Start journeys when something happens in your system | [Send an event](https://docs.lemuai.com/api-reference/events/trigger) |
| Look up your voice agents | [List agents](https://docs.lemuai.com/api-reference/agents/list) |
| See the calls a voice agent has made | [List calls](https://docs.lemuai.com/api-reference/agents/runs/list) |
| See your campaigns | [List campaigns](https://docs.lemuai.com/api-reference/campaigns/list) |
| Keep contacts in sync with your CRM | [Contacts](https://docs.lemuai.com/api-reference/contacts/overview) |
| Record a person's opt-in or opt-out for email, SMS, WhatsApp or voice | [Contact consent](https://docs.lemuai.com/api-reference/contacts/consents) |
| See everything a person did, or every message and call they got | [Contact activity](https://docs.lemuai.com/api-reference/contacts/activity) and [Contact messages](https://docs.lemuai.com/api-reference/contacts/messages) |
| Send orders, subscriptions or bookings to use in journeys and segments | [Custom records](https://docs.lemuai.com/api-reference/records/overview) |
| Send an order, shipping or account email | [Send a transactional email](https://docs.lemuai.com/api-reference/email/send) |
| Send a WhatsApp template (order update, reminder, login code, offer) to one number | [Send a WhatsApp template](https://docs.lemuai.com/api-reference/whatsapp/send-template) |
| See whether a WhatsApp message was delivered and read | [Get a WhatsApp message](https://docs.lemuai.com/api-reference/whatsapp/get-message) |
| Check which events reached LemuAI | [List events](https://docs.lemuai.com/api-reference/events/list) |
Events, contacts and records find the right person by phone number, `external_id` (your own customer ID) or email, so a contact without a phone number can still be matched. See [how the contact is found](https://docs.lemuai.com/api-reference/events/trigger#how-the-contact-is-found).
Everything else (building agents and journeys, running campaigns, recordings and transcripts) is done in the Lemu AI dashboard.
## Base URL
All requests go to:
```
https://app.lemuai.com/api/v1
```
The version (`v1`) is part of the path.
## Authentication
Every request needs an API key from your organization in the `X-API-Key` header. See [Authentication](https://docs.lemuai.com/api-reference/authentication).
**cURL**
```bash
curl https://app.lemuai.com/api/v1/workflow/fetch \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/workflow/fetch", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/workflow/fetch",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Request and response format
Send request bodies as JSON with the `Content-Type: application/json` header. Responses are JSON. Errors return a `detail` field; see [Errors](https://docs.lemuai.com/api-reference/errors).
## Getting call results
The recommended way to receive the outcome of a call (what was said, what the agent captured, how it ended) is to add a [Webhook node](https://docs.lemuai.com/voice-agent/webhook) to your agent. Lemu AI then posts the result to your system when the call finishes, so you don't need to poll.
**Note:** Connecting an AI assistant such as Claude or Cursor? Use the [MCP server](https://docs.lemuai.com/mcp/overview) instead of this REST API. It lets an assistant list your agents and place calls on your behalf, with permissions you approve.
---
# Quickstart
> Make your first LemuAI API calls in five minutes: create a key, add a contact, send an order event and start a call.
URL: https://docs.lemuai.com/api-reference/quickstart
For: Developers
Checked against LemuAI app version 1.0.12
Related: [Authentication](https://docs.lemuai.com/api-reference/authentication), [Send an Event](https://docs.lemuai.com/api-reference/events/trigger), [Webhooks](https://docs.lemuai.com/api-reference/webhooks), [Conventions](https://docs.lemuai.com/api-reference/conventions)
Everything goes to `https://app.lemuai.com/api/v1` with your key in the `X-API-Key` header and JSON bodies. The examples below read the key from the `LEMU_API_KEY` environment variable.
## 1. Create an API key
In the app, open **Settings → API Keys** and create a key. It starts with `lemu_`. Store it as a secret on your server; never put it in a website or mobile app (use [Tracking Sources](https://docs.lemuai.com/website-pixel/overview) write keys there instead).
```bash
export LEMU_API_KEY="lemu_..."
```
## 2. Add or update a contact
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/contacts/upsert \
-H "X-API-Key: $LEMU_API_KEY" \
-H "Content-Type: application/json" \
-d '{"phone": "+919876543210", "first_name": "Priya", "email": "priya@example.com", "list_name": "API quickstart"}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/upsert", {
method: "POST",
headers: { "X-API-Key": process.env.LEMU_API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ phone: "+919876543210", first_name: "Priya", email: "priya@example.com", list_name: "API quickstart" }),
});
console.log(res.status, await res.json());
```
**Python**
```python
import os, requests
r = requests.post(
"https://app.lemuai.com/api/v1/contacts/upsert",
headers={"X-API-Key": os.environ["LEMU_API_KEY"]},
json={"phone": "+919876543210", "first_name": "Priya", "email": "priya@example.com", "list_name": "API quickstart"},
timeout=30,
)
print(r.status_code, r.json())
```
The contact is matched by phone, so sending the same phone again updates them instead of adding a duplicate. `list_name` is required (the list is created if new). See [Upsert a Contact](https://docs.lemuai.com/api-reference/contacts/upsert) for every field.
## 3. Send an order event
Orders sent as `Purchase` events count toward revenue and can start journeys.
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/events \
-H "X-API-Key: $LEMU_API_KEY" \
-H "Content-Type: application/json" \
-d '{"event_type": "Purchase", "phone": "+919876543210", "data": {"order_id": "A-1001", "value": 1499, "currency": "INR"}}'
```
**JavaScript**
```js
await fetch("https://app.lemuai.com/api/v1/events", {
method: "POST",
headers: { "X-API-Key": process.env.LEMU_API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({
event_type: "Purchase",
phone: "+919876543210",
data: { order_id: "A-1001", value: 1499, currency: "INR" },
}),
});
```
**Python**
```python
requests.post(
"https://app.lemuai.com/api/v1/events",
headers={"X-API-Key": os.environ["LEMU_API_KEY"]},
json={"event_type": "Purchase", "phone": "+919876543210",
"data": {"order_id": "A-1001", "value": 1499, "currency": "INR"}},
timeout=30,
).raise_for_status()
```
Check it arrived: **Insights → Event Log** in the app, or [List Events](https://docs.lemuai.com/api-reference/events/list). See [Send an Event](https://docs.lemuai.com/api-reference/events/trigger).
## 4. Start a call
In the app, open a voice agent and add an **API Trigger** step; it shows the agent's trigger URL (with a UUID). Then:
```bash
curl -X POST https://app.lemuai.com/api/v1/public/agent/YOUR_TRIGGER_UUID \
-H "X-API-Key: $LEMU_API_KEY" \
-H "Content-Type: application/json" \
-d '{"phone_number": "+919876543210", "initial_context": {"first_name": "Priya", "order_id": "A-1001"}}'
```
The answer includes the run id. Get the result with [List Calls](https://docs.lemuai.com/api-reference/agents/runs/list), or have the agent push it to you with a [Webhook](https://docs.lemuai.com/api-reference/webhooks). See [Trigger an Outbound Call](https://docs.lemuai.com/api-reference/calls/trigger) for the exact URL and fields.
## Next
- [Webhooks](https://docs.lemuai.com/api-reference/webhooks): get call results pushed to you, and start journeys from your system.
- [Conventions](https://docs.lemuai.com/api-reference/conventions): pagination, limits, retries and idempotency.
- [Errors](https://docs.lemuai.com/api-reference/errors) and [API troubleshooting](https://docs.lemuai.com/troubleshooting/account-and-billing#api-keys).
- [OpenAPI file](https://docs.lemuai.com/openapi.json): import into Postman or generate a client.
---
# Authentication
> Authenticate Lemu AI API requests with an organization API key
URL: https://docs.lemuai.com/api-reference/authentication
## API keys
Every request is authenticated with an API key that belongs to your organization. Anything you read or create with a key belongs to that organization.
### Create a key
Create keys in the Lemu AI dashboard under **Settings → API Keys** (see [API Keys](https://docs.lemuai.com/configurations/api-keys)). The full key is shown **only once**, when you create it. Store it straight away in a secrets manager or an environment variable. Keys start with `lemu_`.
You can also archive a key from the same page. An archived key stops working immediately.
### Send the key
Pass the key in the `X-API-Key` header:
**cURL**
```bash
curl https://app.lemuai.com/api/v1/workflow/fetch \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/workflow/fetch", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/workflow/fetch",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
The `Authorization: Bearer lemu_your_api_key` header is also accepted, except on [Trigger an outbound call](https://docs.lemuai.com/api-reference/calls/trigger), which only reads `X-API-Key`. Use `X-API-Key` everywhere to keep things simple.
### What a key can do
An API key acts for your organization, not for a team member, so team roles don't limit it: a key can use every endpoint in this reference. One exception: the [contacts endpoints](https://docs.lemuai.com/api-reference/contacts/overview#hidden-phone-numbers) show full phone numbers only if the team member who created the key may view personal data.
**Warning:** An API key can act on your whole organization. Keep it on your server. Never put it in a browser, a mobile app, or a public repository.
## Authentication errors
| Status | Meaning |
|---|---|
| `401 Unauthorized` | The key is missing, wrong, or archived |
| `403 Forbidden` | The key is valid, but the resource belongs to another organization |
```json
{
"detail": "Invalid API key"
}
```
---
# Conventions
> How the LemuAI API pages through results, which limits apply, how to retry safely, and how to avoid counting the same order twice.
URL: https://docs.lemuai.com/api-reference/conventions
For: Developers
Checked against LemuAI app version 1.0.12
Related: [Overview](https://docs.lemuai.com/api-reference/overview), [Errors](https://docs.lemuai.com/api-reference/errors), [Quickstart](https://docs.lemuai.com/api-reference/quickstart)
## Requests and responses
- Base URL `https://app.lemuai.com/api/v1`, HTTPS only.
- Authenticate with the `X-API-Key` header ([Authentication](https://docs.lemuai.com/api-reference/authentication)).
- Send JSON with `Content-Type: application/json`; answers are JSON.
- Times are ISO 8601. Times LemuAI returns are in UTC.
- Phone numbers are international format with country code: `+919876543210`.
- Money is in major units (`1499.5` rupees, not paise) with an ISO 4217 `currency` (`INR`).
## Paging through results
List endpoints use one of three styles. Each endpoint's page lists its own parameters.
| Style | Parameters | Next page | Used by |
|---|---|---|---|
| Page number | `page` (from 1), `limit` | `page + 1` until `page` reaches `total_pages` (or a page comes back short) | [List Contacts](https://docs.lemuai.com/api-reference/contacts/list) (limit up to 500), [List Contact Lists](https://docs.lemuai.com/api-reference/contacts/lists) (up to 100), [List Contacts in a List](https://docs.lemuai.com/api-reference/contacts/list-members) (up to 1,000), [List Calls](https://docs.lemuai.com/api-reference/agents/runs/list) |
| Offset | `limit`, `offset` | `offset + limit` until `offset` reaches `total` | [List Events](https://docs.lemuai.com/api-reference/events/list) (limit up to 500) |
| Cursor (newest first) | `limit`, `before` / `before_id` | Pass `next_before` / `next_before_id` from the last answer; stop when it's `null` | [Contact Activity](https://docs.lemuai.com/api-reference/contacts/activity), [Contact Messages](https://docs.lemuai.com/api-reference/contacts/messages) (limit up to 200) |
Example, all contacts in pages of 500:
```python
import os, requests
page, contacts = 1, []
while True:
r = requests.get(
"https://app.lemuai.com/api/v1/contacts",
headers={"X-API-Key": os.environ["LEMU_API_KEY"]},
params={"page": page, "limit": 500},
timeout=30,
)
r.raise_for_status()
body = r.json()
contacts += body["contacts"]
if page >= body["total_pages"]:
break
page += 1
```
## Sizes and limits
| What | Limit |
|---|---|
| [Bulk Upsert Contacts](https://docs.lemuai.com/api-reference/contacts/bulk-upsert) | 5,000 contacts per request |
| [Create or Update Records in Bulk](https://docs.lemuai.com/api-reference/records/batch) | 1,000 records per request |
| One custom record | 16 KB of data, key up to 255 characters, text values up to 2,000 characters |
| Event name | 1 to 100 characters |
| Segment rules | 30 per segment; **is in** lists up to 500 values |
The REST API has no fixed per-key request rate today, but be a good citizen: use the bulk endpoints for imports instead of one request per row, and keep to a few requests per second per key. Website and app events sent with a tracking-source write key are rate limited per source and per device, and answer `429 Too many requests` when exceeded.
## Retries
- **Retry** on network errors, `429`, and `5xx`, with a growing wait (1 s, 2 s, 4 s… up to about a minute) and a little randomness.
- **Don't retry** `400`, `401`, `403`, `404` or `422` without changing the request: they won't succeed as sent. The `detail` field says why ([Errors](https://docs.lemuai.com/api-reference/errors)).
## Sending the same thing twice
| Request | Safe to repeat? |
|---|---|
| Upsert a contact, bulk upsert, create or update a record | Yes. They match on phone / key and update; repeating changes nothing |
| Send an event (`Purchase` and other conversion events) | Orders count once per `order_id`. Always send `order_id`, so a retried order isn't counted twice. Each event still starts journeys that listen for it, so avoid resending non-order events |
| Trigger an outbound call | No. Each request places a call. Retry only when you're sure the first request failed (a network error before any answer, or a `4xx`/`5xx`) |
| Send a transactional email | No. Each request sends an email |
## OpenAPI
The public endpoints are described in an OpenAPI 3 file: [`/openapi.json`](https://docs.lemuai.com/openapi.json). Import it into Postman or Insomnia, generate a client, or give it to your coding assistant.
---
# Webhooks
> Get call results pushed to your system after each call, and start journeys from your system with a signed webhook.
URL: https://docs.lemuai.com/api-reference/webhooks
For: Developers
Checked against LemuAI app version 1.0.12
Related: [Webhook](https://docs.lemuai.com/voice-agent/webhook), [Journey Nodes & Triggers](https://docs.lemuai.com/automation/nodes-and-triggers), [Send an Event](https://docs.lemuai.com/api-reference/events/trigger), [Journeys](https://docs.lemuai.com/troubleshooting/journeys)
There are two directions:
| Direction | What | Set up in |
|---|---|---|
| LemuAI → you | After each call, a voice agent sends the result (variables it captured, duration, recording, transcript) to your URL | A **Webhook** step in the voice agent |
| You → LemuAI | Your system starts a journey for someone by posting to the journey's webhook URL | A journey with the **Webhook** trigger |
To send events (orders, sign-ups) that start any journey listening for them, use [Send an Event](https://docs.lemuai.com/api-reference/events/trigger) instead; it needs your API key and links the event to a contact.
## Receive call results
Add a **Webhook** step to the voice agent (**Voice Agents → Agents**, open the agent). Set the **HTTP Method**, **Endpoint URL**, optional **Auth** and **Custom Headers**, and a **Payload Template (JSON)** using these variables:
| Variable | Value |
|---|---|
| `{{workflow_run_id}}` | The call's run id |
| `{{workflow_id}}`, `{{workflow_name}}` | The agent |
| `{{initial_context.}}` | Values the call started with (from the API, a journey or a campaign) |
| `{{gathered_context.}}` | Variables the agent extracted |
| `{{cost_info.call_duration_seconds}}` | Call duration |
| `{{recording_url}}`, `{{transcript_url}}` | Recording and transcript links |
Example payload template:
```json
{
"call_id": "{{workflow_run_id}}",
"order_id": "{{initial_context.order_id}}",
"confirmed": "{{gathered_context.confirmed}}",
"duration": "{{cost_info.call_duration_seconds}}",
"recording_url": "{{recording_url}}"
}
```
Your endpoint should answer with a `2xx` status quickly. See [Webhook (voice agent)](https://docs.lemuai.com/voice-agent/webhook).
## Start a journey with a webhook
Create a journey with the **Webhook** trigger. Its panel shows the URL to post to:
```text
POST https://app.lemuai.com/api/v1/workflow-execution/webhooks/{trigger_id}
```
The JSON body becomes the run's starting context, so later steps can use `{{context.}}`. Include the person's `phone` so steps that call or message have someone to reach. No API key is needed: the URL is the secret. For extra safety, set a **secret** on the trigger and sign each request.
### Signing requests
When the trigger has a secret, every request must carry:
```text
X-Webhook-Signature: sha256=
```
Sign the exact bytes you send. Re-serialising the JSON after signing (different spacing or key order) breaks the signature.
**cURL**
```bash
BODY='{"phone":"+919876543210","order_id":"A-1001","amount":1499}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | sed 's/^.* //')
curl -X POST "https://app.lemuai.com/api/v1/workflow-execution/webhooks/123" \
-H "Content-Type: application/json" \
-H "X-Webhook-Signature: sha256=$SIG" \
--data-raw "$BODY"
```
**JavaScript**
```js
import crypto from "node:crypto";
const body = JSON.stringify({ phone: "+919876543210", order_id: "A-1001", amount: 1499 });
const sig = crypto.createHmac("sha256", process.env.WEBHOOK_SECRET).update(body).digest("hex");
const res = await fetch("https://app.lemuai.com/api/v1/workflow-execution/webhooks/123", {
method: "POST",
headers: { "Content-Type": "application/json", "X-Webhook-Signature": `sha256=${sig}` },
body,
});
console.log(res.status, await res.json());
```
**Python**
```python
import hashlib, hmac, json, os, requests
body = json.dumps({"phone": "+919876543210", "order_id": "A-1001", "amount": 1499}).encode()
sig = hmac.new(os.environ["WEBHOOK_SECRET"].encode(), body, hashlib.sha256).hexdigest()
r = requests.post(
"https://app.lemuai.com/api/v1/workflow-execution/webhooks/123",
data=body,
headers={"Content-Type": "application/json", "X-Webhook-Signature": f"sha256={sig}"},
timeout=30,
)
print(r.status_code, r.json())
```
### Responses
| Status | Meaning |
|---|---|
| `200` | The run started. The body includes the trigger and run details |
| `401` | "Invalid webhook signature": missing or wrong `X-Webhook-Signature` |
| `404` | "Trigger {id} not found": the trigger was deleted, or the id is wrong |
| `400` | "Trigger {id} is not active", "Trigger {id} is not a webhook trigger", a request that doesn't match the trigger's settings (method, content type, required headers), or a journey that isn't live |
See [Journeys troubleshooting](https://docs.lemuai.com/troubleshooting/journeys) for each message.
---
# Errors
> HTTP status codes and error formats returned by the Lemu AI API
URL: https://docs.lemuai.com/api-reference/errors
## Error format
Errors return a JSON body with a `detail` field:
```json
{
"detail": "Agent trigger not found"
}
```
When the request itself is invalid (status `422`), `detail` is a list that points at each field that failed:
```json
{
"detail": [
{
"loc": ["body", "phone_number"],
"msg": "Field required",
"type": "missing"
}
]
}
```
`loc` shows where the problem is: `body` for the JSON body, `query` for a query parameter, `path` for a value in the URL.
Some endpoints return `detail` as an object with a fixed `error` word your code can check and a `message` for people, for example [Send a WhatsApp Template](https://docs.lemuai.com/api-reference/whatsapp/send-template):
```json
{
"detail": {
"error": "balance_too_low",
"message": "Your WhatsApp balance is too low. Recharge to keep sending."
}
}
```
## Status codes
| Status | Meaning | Common causes |
|---|---|---|
| `400` | Bad request | Telephony isn't set up for your organization, the carrier rejected the call, or a filter value is malformed |
| `401` | Unauthorized | Missing, wrong, or archived API key |
| `402` | Payment required | Your plan's call minutes or contact limit is used up, or your WhatsApp balance is too low |
| `403` | Forbidden | The resource belongs to another organization, or a filter you sent isn't allowed |
| `404` | Not found | The id doesn't exist in your organization, or an API Trigger was removed or turned off |
| `409` | Conflict | A contact with the same `external_id` already exists |
| `422` | Unprocessable entity | The body or a query parameter failed validation (see the format above) |
| `500` | Internal server error | Something went wrong on our side |
| `502` | Bad gateway | WhatsApp or the email service refused the message. `detail` holds their reason |
## Handling errors
- **Retry `500` responses** with exponential backoff. They are usually temporary.
- **Don't retry `4xx` responses** without changing the request. They describe a problem with the request, the key, or your plan.
- **On `422`**, read the `loc` of each entry to find the field to fix.
- **On `401` for a key that used to work**, check whether it was archived in **Settings → API Keys**.
---
# Trigger an Outbound Call
> Place an outbound phone call with a voice agent through its API Trigger
URL: https://docs.lemuai.com/api-reference/calls/trigger
Starts an outbound call to one phone number using a voice agent. This is the endpoint to call from your CRM, n8n, Zapier, or your own backend.
The `uuid` in the path identifies an **[API Trigger](https://docs.lemuai.com/voice-agent/api-trigger) node** in your agent, not the agent itself. Add an API Trigger node to the agent in the editor, save it, and copy the endpoint URL shown in the node's settings. The trigger must be active and still present in the agent's workflow.
**Note:** Your organization's telephony provider must be set up before calls can connect. See [Telephony](https://docs.lemuai.com/integrations/telephony/overview).
**Endpoint:** `POST /api/v1/public/agent/{uuid}`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from the same organization as the agent. This endpoint only accepts the key in this header. |
| `Content-Type` | Yes | `application/json` |
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `uuid` | string | Yes | The trigger id of the agent's API Trigger node (the last part of the endpoint URL shown in the node). |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `phone_number` | string | Yes | The number to call, in international format with the country code, for example `+919876543210`. |
| `initial_context` | object | No | Data for this call, such as the customer's name or order id. Each key becomes a template variable the agent can use in its prompts (see below). |
**Example request:**
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/public/agent/4f1c2b7e-9a3d-4e21-b6a0-2d5f8c9e1a77 \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"phone_number": "+919876543210",
"initial_context": {
"customer_name": "Priya",
"order_id": "ORD-1042",
"delivery_date": "28 October"
}
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/public/agent/4f1c2b7e-9a3d-4e21-b6a0-2d5f8c9e1a77", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"phone_number": "+919876543210",
"initial_context": {
"customer_name": "Priya",
"order_id": "ORD-1042",
"delivery_date": "28 October"
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/public/agent/4f1c2b7e-9a3d-4e21-b6a0-2d5f8c9e1a77",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"phone_number": "+919876543210",
"initial_context": {
"customer_name": "Priya",
"order_id": "ORD-1042",
"delivery_date": "28 October",
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Using initial context
Values in `initial_context` are available to the agent as template variables. With the request above, a prompt like:
```
Hi {{customer_name}}, I'm calling about your order {{order_id}}, due on {{delivery_date}}.
```
is spoken as "Hi Priya, I'm calling about your order ORD-1042, due on 28 October." See [Template Variables](https://docs.lemuai.com/voice-agent/template-variables) for fallbacks and nested values.
## Response
**`200`**: the call was handed to your telephony provider.
```json
{
"status": "initiated",
"workflow_run_id": 18234,
"workflow_run_name": "WR-API-4821"
}
```
| Field | Type | Description |
|---|---|---|
| `status` | string | Always `initiated` on success. The call is dialing; it has not been answered yet. |
| `workflow_run_id` | integer | The id of this call. It appears in [List calls](https://docs.lemuai.com/api-reference/agents/runs/list), in the dashboard, and in your Webhook node payload. |
| `workflow_run_name` | string | A short label for the call, shown in the dashboard. |
To receive the outcome when the call ends, add a [Webhook node](https://docs.lemuai.com/voice-agent/webhook) to the agent.
## Errors
| Status | When |
|---|---|
| `400` | Telephony isn't set up for your organization, or the provider refused the call (the reason is in `detail`) |
| `401` | The API key is missing or invalid |
| `402` | Your plan has no call minutes left |
| `403` | The API key belongs to a different organization than the agent |
| `404` | No trigger with this `uuid`, the trigger is turned off, or it was removed from the agent |
| `422` | `phone_number` is missing or the body isn't valid JSON |
---
# Send an Event
> Send an event from your own system to record what a person did and start journeys for them
URL: https://docs.lemuai.com/api-reference/events/trigger
Sends an event that happened in your own system, such as an abandoned cart, a placed order or a submitted form. LemuAI stores it, links it to the right contact, and starts every active journey whose [API Events trigger](https://docs.lemuai.com/automation/nodes-and-triggers) listens for the same `event_type`.
Use this to start a journey, for example a WhatsApp message or a follow-up call an hour after a cart is abandoned. To call one number straight away with a voice agent, use [Trigger an outbound call](https://docs.lemuai.com/api-reference/calls/trigger) instead.
**Endpoint:** `POST /api/v1/events`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `event_type` | string | Yes | The name of the event, 1 to 100 characters, for example `Purchase`, `InitiateCheckout` or your own `cart_abandoned`. Journeys whose API Events trigger uses the same `event_type` start for this contact. See [Event names](#event-names). |
| `phone` | string | No | The person's phone number in international format, for example `+919876543210`, up to 50 characters. |
| `email` | string | No | The person's email address, up to 254 characters. |
| `external_id` | string | No | Your own id for the person, for example a CRM or customer id, up to 255 characters. |
| `anonymous_id` | string | No | The visitor id set by the LemuAI website snippet or an app SDK (see [Tracking Sources](https://docs.lemuai.com/website-pixel/overview)), up to 512 characters. Send it to tie website or app activity to the person once they sign up or check out. |
| `list_name` | string | No | A contact list name, up to 255 characters. The contact is added to this list, and the list is created if it doesn't exist yet. |
| `data` | object | No | Any details about the event, such as order id, amount or product. Journeys started by this event can use these values (see below). For a `Purchase`, include `value`, `currency` and `order_id` (see [Orders and revenue](#orders-and-revenue)). |
Send at least one of `phone`, `email`, `external_id` or `anonymous_id` to link the event to a person. An event with none of them is stored but not linked to a contact.
If `data` contains `first_name` and `last_name` (or `name`, `full_name`, `contact_name` or `customer_name`), the name is saved on the contact.
## Event names
Use Meta's standard event names where one fits, such as `Purchase`, `AddToCart`, `InitiateCheckout` or `Lead`. They are matched whatever the case or separators: `purchase`, `PURCHASE` and `Purchase` are all stored as `Purchase`, and `add_to_cart` as `AddToCart`. Any other name is a custom event and is stored as you sent it.
Older names such as `order_placed` and `cart_added` still match `Purchase` and `InitiateCheckout` in journeys and segments. See [Standard and conversion events](https://docs.lemuai.com/website-pixel/standard-events) for the full list.
## Orders and revenue
A `Purchase` (or any other event listed under **Conversion events** in [Sending Limits](https://docs.lemuai.com/settings/sending-limits#conversion-events)) counts as an order for journey and campaign revenue and ROI. Include these fields in `data`:
| Field | Type | Description |
|---|---|---|
| `value` | number | The order total in major units, for example `1499.5` |
| `currency` | string | An ISO 4217 code, for example `INR` |
| `order_id` | string | Your id for the order. The same order reported more than once, by this API, your website, your app or Shopify, counts once |
The event is never rejected for a missing field. An order without a value counts with no revenue, a missing currency is replaced by your workspace currency, and an order without an `order_id` counts every time it is sent.
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/events \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"event_type": "Purchase",
"phone": "+919876543210",
"data": {
"value": 1499.5,
"currency": "INR",
"order_id": "1042",
"content_ids": ["SKU1"]
}
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/events", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"event_type": "Purchase",
"phone": "+919876543210",
"data": {
"value": 1499.5,
"currency": "INR",
"order_id": "1042",
"content_ids": [
"SKU1"
]
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/events",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"event_type": "Purchase",
"phone": "+919876543210",
"data": {
"value": 1499.5,
"currency": "INR",
"order_id": "1042",
"content_ids": [
"SKU1",
],
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## How the contact is found
LemuAI looks up every identifier you send (`phone`, `email`, `external_id` and `anonymous_id`) and works out which person they belong to:
1. **One match.** If the identifiers point to one existing contact, the event is linked to it, and any new identifiers you sent are added to that contact.
2. **Several matches.** If they point to two or more contacts that are clearly the same person (for example the phone matches one contact and the email matches another, and nothing conflicts), those contacts are merged into one and the event is linked to it. Contacts are not merged when that would join two different people, for example two contacts that each have a different email. In that case the event is linked to the main matching contact and nothing is merged.
3. **No match.** A new contact is created, but only when you sent a `phone` or an `email`. An `external_id` or `anonymous_id` on its own links to an existing contact or to none; it never creates one.
A website visitor id that was linked to another person before moves to the person in this event.
**Example request:**
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/events \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"event_type": "cart_abandoned",
"phone": "+919876543210",
"email": "priya@example.com",
"external_id": "cust-58214",
"list_name": "Abandoned carts",
"data": {
"first_name": "Priya",
"cart_amount": 2499,
"product_name": "Running shoes"
}
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/events", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"event_type": "cart_abandoned",
"phone": "+919876543210",
"email": "priya@example.com",
"external_id": "cust-58214",
"list_name": "Abandoned carts",
"data": {
"first_name": "Priya",
"cart_amount": 2499,
"product_name": "Running shoes"
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/events",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"event_type": "cart_abandoned",
"phone": "+919876543210",
"email": "priya@example.com",
"external_id": "cust-58214",
"list_name": "Abandoned carts",
"data": {
"first_name": "Priya",
"cart_amount": 2499,
"product_name": "Running shoes",
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`201`**: the event was stored and matching journeys were queued.
```json
{
"event_id": 90412,
"contact_id": 5531,
"triggered_workflows": 0
}
```
| Field | Type | Description |
|---|---|---|
| `event_id` | integer | The id of the stored event. It appears in the [Event Log](https://docs.lemuai.com/event-log/overview). |
| `contact_id` | integer or null | The contact the event was linked to. `null` when no identifier was sent, when only an `external_id` or `anonymous_id` was sent and no contact has it, or when your plan's contact limit stopped a new contact being created. |
| `triggered_workflows` | integer | Always `0`. Journeys are started in the background just after the response, so the count isn't known yet. Check the Event Log or the journey's runs to see what ran. |
## Using event data in a journey
A journey started by this event gets `phone`, `event_type` and `event_id`, plus every field from `data` (or only the fields picked in the trigger's context mapping). With the request above, a call step in the journey can use `{{first_name}}`, `{{cart_amount}}` and `{{product_name}}` in the agent's prompt.
On the journey's API Events trigger you can also:
- wait before running, for example 60 minutes after `cart_abandoned`;
- cancel the run if another event arrives for the same contact first, for example `Purchase`;
- only run for contacts in a chosen list.
See [Journey nodes and triggers](https://docs.lemuai.com/automation/nodes-and-triggers) for the full trigger settings.
**Note:** A new contact created from an event is tagged `event` and counts toward your plan's contact limit. If you've reached the limit, the event is still stored, but no contact is created and `contact_id` is `null`.
## Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid. |
| `422` | `event_type` is missing or too long, or another field is too long or has the wrong type. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# List Events
> List your organization's events from every source, newest first
URL: https://docs.lemuai.com/api-reference/events/list
Returns your organization's events, newest first. This is the same data as the [Event Log](https://docs.lemuai.com/event-log/overview) page. It includes events you sent with [Send an event](https://docs.lemuai.com/api-reference/events/trigger) and events from other sources, such as Shopify, your [tracking sources](https://docs.lemuai.com/website-pixel/overview), [segments](https://docs.lemuai.com/segments/overview) and [custom records](https://docs.lemuai.com/records/overview).
**Endpoint:** `GET /api/v1/events`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `event_type` | string | No | Only return events of this type, for example `Purchase`. A Meta standard event name also returns events stored under its older names, so `Purchase` includes `order_placed` and `checkout_completed`. See [Standard and conversion events](https://docs.lemuai.com/website-pixel/standard-events#old-names-that-still-match). |
| `source` | string | No | Only return events from this source. See [Event sources](#event-sources) below. |
| `include_message_updates` | boolean | No | Also return message status updates, such as `message_sent` or `message_delivered`. Default `false`. Only works when the event store is on (see `store` below). |
| `search` | string | No | Match against the phone number, the contact's name or the event type. |
| `start_date` | string | No | Earliest event to include, as `YYYY-MM-DD` or a full ISO date and time. |
| `end_date` | string | No | Latest event to include, as `YYYY-MM-DD` (the whole day is included) or a full ISO date and time. |
| `limit` | integer | No | How many events to return, 1 to 500. Default `100`. |
| `offset` | integer | No | How many events to skip, for paging. Default `0`. |
## Event sources
| Source | Where the event came from |
|---|---|
| `api` | [Send an event](https://docs.lemuai.com/api-reference/events/trigger) |
| `shopify` | Your connected Shopify store |
| `pixel` | A [tracking source](https://docs.lemuai.com/website-pixel/overview): the LemuAI website snippet or an app SDK, including visits by people who aren't known yet |
| `messaging` | Status changes of messages and calls on any channel |
| `segments` | A contact entering or leaving a segment |
| `records` | A custom record being created, updated or deleted |
| `backfill` | Older events copied in when the event store was turned on |
**Example request:**
**cURL**
```bash
curl "https://app.lemuai.com/api/v1/events?source=api&event_type=cart_abandoned&start_date=2026-10-01&limit=50" \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/events?source=api&event_type=cart_abandoned&start_date=2026-10-01&limit=50", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/events?source=api&event_type=cart_abandoned&start_date=2026-10-01&limit=50",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"events": [
{
"id": 90412,
"event_id": "3f6c2a9e-8d1b-5c7a-9e42-1b7d0c5a6f13",
"event_type": "cart_abandoned",
"source": "api",
"phone": "+919876543210",
"contact_id": 5531,
"contact_name": "Priya Sharma",
"anonymous_id": null,
"event_data": {
"first_name": "Priya",
"cart_amount": 2499,
"product_name": "Running shoes"
},
"created_at": "2026-10-27T09:14:02.511000+00:00"
}
],
"total": 1,
"store": "clickhouse"
}
```
| Field | Type | Description |
|---|---|---|
| `events` | array | The events on this page, newest first. |
| `events[].id` | integer | The event's number in LemuAI. This is the `event_id` returned by Send an event. It is `0` for events that are only kept in the event store, such as page views by website visitors. |
| `events[].event_id` | string | A unique id (UUID) for the event. Every event has one, so use it when you need a stable id. |
| `events[].event_type` | string | The event name. |
| `events[].source` | string | Where the event came from. See [Event sources](#event-sources). |
| `events[].phone` | string or null | The phone number sent with the event. |
| `events[].contact_id` | integer or null | The contact the event is linked to. |
| `events[].contact_name` | string or null | That contact's name, if known. |
| `events[].anonymous_id` | string or null | The website visitor id, for activity by a visitor who isn't linked to a contact yet. |
| `events[].event_data` | object | The details sent with the event. |
| `events[].created_at` | string | When the event happened, in ISO 8601 (UTC). |
| `total` | integer | How many events match your filters in total, for paging with `limit` and `offset`. |
| `store` | string | Where the events were read from: `clickhouse` (the event store, which holds every source including anonymous website visits) or `postgres` (the main database, used when the event store isn't on). |
**Note:** API keys see full phone numbers here. In the dashboard, team members without permission to view personal data see them partly hidden.
## Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid. |
| `422` | A query parameter has the wrong type, or `limit` is outside 1 to 500. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# List Agents
> List the voice agents in your organization
URL: https://docs.lemuai.com/api-reference/agents/list
Returns every voice agent in your organization with a few summary numbers. Use it to find an agent's `id` for [List calls](https://docs.lemuai.com/api-reference/agents/runs/list).
**Endpoint:** `GET /api/v1/workflow/fetch`
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `status` | string | No | `active`, `archived`, or both separated by a comma (`active,archived`). Leave it out to get all agents. Any other value returns `422`. |
**Example request:**
**cURL**
```bash
curl "https://app.lemuai.com/api/v1/workflow/fetch?status=active" \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/workflow/fetch?status=active", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/workflow/fetch?status=active",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**: a list of agents.
```json
[
{
"id": 412,
"name": "Order Delivery Confirmation",
"status": "active",
"created_at": "2026-09-14T08:21:47Z",
"total_runs": 1284,
"workflow_uuid": "8d0e6c2a-51f4-4b0e-9f7c-3c2a1e6b9d40",
"last_run_at": "2026-10-23T11:05:12Z",
"success_rate": 87.4
}
]
```
| Field | Type | Description |
|---|---|---|
| `id` | integer | The agent's id. Use it in other endpoints. |
| `name` | string | The agent's name as shown in the dashboard. |
| `status` | string | `active` or `archived`. |
| `created_at` | string | When the agent was created (ISO 8601, UTC). |
| `total_runs` | integer | How many calls the agent has made or received. |
| `workflow_uuid` | string or null | A stable public identifier for the agent. This is **not** the id used by [Trigger an outbound call](https://docs.lemuai.com/api-reference/calls/trigger); that endpoint needs the API Trigger node's id. |
| `last_run_at` | string or null | When the agent's most recent call started, or `null` if it has none. |
| `success_rate` | number or null | Percentage of the agent's calls that ran to completion, from `0` to `100` (one decimal place). `null` if it has no calls yet. |
---
# List Calls
> List the calls (runs) made or received by one voice agent
URL: https://docs.lemuai.com/api-reference/agents/runs/list
Returns the calls for one voice agent, newest first, a page at a time. Each call is called a **run**. Use it to check whether a call you [triggered](https://docs.lemuai.com/api-reference/calls/trigger) has finished and what the agent captured.
**Tip:** If you need each result as soon as a call ends, add a [Webhook node](https://docs.lemuai.com/voice-agent/webhook) to the agent instead of polling this endpoint.
**Endpoint:** `GET /api/v1/workflow/{workflow_id}/runs`
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `workflow_id` | integer | Yes | The agent's `id` from [List agents](https://docs.lemuai.com/api-reference/agents/list). |
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | No | Page number, starting at `1`. Default `1`. |
| `limit` | integer | No | Calls per page. Default `50`. |
| `sort_by` | string | No | `created_at` (default) or `duration`. |
| `sort_order` | string | No | `desc` (default) or `asc`. |
| `filters` | string | No | A JSON array of filters, URL-encoded. See below. |
## Filters
`filters` is a JSON array. Each item has an `attribute`, a `type`, and a `value`:
| Attribute | Type | Value | Matches calls |
|---|---|---|---|
| `dateRange` | `dateRange` | `{"from": "2026-10-01T00:00:00", "to": "2026-10-31T23:59:59"}` | Started between the two times (ISO 8601). Either end can be left out. |
| `status` | `radio` | `{"status": "completed"}` or `{"status": "in_progress"}` | That have finished, or are still going |
| `dispositionCode` | `multiSelect` | `{"codes": ["INTERESTED", "CALLBACK"]}` | Ended with one of these disposition codes |
| `duration` | `numberRange` | `{"min": 30, "max": 600}` | Lasted between these numbers of seconds |
Any other attribute returns `403`. A `filters` value that isn't valid JSON returns `400`.
**Example request** (completed calls from October):
**cURL**
```bash
curl -G "https://app.lemuai.com/api/v1/workflow/412/runs" \
-H "X-API-Key: lemu_your_api_key" \
--data-urlencode 'limit=20' \
--data-urlencode 'filters=[{"attribute":"status","type":"radio","value":{"status":"completed"}},{"attribute":"dateRange","type":"dateRange","value":{"from":"2026-10-01T00:00:00"}}]'
```
**JavaScript**
```js
const params = new URLSearchParams({
"limit": "20",
"filters": "[{\"attribute\":\"status\",\"type\":\"radio\",\"value\":{\"status\":\"completed\"}},{\"attribute\":\"dateRange\",\"type\":\"dateRange\",\"value\":{\"from\":\"2026-10-01T00:00:00\"}}]",
});
const res = await fetch(`https://app.lemuai.com/api/v1/workflow/412/runs?${params}`, {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/workflow/412/runs",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
params={
"limit": "20",
"filters": "[{\"attribute\":\"status\",\"type\":\"radio\",\"value\":{\"status\":\"completed\"}},{\"attribute\":\"dateRange\",\"type\":\"dateRange\",\"value\":{\"from\":\"2026-10-01T00:00:00\"}}]",
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"runs": [
{
"id": 18234,
"workflow_id": 412,
"name": "WR-API-4821",
"mode": "plivo",
"created_at": "2026-10-23T11:05:12Z",
"is_completed": true,
"call_type": "outbound",
"definition_id": 1907,
"initial_context": {
"phone_number": "+919876543210",
"customer_name": "Priya",
"order_id": "ORD-1042"
},
"gathered_context": {
"delivery_confirmed": true,
"preferred_time": "after 5 pm",
"mapped_call_disposition": "CONFIRMED"
},
"cost_info": {
"billed_minutes": 2,
"call_duration_seconds": 94
},
"recording_url": "recordings/18234.wav",
"transcript_url": "transcripts/18234.txt"
}
],
"total_count": 1284,
"page": 1,
"limit": 20,
"total_pages": 65,
"applied_filters": [
{ "attribute": "status", "type": "radio", "value": { "status": "completed" } }
]
}
```
| Field | Type | Description |
|---|---|---|
| `runs` | array | The calls on this page. Fields of each call are below. |
| `total_count` | integer | Calls matching your filters across all pages. |
| `page` | integer | The page returned. |
| `limit` | integer | Calls per page. |
| `total_pages` | integer | Number of pages at this `limit`. |
| `applied_filters` | array or null | The filters that were applied, or `null` if none. |
**Each call:**
| Field | Type | Description |
|---|---|---|
| `id` | integer | The call's id. Matches `workflow_run_id` from [Trigger an outbound call](https://docs.lemuai.com/api-reference/calls/trigger). |
| `workflow_id` | integer | The agent that handled the call. |
| `name` | string | The call's label in the dashboard. |
| `mode` | string | How the call was connected: the telephony provider (for example `twilio`, `plivo`, `exotel`), or `webrtc` / `textchat` for browser tests. |
| `created_at` | string | When the call started (ISO 8601, UTC). |
| `is_completed` | boolean | `true` once the call has ended. |
| `call_type` | string | `outbound` or `inbound`. |
| `definition_id` | integer or null | The version of the agent that ran this call. |
| `initial_context` | object or null | The data the call started with, including `phone_number` and anything you sent in `initial_context`. |
| `gathered_context` | object or null | What the agent captured during the call, plus `mapped_call_disposition` (the disposition code the call ended with). Empty until the call has finished. |
| `cost_info` | object or null | `call_duration_seconds` and `billed_minutes` for the call. `null` until the call has ended. |
| `recording_url`, `transcript_url` | string or null | Internal references to the stored recording and transcript. Open recordings and transcripts from the call in the dashboard; they are not downloadable through the API. |
**Note:** Phone numbers and other personal details in `initial_context` and `gathered_context` may be partly hidden, depending on whether the person who created the API key is allowed to view personal data in your organization.
---
# List Campaigns
> List the calling campaigns in your organization and their progress
URL: https://docs.lemuai.com/api-reference/campaigns/list
Returns every campaign in your organization with its state and progress counts. Campaigns are created and run from the dashboard; see [Campaigns](https://docs.lemuai.com/core-concepts/campaigns).
**Endpoint:** `GET /api/v1/campaign/`
This endpoint takes no parameters.
**Example request:**
**cURL**
```bash
curl https://app.lemuai.com/api/v1/campaign/ \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/campaign/", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/campaign/",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"campaigns": [
{
"id": 57,
"name": "October payment reminders",
"workflow_id": 412,
"workflow_name": "Payment Reminder",
"state": "running",
"source_type": "contact-list",
"source_id": "23",
"total_rows": 1200,
"processed_rows": 640,
"failed_rows": 12,
"created_at": "2026-10-20T09:00:00Z",
"started_at": "2026-10-21T04:30:00Z",
"completed_at": null,
"retry_config": {
"enabled": true,
"max_retries": 2,
"retry_delay_seconds": 120,
"retry_on_busy": true,
"retry_on_no_answer": true,
"retry_on_voicemail": false
},
"schedule_config": {
"enabled": true,
"timezone": "Asia/Kolkata",
"slots": [
{ "day_of_week": 0, "start_time": "10:00", "end_time": "18:00" }
]
},
"circuit_breaker": {
"enabled": true,
"failure_threshold": 0.5,
"window_seconds": 120,
"min_calls_in_window": 5
}
}
]
}
```
**Each campaign:**
| Field | Type | Description |
|---|---|---|
| `id` | integer | The campaign's id. |
| `name` | string | The campaign's name. |
| `workflow_id` | integer | The voice agent the campaign calls with. |
| `workflow_name` | string | That agent's name. |
| `state` | string | `created`, `syncing`, `running`, `paused`, `completed`, or `failed`. |
| `source_type` | string | Where the numbers come from: `contact-list`, `google-sheet`, or `csv`. |
| `source_id` | string | The contact list id, Google Sheet URL, or uploaded file reference. |
| `total_rows` | integer or null | Contacts in the campaign, once the source has been read. |
| `processed_rows` | integer | Contacts already called. |
| `failed_rows` | integer | Contacts whose call could not be placed. |
| `created_at` | string | When the campaign was created (ISO 8601, UTC). |
| `started_at` | string or null | When it was first started. |
| `completed_at` | string or null | When it finished. |
| `retry_config` | object | Whether and how unanswered calls are retried: `enabled`, `max_retries`, `retry_delay_seconds`, and which outcomes trigger a retry (`retry_on_busy`, `retry_on_no_answer`, `retry_on_voicemail`). |
| `schedule_config` | object or null | The calling windows: `timezone` and `slots` (`day_of_week` from `0` Monday to `6` Sunday, `start_time` and `end_time` as `HH:MM`). `null` if the campaign calls at any time. |
| `circuit_breaker` | object or null | Automatic pause when too many calls fail: `failure_threshold` (share of failures, `0` to `1`) within `window_seconds`, once at least `min_calls_in_window` calls were made. |
---
# Overview
> Keep your Lemu AI contacts and contact lists in sync with your CRM
URL: https://docs.lemuai.com/api-reference/contacts/overview
A **contact** is a person you call or message. Contacts are grouped into **contact lists**, which campaigns and journeys use as their audience. One contact can be in several lists.
The contacts API is for keeping Lemu AI in step with your own system (a CRM, a spreadsheet, a signup form):
| Method | Endpoint | Purpose |
|---|---|---|
| `POST` | `/contacts/upsert` | [Add or update one contact](https://docs.lemuai.com/api-reference/contacts/upsert) and put it in a list |
| `POST` | `/contacts/bulk-upsert` | [Add or update up to 5,000 contacts](https://docs.lemuai.com/api-reference/contacts/bulk-upsert) in one list |
| `GET` | `/contacts` | [List and search contacts](https://docs.lemuai.com/api-reference/contacts/list) |
| `GET` | `/contacts/{contact_id}` | [Get one contact](https://docs.lemuai.com/api-reference/contacts/get) and the lists it is in |
| `GET` | `/contacts/lists` | [List your contact lists](https://docs.lemuai.com/api-reference/contacts/lists) |
| `GET` | `/contacts/lists/{list_id}/contacts` | [List the contacts in one list](https://docs.lemuai.com/api-reference/contacts/list-members) |
| `GET` | `/contacts/{contact_id}/consents` | [Get a contact's consent](https://docs.lemuai.com/api-reference/contacts/consents) for each channel |
| `PUT` | `/contacts/{contact_id}/consents/{channel}` | [Record an opt-in or opt-out](https://docs.lemuai.com/api-reference/contacts/consents#record-consent-for-one-channel) |
| `GET` | `/contacts/{contact_id}/activity` | [Get a contact's activity](https://docs.lemuai.com/api-reference/contacts/activity) from every source |
| `GET` | `/contacts/{contact_id}/messages` | [List a contact's messages and calls](https://docs.lemuai.com/api-reference/contacts/messages) |
Editing lists, deleting contacts, and importing from Google Sheets are done in the dashboard under **Contacts**.
## Contact fields
| Field | Type | Description |
|---|---|---|
| `id` | integer | The contact's id in Lemu AI. |
| `organization_id` | integer | Your organization's id. |
| `phone` | string or null | Phone number in international format, for example `+919876543210`. Used to match existing contacts when upserting. |
| `phone_last4` | string or null | The last four digits of the phone number. |
| `phone_masked` | boolean | `true` if `phone` is partly hidden (see below). |
| `external_id` | string or null | Your own id for this person, for example the CRM record id. Must be unique in your organization. |
| `email` | string or null | Email address. |
| `first_name`, `last_name` | string or null | Name. |
| `company` | string or null | Company name. |
| `title` | string or null | Job title. |
| `tags` | array of strings or null | Labels for grouping and filtering. |
| `custom_fields` | object | Any other values you store on the contact, as key-value pairs. Agents can use them as template variables when calling the contact. |
| `created_at`, `updated_at` | string | Timestamps (ISO 8601, UTC). |
## Hidden phone numbers
Phone numbers are personal data. If the person who created the API key isn't allowed to view personal data in your organization, responses show the number partly hidden (for example `•••• 3210`) and set `phone_masked` to `true`. Organization owners and admins, and team members with permission to view personal data, see full numbers.
## Plan limits
Your plan sets how many contacts your organization can store. Requests that would go over the limit return `402`.
---
# Upsert a Contact
> Create or update one contact by phone number and add it to a contact list
URL: https://docs.lemuai.com/api-reference/contacts/upsert
Adds one contact to a contact list, creating whatever doesn't exist yet:
- **The contact** is matched by `phone` in your organization. The match ignores formatting, so `+91 98765 43210` and `+919876543210` are the same number. If a match is found, the fields you send are updated; if not, a new contact is created.
- **The list** is matched by `list_name`. If no list has that name, it is created.
Use this endpoint when a record is created or changes in your CRM.
**Endpoint:** `POST /api/v1/contacts/upsert`
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `list_name` | string | Yes | The contact list to add the contact to (1 to 255 characters). Created if it doesn't exist. |
| `phone` | string | One of `phone` or `external_id` | Phone number in international format. This is what existing contacts are matched on. |
| `external_id` | string | One of `phone` or `external_id` | Your own id for the person. Stored on the contact, but not used for matching: a request with only `external_id` always creates a new contact. |
| `email` | string | No | A valid email address. |
| `first_name` | string | No | Up to 100 characters. |
| `last_name` | string | No | Up to 100 characters. |
| `company` | string | No | Up to 255 characters. |
| `title` | string | No | Job title, up to 255 characters. |
| `tags` | array of strings | No | Replaces the contact's tags. |
| `custom_fields` | object | No | Extra values. Merged into the contact's existing custom fields: keys you send are updated, others are kept. |
When updating, fields you leave out (or send as `null`) keep their current value.
**Example request:**
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/contacts/upsert \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"list_name": "October renewals",
"phone": "+919876543210",
"external_id": "crm-58213",
"first_name": "Priya",
"last_name": "Sharma",
"tags": ["renewal", "gold"],
"custom_fields": { "plan": "Gold", "renewal_date": "2026-11-05" }
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/upsert", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"list_name": "October renewals",
"phone": "+919876543210",
"external_id": "crm-58213",
"first_name": "Priya",
"last_name": "Sharma",
"tags": [
"renewal",
"gold"
],
"custom_fields": {
"plan": "Gold",
"renewal_date": "2026-11-05"
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/contacts/upsert",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"list_name": "October renewals",
"phone": "+919876543210",
"external_id": "crm-58213",
"first_name": "Priya",
"last_name": "Sharma",
"tags": [
"renewal",
"gold",
],
"custom_fields": {
"plan": "Gold",
"renewal_date": "2026-11-05",
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"contact": {
"id": 901,
"organization_id": 7,
"external_id": "crm-58213",
"phone": "+919876543210",
"phone_last4": "3210",
"phone_masked": false,
"email": null,
"first_name": "Priya",
"last_name": "Sharma",
"company": null,
"title": null,
"tags": ["renewal", "gold"],
"custom_fields": { "plan": "Gold", "renewal_date": "2026-11-05" },
"created_at": "2026-10-20T10:00:00Z",
"updated_at": "2026-10-24T09:12:40Z"
},
"contact_list": {
"id": 55,
"organization_id": 7,
"name": "October renewals",
"description": null,
"metadata": {},
"column_schema": [],
"created_at": "2026-10-24T09:12:40Z",
"updated_at": "2026-10-24T09:12:40Z"
},
"contact_created": false,
"list_created": true
}
```
| Field | Type | Description |
|---|---|---|
| `contact` | object | The contact after the update. See [contact fields](https://docs.lemuai.com/api-reference/contacts/overview#contact-fields). |
| `contact_list` | object | The list the contact was added to: `id`, `name`, `description`, and timestamps. |
| `contact_created` | boolean | `true` if a new contact was created, `false` if an existing one was updated. |
| `list_created` | boolean | `true` if the list was created by this request. |
## Errors
| Status | When |
|---|---|
| `402` | Your plan's contact limit is reached |
| `422` | Neither `phone` nor `external_id` was sent, `list_name` is missing, or a field is too long or not valid (for example `email`) |
---
# Bulk Upsert Contacts
> Create or update up to 5,000 contacts in one contact list in a single request
URL: https://docs.lemuai.com/api-reference/contacts/bulk-upsert
Loads or refreshes a contact list in one request. For each contact:
1. Lemu AI looks for an existing contact with the same `phone`, then with the same `external_id`. A row that has neither a phone nor an `external_id` is matched by `email` instead (ignoring upper and lower case), so sending the same email-only rows again updates them rather than creating duplicates.
2. If one is found, it is updated with the fields you send. If not, a new contact is created.
3. The contact is added to the list named `list_name`, which is created if it doesn't exist.
Each contact is handled on its own, so one bad row doesn't stop the rest. Rows that fail are reported in `errors`.
This endpoint matches rows by phone, `external_id` and email only. It does not merge contacts. To link activity from several identifiers (for example a website visitor id) to one person, use [Send an event](https://docs.lemuai.com/api-reference/events/trigger).
**Note:** Bulk matching compares phone numbers exactly as stored. Send every number in the same international format (for example `+919876543210`) so existing contacts are found instead of duplicated.
**Endpoint:** `POST /api/v1/contacts/bulk-upsert`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `list_name` | string | Yes | The list to put the contacts in (1 to 255 characters). Created if it doesn't exist. |
| `contacts` | array | Yes | Between 1 and 5,000 contacts. Each one accepts the fields below. |
**Each contact:**
| Field | Type | Description |
|---|---|---|
| `phone` | string | Phone number in international format. |
| `external_id` | string | Your own id for the person. |
| `email` | string | Email address. |
| `first_name`, `last_name` | string | Name. A single `name` (or `full_name`) is also accepted and split into first and last name. |
| `company` | string | Company name. |
| `title` | string | Job title. |
| `tags` | array of strings | Replaces the contact's tags. |
| `custom_fields` | object | Extra values, merged into the contact's custom fields. |
| *any other key* | any | Stored in `custom_fields`, so you can send a row from a spreadsheet or CRM as it is. A `mobile` key is used as `phone` and an `id` key as `external_id` when those aren't set. |
**Example request:**
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/contacts/bulk-upsert \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"list_name": "October renewals",
"contacts": [
{ "phone": "+919876543210", "first_name": "Priya", "plan": "Gold" },
{ "phone": "+919812345678", "name": "Rahul Verma", "id": "crm-58214", "tags": ["renewal"] },
{ "phone": "+919876543210", "first_name": "Priya S." }
]
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/bulk-upsert", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"list_name": "October renewals",
"contacts": [
{
"phone": "+919876543210",
"first_name": "Priya",
"plan": "Gold"
},
{
"phone": "+919812345678",
"name": "Rahul Verma",
"id": "crm-58214",
"tags": [
"renewal"
]
},
{
"phone": "+919876543210",
"first_name": "Priya S."
}
]
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/contacts/bulk-upsert",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"list_name": "October renewals",
"contacts": [
{
"phone": "+919876543210",
"first_name": "Priya",
"plan": "Gold",
},
{
"phone": "+919812345678",
"name": "Rahul Verma",
"id": "crm-58214",
"tags": [
"renewal",
],
},
{
"phone": "+919876543210",
"first_name": "Priya S.",
},
],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"created": 1,
"updated": 1,
"failed": 1,
"errors": [
{ "index": 2, "error": "Duplicate phone +919876543210 in batch, skipped" }
],
"list_created": false,
"list_id": 42,
"contacts": [
{
"id": 901,
"organization_id": 7,
"external_id": "crm-58213",
"phone": "+919876543210",
"phone_last4": "3210",
"phone_masked": false,
"email": null,
"first_name": "Priya",
"last_name": "Sharma",
"company": null,
"title": null,
"tags": ["renewal", "gold"],
"custom_fields": { "plan": "Gold" },
"created_at": "2026-10-20T10:00:00Z",
"updated_at": "2026-10-24T09:20:03Z"
}
]
}
```
| Field | Type | Description |
|---|---|---|
| `created` | integer | Contacts created. |
| `updated` | integer | Existing contacts updated. |
| `failed` | integer | Rows that were skipped. |
| `errors` | array | One entry per failed row: `index` (its position in your `contacts` array, starting at `0`) and `error` (why). A phone number, `external_id` or email (for email-only rows) repeated within the same request is skipped after its first appearance. |
| `list_created` | boolean | `true` if the list was created by this request. |
| `list_id` | integer | The id of the list. Use it with [List the contacts in one list](https://docs.lemuai.com/api-reference/contacts/list-members), or to pick the list as a journey or campaign audience. |
| `contacts` | array | The contacts that were created or updated. See [contact fields](https://docs.lemuai.com/api-reference/contacts/overview#contact-fields). |
## Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid |
| `402` | The contacts would take your organization over its plan's contact limit |
| `422` | `list_name` is missing, `contacts` is empty or has more than 5,000 items, or a field is too long |
---
# List Contacts
> List and search the contacts in your organization
URL: https://docs.lemuai.com/api-reference/contacts/list
Returns your contacts a page at a time, newest first, with optional search and filters.
**Endpoint:** `GET /api/v1/contacts`
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | No | Page number, starting at `1`. Default `1`. |
| `limit` | integer | No | Contacts per page, `1` to `500`. Default `50`. |
| `search` | string | No | Text to look for in first, last or full name, email, company, external ID and phone. A phone-like value also matches the last 4 digits, and the full number with or without the country code (`9876543210`, `+919876543210`). |
| `tags` | string | No | Comma-separated tags. Returns contacts with any of them. |
| `has_email` | boolean | No | `true` for contacts with an email, `false` for contacts without one. |
| `has_phone` | boolean | No | `true` for contacts with a phone number, `false` for contacts without one. |
| `list_id` | integer | No | Only contacts in this list. |
| `sort_by` | string | No | `created_at` (default), `first_name`, `last_name`, `phone`, `email`, `company`, `title`, `opted_out` or `id`. |
| `sort_dir` | string | No | `desc` (default) or `asc`. |
**Example request:**
**cURL**
```bash
curl -G https://app.lemuai.com/api/v1/contacts \
-H "X-API-Key: lemu_your_api_key" \
--data-urlencode "search=Priya" \
--data-urlencode "tags=renewal,gold" \
--data-urlencode "limit=25"
```
**JavaScript**
```js
const params = new URLSearchParams({
"search": "Priya",
"tags": "renewal,gold",
"limit": "25",
});
const res = await fetch(`https://app.lemuai.com/api/v1/contacts?${params}`, {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
params={
"search": "Priya",
"tags": "renewal,gold",
"limit": "25",
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"contacts": [
{
"id": 901,
"organization_id": 7,
"external_id": "crm-58213",
"phone": "+919876543210",
"phone_last4": "3210",
"phone_masked": false,
"email": "priya@example.com",
"first_name": "Priya",
"last_name": "Sharma",
"company": "Sharma Traders",
"title": "Owner",
"tags": ["renewal", "gold"],
"custom_fields": { "plan": "Gold" },
"created_at": "2026-10-20T10:00:00Z",
"updated_at": "2026-10-24T09:12:40Z"
}
],
"total_count": 1,
"page": 1,
"limit": 25,
"total_pages": 1
}
```
| Field | Type | Description |
|---|---|---|
| `contacts` | array | The contacts on this page. See [contact fields](https://docs.lemuai.com/api-reference/contacts/overview#contact-fields). |
| `total_count` | integer | Contacts matching your filters across all pages. |
| `page` | integer | The page returned. |
| `limit` | integer | Contacts per page. |
| `total_pages` | integer | Number of pages at this `limit`. |
---
# Get a Contact
> Get one contact and the contact lists it belongs to
URL: https://docs.lemuai.com/api-reference/contacts/get
Returns one contact by its Lemu AI id, including the lists it is in.
**Endpoint:** `GET /api/v1/contacts/{contact_id}`
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `contact_id` | integer | Yes | The contact's `id`, from [List contacts](https://docs.lemuai.com/api-reference/contacts/list) or an upsert response. |
**Example request:**
**cURL**
```bash
curl https://app.lemuai.com/api/v1/contacts/901 \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/901", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts/901",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"id": 901,
"organization_id": 7,
"external_id": "crm-58213",
"phone": "+919876543210",
"phone_last4": "3210",
"phone_masked": false,
"email": "priya@example.com",
"first_name": "Priya",
"last_name": "Sharma",
"company": "Sharma Traders",
"title": "Owner",
"tags": ["renewal", "gold"],
"custom_fields": { "plan": "Gold" },
"created_at": "2026-10-20T10:00:00Z",
"updated_at": "2026-10-24T09:12:40Z",
"lists": [
{ "id": 55, "name": "October renewals" },
{ "id": 23, "name": "All customers" }
]
}
```
The response has all the [contact fields](https://docs.lemuai.com/api-reference/contacts/overview#contact-fields), plus:
| Field | Type | Description |
|---|---|---|
| `lists` | array | The lists this contact is in, each with `id` and `name`. |
## Errors
| Status | When |
|---|---|
| `404` | No contact with this id in your organization |
---
# List Contact Lists
> List the contact lists in your organization with their sizes
URL: https://docs.lemuai.com/api-reference/contacts/lists
Returns your contact lists a page at a time, with how many contacts each holds.
**Endpoint:** `GET /api/v1/contacts/lists`
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | No | Page number, starting at `1`. Default `1`. |
| `limit` | integer | No | Lists per page, `1` to `100`. Default `50`. |
**Example request:**
**cURL**
```bash
curl https://app.lemuai.com/api/v1/contacts/lists \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/lists", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts/lists",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"lists": [
{
"id": 55,
"organization_id": 7,
"name": "October renewals",
"description": "Gold and silver plans renewing in November",
"metadata": {},
"column_schema": [],
"created_at": "2026-10-24T09:12:40Z",
"updated_at": "2026-10-24T09:12:40Z",
"member_count": 1240
}
],
"total_count": 1,
"page": 1,
"limit": 50,
"total_pages": 1
}
```
**Each list:**
| Field | Type | Description |
|---|---|---|
| `id` | integer | The list's id. Use it with [List the contacts in a list](https://docs.lemuai.com/api-reference/contacts/list-members). |
| `organization_id` | integer | Your organization's id. |
| `name` | string | The list's name. This is what `list_name` matches when upserting. |
| `description` | string or null | The list's description. |
| `metadata` | object | Extra information stored on the list. |
| `column_schema` | array | The extra columns this list has (from imported files or sheets). |
| `created_at`, `updated_at` | string | Timestamps (ISO 8601, UTC). |
| `member_count` | integer | How many contacts are in the list. |
The page fields `total_count`, `page`, `limit`, and `total_pages` work as in [List contacts](https://docs.lemuai.com/api-reference/contacts/list).
---
# List Contacts in a List
> Page through, sort, and search the contacts in one contact list
URL: https://docs.lemuai.com/api-reference/contacts/list-members
Returns the contacts in one list. Unlike [List contacts](https://docs.lemuai.com/api-reference/contacts/list), you can sort the results and fetch up to 1,000 contacts per page.
**Endpoint:** `GET /api/v1/contacts/lists/{list_id}/contacts`
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `list_id` | integer | Yes | The list's `id` from [List contact lists](https://docs.lemuai.com/api-reference/contacts/lists). |
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `page` | integer | No | Page number, starting at `1`. Default `1`. |
| `limit` | integer | No | Contacts per page, `1` to `1000`. Default `25`. |
| `sort_by` | string | No | Column to sort by. Default `added_at` (when the contact joined the list). |
| `sort_dir` | string | No | `desc` (default) or `asc`. |
| `search` | string | No | Text to look for in name, phone, email, and company. |
**Example request:**
**cURL**
```bash
curl -G https://app.lemuai.com/api/v1/contacts/lists/55/contacts \
-H "X-API-Key: lemu_your_api_key" \
--data-urlencode "limit=500" \
--data-urlencode "sort_dir=asc"
```
**JavaScript**
```js
const params = new URLSearchParams({
"limit": "500",
"sort_dir": "asc",
});
const res = await fetch(`https://app.lemuai.com/api/v1/contacts/lists/55/contacts?${params}`, {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts/lists/55/contacts",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
params={
"limit": "500",
"sort_dir": "asc",
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**: the same shape as [List contacts](https://docs.lemuai.com/api-reference/contacts/list): `contacts`, `total_count`, `page`, `limit`, and `total_pages`.
## Errors
| Status | When |
|---|---|
| `404` | No list with this id in your organization |
---
# Contact Consent
> Read and record a contact's opt-in or opt-out for email, SMS, WhatsApp and voice
URL: https://docs.lemuai.com/api-reference/contacts/consents
Each contact has a consent status for every channel. LemuAI checks it before a journey or campaign sends a message or places a call, so recording opt-ins and opt-outs from your own system (a signup form, a preference center, a support ticket) keeps your messages within what each person agreed to.
## How consent works
Every channel has one of three states:
| Status | Meaning |
|---|---|
| `subscribed` | The person opted in to this channel. |
| `unsubscribed` | The person opted out of this channel. On WhatsApp this stops marketing: replies in a chat they start, utility templates and authentication codes still go. |
| `null` (unknown) | Nothing has been recorded for this channel yet. |
What happens when the status is unknown depends on the channel:
| Channel | Unknown means |
|---|---|
| `voice` | Allowed |
| `whatsapp` | Allowed |
| `email` | Not allowed for marketing email |
| `sms` | Not allowed |
The contact's `opted_out` flag is a separate "do not contact" switch. When it is `true`, no channel is allowed, whatever the per-channel status says. Recording a channel status with this API doesn't change `opted_out`.
Each response includes `can_contact` for every channel, which applies all of these rules for you.
**Note:** For marketing email, your workspace's email settings can also allow sending when consent is unknown. Transactional email (order and account updates sent with [Send a transactional email](https://docs.lemuai.com/api-reference/email/send)) doesn't need consent, but is never sent to an address on your suppression list, for example after a hard bounce, a spam complaint or an unsubscribe.
## Get a contact's consent
Returns the consent state for all four channels, including channels with nothing recorded.
**Endpoint:** `GET /api/v1/contacts/{contact_id}/consents`
### Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
### Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `contact_id` | integer | Yes | The contact's `id`, from [List contacts](https://docs.lemuai.com/api-reference/contacts/list) or an upsert response. |
**Example request:**
**cURL**
```bash
curl https://app.lemuai.com/api/v1/contacts/901/consents \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/901/consents", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts/901/consents",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
### Response
**`200`**
```json
{
"contact_id": 901,
"opted_out": false,
"consents": [
{
"channel": "email",
"status": "subscribed",
"source": "signup_form",
"source_detail": { "form": "footer-newsletter" },
"updated_at": "2026-10-20T08:12:44Z",
"can_contact": true
},
{
"channel": "sms",
"status": null,
"source": null,
"source_detail": {},
"updated_at": null,
"can_contact": false
},
{
"channel": "whatsapp",
"status": "unsubscribed",
"source": "manual",
"source_detail": {},
"updated_at": "2026-10-22T11:03:10Z",
"can_contact": false
},
{
"channel": "voice",
"status": null,
"source": null,
"source_detail": {},
"updated_at": null,
"can_contact": true
}
]
}
```
| Field | Type | Description |
|---|---|---|
| `contact_id` | integer | The contact. |
| `opted_out` | boolean | The contact's "do not contact" switch. When `true`, `can_contact` is `false` for every channel. |
| `consents` | array | One entry per channel: `email`, `sms`, `whatsapp` and `voice`. |
| `consents[].channel` | string | The channel. |
| `consents[].status` | string or null | `subscribed`, `unsubscribed`, or `null` when nothing has been recorded. |
| `consents[].source` | string or null | Where the latest status came from, as sent when it was recorded (for example `manual`, `signup_form` or `checkout`). |
| `consents[].source_detail` | object | Any extra details sent with the latest status. |
| `consents[].updated_at` | string or null | When the status was last recorded, in ISO 8601 (UTC). |
| `consents[].can_contact` | boolean | Whether a message or call on this channel may go to this contact right now. |
## Record consent for one channel
Sets the status for one channel. Every change is also kept in the contact's consent history.
**Endpoint:** `PUT /api/v1/contacts/{contact_id}/consents/{channel}`
### Headers (record)
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
### Path parameters (record)
| Name | Type | Required | Description |
|---|---|---|---|
| `contact_id` | integer | Yes | The contact's `id`. |
| `channel` | string | Yes | `email`, `sms`, `whatsapp` or `voice`. |
### Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `status` | string | Yes | `subscribed` or `unsubscribed`. |
| `source` | string | No | Where the decision came from, 1 to 64 characters, for example `signup_form`, `checkout` or `support`. Default `manual`. |
| `source_detail` | object | No | Any extra details you want kept with the decision, such as a form name or the text the person agreed to. |
**Example request:**
**cURL**
```bash
curl -X PUT https://app.lemuai.com/api/v1/contacts/901/consents/whatsapp \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"status": "subscribed",
"source": "checkout",
"source_detail": { "order_id": "SO-10422", "checkbox": "Send me order updates on WhatsApp" }
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/901/consents/whatsapp", {
method: "PUT",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"status": "subscribed",
"source": "checkout",
"source_detail": {
"order_id": "SO-10422",
"checkbox": "Send me order updates on WhatsApp"
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.put(
"https://app.lemuai.com/api/v1/contacts/901/consents/whatsapp",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"status": "subscribed",
"source": "checkout",
"source_detail": {
"order_id": "SO-10422",
"checkbox": "Send me order updates on WhatsApp",
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
### Response (record)
**`200`**: the full consent state for the contact, in the same shape as [Get a contact's consent](#get-a-contacts-consent).
### Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid. |
| `404` | No contact with this id in your organization. |
| `422` | `channel` isn't one of the four channels, `status` isn't `subscribed` or `unsubscribed`, or `source` is empty or too long. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Contact Activity
> Get everything one contact did, from every source, newest first
URL: https://docs.lemuai.com/api-reference/contacts/activity
Returns a contact's activity timeline, newest first: events you sent, Shopify orders, website visits, message status changes, segment changes and custom record changes. It is the same timeline as the **Activity** tab on the contact's page.
The timeline covers the whole person:
- events stored against contacts that were later [merged](https://docs.lemuai.com/api-reference/events/trigger#how-the-contact-is-found) into this one;
- website visits made before the person was identified, through the visitor ids linked to the contact.
**Info:** **Setup required.** Activity is read from the event store. If the event store isn't turned on for your workspace, the response has `enabled: false` and no events. Use [List events](https://docs.lemuai.com/api-reference/events/list) in that case.
**Endpoint:** `GET /api/v1/contacts/{contact_id}/activity`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `contact_id` | integer | Yes | The contact's `id`, from [List contacts](https://docs.lemuai.com/api-reference/contacts/list) or an upsert response. |
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | integer | No | How many events to return, 1 to 200. Default `50`. |
| `before` | string | No | Only return events before this time, in ISO 8601. To get the next page, pass the `next_before` value from the previous response. |
**Example request:**
**cURL**
```bash
curl "https://app.lemuai.com/api/v1/contacts/901/activity?limit=20" \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/901/activity?limit=20", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts/901/activity?limit=20",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"enabled": true,
"events": [
{
"event_id": "3f6c2a9e-8d1b-5c7a-9e42-1b7d0c5a6f13",
"event_type": "Purchase",
"occurred_at": "2026-10-27T09:14:02.511000Z",
"source": "api",
"contact_id": 901,
"anonymous_id": null,
"properties": { "order_id": "SO-10422", "value": 2499, "currency": "INR" }
},
{
"event_id": "a81d4c0e-27f3-4b0a-9a55-6c1e2f7b9d40",
"event_type": "PageView",
"occurred_at": "2026-10-27T09:02:40.118000Z",
"source": "pixel",
"contact_id": null,
"anonymous_id": "6b1e2c4f-9a7d-4e3b-8c21-0f5d7a9e3b12",
"properties": { "url": "https://shop.example.com/products/running-shoes" }
}
],
"next_before": null
}
```
| Field | Type | Description |
|---|---|---|
| `enabled` | boolean | `false` when the event store isn't turned on. `events` is then empty. |
| `events` | array | The events on this page, newest first. |
| `events[].event_id` | string | The event's unique id (UUID). |
| `events[].event_type` | string | The event name, for example `Purchase`, `PageView` or `message_delivered`. Events stored before Lemu switched to Meta's [standard event names](https://docs.lemuai.com/website-pixel/standard-events) keep their older name, such as `order_placed` or `page_viewed`. |
| `events[].occurred_at` | string | When it happened, in ISO 8601 (UTC). |
| `events[].source` | string | Where it came from: `api`, `shopify`, `pixel`, `messaging`, `segments`, `records` or `backfill`. See [Event sources](https://docs.lemuai.com/api-reference/events/list#event-sources). |
| `events[].contact_id` | integer or null | The contact the event was stored against: this contact or one merged into it. `null` for website activity from before the person was identified. |
| `events[].anonymous_id` | string or null | The website or app visitor id, for events from a tracking source. |
| `events[].properties` | object | The details of the event. |
| `next_before` | string or null | Pass this as `before` to get the next page. `null` on the last page. |
## Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid. |
| `404` | No contact with this id in your organization. |
| `503` | The event store couldn't be read right now. Try again shortly. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Contact Messages
> List every message and call to or from one contact, on any channel, with delivery status
URL: https://docs.lemuai.com/api-reference/contacts/messages
Returns every message sent to or received from a contact, newest first, on every channel: WhatsApp, email, SMS and voice calls. Each entry shows where the message is in its life (sent, delivered, read, failed) and what sent it.
**Endpoint:** `GET /api/v1/contacts/{contact_id}/messages`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `contact_id` | integer | Yes | The contact's `id`, from [List contacts](https://docs.lemuai.com/api-reference/contacts/list) or an upsert response. |
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `limit` | integer | No | How many messages to return, 1 to 200. Default `50`. |
| `before_id` | integer | No | Only return messages older than the message with this `id`. To get the next page, pass the `next_before_id` value from the previous response. |
**Example request:**
**cURL**
```bash
curl "https://app.lemuai.com/api/v1/contacts/901/messages?limit=20" \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/contacts/901/messages?limit=20", {
method: "GET",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
},
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/contacts/901/messages?limit=20",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"messages": [
{
"id": 77120,
"channel": "whatsapp",
"direction": "outbound",
"status": "read",
"provider": "meta",
"provider_status": "read",
"template_name": "cart_reminder",
"text": "Hi Priya, you left something in your cart. Complete your order here: https://le2.in/abc123",
"source_type": "automation",
"source_id": 3318,
"workflow_run_id": null,
"error": null,
"meta": {},
"created_at": "2026-10-27T10:14:05Z",
"sent_at": "2026-10-27T10:14:06Z",
"delivered_at": "2026-10-27T10:14:09Z",
"read_at": "2026-10-27T10:20:31Z",
"failed_at": null
},
{
"id": 77064,
"channel": "voice",
"direction": "outbound",
"status": "delivered",
"provider": "plivo",
"provider_status": "completed",
"template_name": null,
"source_type": "campaign",
"source_id": 214,
"workflow_run_id": 51290,
"error": null,
"meta": { "duration": 94 },
"created_at": "2026-10-26T15:02:11Z",
"sent_at": "2026-10-26T15:02:12Z",
"delivered_at": "2026-10-26T15:02:20Z",
"read_at": null,
"failed_at": null
}
],
"next_before_id": null
}
```
| Field | Type | Description |
|---|---|---|
| `messages` | array | The messages on this page, newest first. |
| `messages[].id` | integer | The message's id. |
| `messages[].channel` | string | `whatsapp`, `email`, `sms` or `voice`. A call is one message on the `voice` channel. |
| `messages[].direction` | string | `outbound` (sent to the contact) or `inbound` (received from the contact). |
| `messages[].status` | string | Where the message is now. See [Message status](#message-status). |
| `messages[].provider` | string or null | The service that carried the message, for example the WhatsApp, email or telephony provider. |
| `messages[].provider_status` | string or null | The provider's own last status word, before LemuAI mapped it to `status`. |
| `messages[].template_name` | string or null | The WhatsApp or email template used, if any. |
| `messages[].text` | string or null | The message's text, up to 1,000 characters: what was written, or a template's filled-in text. `null` for calls and messages with no text. |
| `messages[].source_type` | string or null | What sent it: `automation` (a journey), `campaign`, `voice_agent` (an agent during a call), `transactional` (the [transactional email API](https://docs.lemuai.com/api-reference/email/send)), `inbox` (a team member replying in the Inbox), `manual` (a call placed by hand or through the API), `inbound_call`, `customer` (a message the contact sent you) or `test`. |
| `messages[].source_id` | integer or null | The id of what sent it, such as the journey run, the campaign or the call. |
| `messages[].workflow_run_id` | integer or null | The call this message is (voice), or the call it was sent during (for example a WhatsApp message sent by an agent tool). |
| `messages[].error` | string or null | Why the message failed, when `status` is `failed`. |
| `messages[].meta` | object | Extra details about the message, for example a call's `duration` in seconds. |
| `messages[].created_at` | string | When the message was created, in ISO 8601 (UTC). |
| `messages[].sent_at`, `delivered_at`, `read_at`, `failed_at` | string or null | When the message reached each status. `null` if it hasn't. |
| `next_before_id` | integer or null | Pass this as `before_id` to get the next page. `null` on the last page. |
## Message status
Outbound messages move forward through these statuses, or end as `failed`:
| Status | Meaning |
|---|---|
| `queued` | Waiting to be sent. |
| `sent` | Handed to the provider. |
| `delivered` | Reached the person. For a call, the call was answered. |
| `read` | The person opened it. For email, the email was opened. |
| `clicked` | For email, the person clicked a tracked link. |
| `failed` | It couldn't be sent or delivered. See `error`. |
| `received` | An inbound message from the contact. |
## Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid. |
| `404` | No contact with this id in your organization. |
| `422` | `limit` is outside 1 to 200, or `before_id` isn't a number. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Overview
> Send custom records such as orders, subscriptions or bookings from your system to Lemu AI
URL: https://docs.lemuai.com/api-reference/records/overview
**Custom records** hold data about your contacts that doesn't fit on the contact itself, such as orders, subscriptions, bookings or policies. You define each **record type** and its fields in the dashboard under **Records**. See [Custom Records](https://docs.lemuai.com/records/overview) for how to set one up and how journeys, segments and messages use records.
The records API keeps those records in step with your own system:
| Method | Endpoint | Purpose |
|---|---|---|
| `PUT` | `/objects/{api_name}/records/{key}` | [Create or update one record](https://docs.lemuai.com/api-reference/records/upsert) |
| `POST` | `/objects/{api_name}/records/batch` | [Create or update up to 1,000 records](https://docs.lemuai.com/api-reference/records/batch) in one request |
Creating record types, changing their fields, importing CSV files and deleting records are done in the dashboard.
## Key ideas
| Term | Meaning |
|---|---|
| `api_name` | The record type's API name, for example `subscription`. It is made from the record type's name when you create it, in lower case with underscores. |
| Record key | The value that identifies a record within its type, for example a subscription id. Sending the same key again updates that record instead of creating a new one. |
| Owner | The contact a record belongs to. Every record of a normal record type has one owner. A [catalog](https://docs.lemuai.com/records/catalog) (such as products) has no owner. |
| `data` | The record's fields, as an object of field name and value. Only fields defined on the record type are accepted. |
## How updates work
Records are merged, not replaced:
- fields you send replace the stored value;
- fields you don't send keep their stored value;
- a field sent as `null` or an empty string is cleared.
Each change records an `object_created` or `object_updated` event on the owner's timeline (source `records`), so journeys and segments can react to it. Personal fields aren't copied into the event.
## Field values
| Field type | Send |
|---|---|
| Text | A string, up to 2,000 characters. |
| Number | A number, or a string that is a number. |
| True or false | `true` or `false` (also `"yes"`, `"no"`, `"1"`, `"0"`). |
| Date | A date, for example `"2026-11-30"`. |
| Date and time | An ISO 8601 date and time, for example `"2026-11-30T18:00:00Z"`. |
| Choice | One of the field's options. Upper and lower case are ignored. |
| Link | An `http` or `https` link, up to 2,000 characters. |
A record can be at most 16 KB once saved. Fields marked as required must have a value.
**Note:** Fields marked as personal are partly hidden (`•••`) in the dashboard for team members without permission to view personal data. API keys always see the full values.
## Plan limits
Your plan sets how many record types and records your organization can store. A request that would create more records than your plan allows returns `402`.
---
# Create or Update a Record
> Create or update one custom record by its key, and set the contact it belongs to
URL: https://docs.lemuai.com/api-reference/records/upsert
Creates a record, or updates it if a record with the same key already exists. Fields you send replace the stored values, fields you don't send are kept, and `null` clears a field. See [how updates work](https://docs.lemuai.com/api-reference/records/overview#how-updates-work).
**Endpoint:** `PUT /api/v1/objects/{api_name}/records/{key}`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `api_name` | string | Yes | The record type's API name, for example `subscription`. |
| `key` | string | Yes | The record's key, for example `SUB-1042`. If `data` also contains the key field, it must have the same value. |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `data` | object | No | The record's fields, as field name and value. Only fields defined on the record type are accepted. See [field values](https://docs.lemuai.com/api-reference/records/overview#field-values). |
| `phone` | string | No | The owner's phone number in international format. |
| `email` | string | No | The owner's email address. |
| `external_id` | string | No | Your own id for the owner. |
| `shopify_customer_id` | string | No | The owner's Shopify customer id. |
| `contact_id` | integer | No | The owner's Lemu AI contact id. If that contact was merged into another, the record goes to the contact it was merged into. |
## Choosing the owner
Records of a normal record type belong to one contact. A [catalog](https://docs.lemuai.com/records/catalog) has no owner, so these fields are ignored for it.
1. If you send `contact_id`, that contact is the owner.
2. Otherwise, if you send `phone`, `email`, `external_id` or `shopify_customer_id`, Lemu AI finds the contact the same way as [Send an event](https://docs.lemuai.com/api-reference/events/trigger#how-the-contact-is-found). A new contact (tagged `record`) is only created from a `phone` or `email`.
3. If you send no owner fields and the record already exists, it keeps its owner.
4. A new record with no owner fields is rejected.
Sending a different owner for an existing record moves the record to that contact.
**Example request:**
**cURL**
```bash
curl -X PUT https://app.lemuai.com/api/v1/objects/subscription/records/SUB-1042 \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"email": "priya@example.com",
"data": {
"plan": "Gold",
"status": "active",
"renews_on": "2026-11-30",
"monthly_amount": 499
}
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/objects/subscription/records/SUB-1042", {
method: "PUT",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"email": "priya@example.com",
"data": {
"plan": "Gold",
"status": "active",
"renews_on": "2026-11-30",
"monthly_amount": 499
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.put(
"https://app.lemuai.com/api/v1/objects/subscription/records/SUB-1042",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"email": "priya@example.com",
"data": {
"plan": "Gold",
"status": "active",
"renews_on": "2026-11-30",
"monthly_amount": 499,
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**
```json
{
"status": "created",
"record": {
"id": 18342,
"key": "SUB-1042",
"contact_id": 901,
"data": {
"subscription_id": "SUB-1042",
"plan": "Gold",
"status": "active",
"renews_on": "2026-11-30",
"monthly_amount": 499
},
"created_at": "2026-10-27T09:30:12Z",
"updated_at": "2026-10-27T09:30:12Z",
"deleted_at": null
}
}
```
| Field | Type | Description |
|---|---|---|
| `status` | string | `created` (new record, or a deleted one brought back), `updated` (a field or the owner changed) or `unchanged` (nothing changed). |
| `record.id` | integer | The record's id in Lemu AI. |
| `record.key` | string | The record's key. |
| `record.contact_id` | integer or null | The owner. `null` for catalog records. |
| `record.data` | object | All of the record's fields after the update, including the key field. |
| `record.created_at`, `record.updated_at` | string | Timestamps, in ISO 8601 (UTC). |
| `record.deleted_at` | string or null | When the record was deleted. Always `null` here. |
## Errors
| Status | When |
|---|---|
| `400` | There's no record type with this `api_name`, the record type is archived, the record has no owner, no contact matches the owner, a new owner contact couldn't be created because your plan's contact limit is reached, a field is unknown or has a value of the wrong type, a required field is missing, the key in `data` doesn't match the path, or the record is larger than 16 KB. `detail` lists every problem. |
| `401` | The API key is missing or not valid. |
| `402` | Creating the record would take your organization over its plan's record limit. |
| `422` | The body isn't valid JSON, or an owner field is too long. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Create or Update Records in Bulk
> Create or update up to 1,000 custom records of one record type in a single request
URL: https://docs.lemuai.com/api-reference/records/batch
Creates or updates up to 1,000 records of one record type. Each record works the same way as [Create or update a record](https://docs.lemuai.com/api-reference/records/upsert), and each one succeeds or fails on its own, so one bad row doesn't stop the rest.
**Endpoint:** `POST /api/v1/objects/{api_name}/records/batch`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `api_name` | string | Yes | The record type's API name, for example `subscription`. |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `records` | array | Yes | Between 1 and 1,000 records. Each one accepts the fields below. |
**Each record:**
| Field | Type | Description |
|---|---|---|
| `key` | string | The record's key. If you leave it out, the value of the key field in `data` is used. |
| `data` | object | The record's fields. See [field values](https://docs.lemuai.com/api-reference/records/overview#field-values). |
| `phone`, `email`, `external_id`, `shopify_customer_id`, `contact_id` | | The owner, as in [Choosing the owner](https://docs.lemuai.com/api-reference/records/upsert#choosing-the-owner). Needed for a new record of a normal record type. |
If the same key appears more than once in one request, the last one is saved and the earlier ones are reported as errors.
**Example request:**
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/objects/subscription/records/batch \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"records": [
{
"key": "SUB-1042",
"email": "priya@example.com",
"data": { "plan": "Gold", "status": "active", "renews_on": "2026-11-30" }
},
{
"phone": "+919812345678",
"data": { "subscription_id": "SUB-1043", "plan": "Silver", "status": "paused" }
},
{
"key": "SUB-1044",
"data": { "plan": "Platinum" }
}
]
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/objects/subscription/records/batch", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"records": [
{
"key": "SUB-1042",
"email": "priya@example.com",
"data": {
"plan": "Gold",
"status": "active",
"renews_on": "2026-11-30"
}
},
{
"phone": "+919812345678",
"data": {
"subscription_id": "SUB-1043",
"plan": "Silver",
"status": "paused"
}
},
{
"key": "SUB-1044",
"data": {
"plan": "Platinum"
}
}
]
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/objects/subscription/records/batch",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"records": [
{
"key": "SUB-1042",
"email": "priya@example.com",
"data": {
"plan": "Gold",
"status": "active",
"renews_on": "2026-11-30",
},
},
{
"phone": "+919812345678",
"data": {
"subscription_id": "SUB-1043",
"plan": "Silver",
"status": "paused",
},
},
{
"key": "SUB-1044",
"data": {
"plan": "Platinum",
},
},
],
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**: the request was processed. Check each result to see which records were saved.
```json
{
"results": [
{ "key": "SUB-1042", "status": "updated", "record_id": 18342, "contact_id": 901 },
{ "key": "SUB-1043", "status": "created", "record_id": 18343, "contact_id": 1207 },
{
"key": "SUB-1044",
"status": "error",
"error": "A new record needs its owner: phone, email, external_id, shopify_customer_id or contact_id"
}
],
"counts": { "updated": 1, "created": 1, "error": 1 }
}
```
| Field | Type | Description |
|---|---|---|
| `results` | array | One entry per record you sent, in the same order. |
| `results[].key` | string | The record's key. Missing when the row had no key at all. |
| `results[].status` | string | `created`, `updated`, `unchanged` or `error`. |
| `results[].record_id` | integer | The record's id. Not included for rows with an error. |
| `results[].contact_id` | integer | The record's owner. Not included for catalog records or rows with an error. |
| `results[].error` | string | Why the row failed. Only included when `status` is `error`. |
| `counts` | object | How many rows ended with each status. |
## Errors
These apply to the whole request. Problems with a single record are reported in `results` instead.
| Status | When |
|---|---|
| `400` | There's no record type with this `api_name`, or the record type is archived. |
| `401` | The API key is missing or not valid. |
| `402` | The new records would take your organization over its plan's record limit. Nothing is saved. |
| `422` | `records` is missing, empty or has more than 1,000 items, or a field has the wrong type. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Send a Transactional Email
> Send an order, shipping or account email to one person from a saved email template
URL: https://docs.lemuai.com/api-reference/email/send
Sends one transactional email, such as an order confirmation, a shipping update or a password reset, from an [email template](https://docs.lemuai.com/email/templates) you built in the dashboard. Values you send in `data` fill the template's merge tags.
Use this only for messages the person needs. Marketing email (offers, newsletters, reminders to buy) goes through [email campaigns](https://docs.lemuai.com/email/campaigns) and journeys, which check consent and add an unsubscribe link.
**Info:** **Setup required.** Before you can send, your account needs:
- LemuAI's email service turned on. Contact [hello@lemuai.com](mailto:hello@lemuai.com) to enable it.
- A verified sending domain and at least one sender. See [Email Setup](https://docs.lemuai.com/email/setup).
- A saved template. Transactional templates are best marked as transactional in the editor.
**Endpoint:** `POST /api/v1/email/send`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your organization. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `template_id` | integer | Yes | The template to send. It is the number at the end of the template's address when you open it in the dashboard, for example `/email/templates/42`. |
| `to` | string | Yes | The recipient's email address, 3 to 320 characters. |
| `data` | object | No | Values for the template's merge tags, such as order id, items or total. See below. |
| `sender_id` | integer | No | The sender (From name and address) to use. Default: your default sender from Email Setup. |
| `template_version` | integer | No | A saved version of the template to send. Default: the latest saved version. |
| `subject` | string | No | A subject line to use instead of the template's, up to 998 characters. Merge tags work here too. |
## What the template can use
| Merge tag | Filled with |
|---|---|
| `{{ event.order_id }}` or `{{ data.order_id }}` | A value from the `data` you sent. Both names work, so templates built for journeys with `event.*` tags can be reused here. |
| `{{ contact.first_name }}`, `{{ contact.custom.plan }}` | The contact whose email is `to`, if there is one. Empty if no contact has that address. |
| `{{ organization.name }}`, `{{ organization.address }}` | Your organization's name and postal address. |
Use `| default("there")` for values that may be missing, and `| money("INR")` to format prices. See [Personalize with merge tags](https://docs.lemuai.com/email/templates#personalize-with-merge-tags).
**Example request:**
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/email/send \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"template_id": 42,
"to": "priya@example.com",
"data": {
"order_id": "SO-10422",
"total": 2499,
"items": [
{ "title": "Running shoes", "quantity": 1, "price": 2499 }
],
"tracking_url": "https://track.example.com/SO-10422"
}
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/email/send", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
"template_id": 42,
"to": "priya@example.com",
"data": {
"order_id": "SO-10422",
"total": 2499,
"items": [
{
"title": "Running shoes",
"quantity": 1,
"price": 2499
}
],
"tracking_url": "https://track.example.com/SO-10422"
}
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/email/send",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"template_id": 42,
"to": "priya@example.com",
"data": {
"order_id": "SO-10422",
"total": 2499,
"items": [
{
"title": "Running shoes",
"quantity": 1,
"price": 2499,
},
],
"tracking_url": "https://track.example.com/SO-10422",
},
},
timeout=30,
)
response.raise_for_status()
print(response.json())
```
## Response
**`200`**: the email was handed to the sending service.
```json
{
"message_id": 77341,
"provider_message_id": "0109019a2c5e1f4b-6f1d8c2a-9b7e-4f3a-8d21-5e0c7b9a1d34-000000"
}
```
| Field | Type | Description |
|---|---|---|
| `message_id` | integer | The message's id in LemuAI. Its delivery status (delivered, opened, clicked, bounced) appears in the contact's [messages](https://docs.lemuai.com/api-reference/contacts/messages) when `to` belongs to a contact. |
| `provider_message_id` | string | The sending service's id for the email. |
## Consent and suppression
Transactional email doesn't need the person's email consent, and it is sent even when your marketing email is paused. It is still never sent to an address on your suppression list (for example after a hard bounce, a spam complaint or an unsubscribe). Those requests return `422` with `skipped` set to `suppressed`.
## Errors
| Status | When |
|---|---|
| `400` | The template has never been saved, you have no sender (add one in Email Setup), or `to` isn't a valid email address. |
| `401` | The API key is missing or not valid. |
| `404` | No template with this `template_id` in your organization. |
| `422` | Nothing was sent. `detail.skipped` says why: `domain_not_verified` (the sender's domain isn't verified), `suppressed` (the address is on your suppression list), `render_failed` (a merge tag couldn't be filled, see `detail.message`) or `no_address`. Also returned when a field is missing or has the wrong type. |
| `502` | The sending service refused the email. It is logged as failed. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Send a WhatsApp Template
> Send an approved WhatsApp template to one phone number from your own system, with values for its variables
URL: https://docs.lemuai.com/api-reference/whatsapp/send-template
For: Developers
Checked against LemuAI app version 1.0.53
Related: [Get a WhatsApp Message](https://docs.lemuai.com/api-reference/whatsapp/get-message), [Numbers](https://docs.lemuai.com/whatsapp/numbers), [WhatsApp Messaging](https://docs.lemuai.com/messaging/whatsapp), [Errors](https://docs.lemuai.com/api-reference/errors), [WhatsApp and Inbox](https://docs.lemuai.com/troubleshooting/whatsapp)
Sends one approved WhatsApp template to one phone number from your own system, for example an order update, a payment reminder or a login code. You say which template to send, the number to send it to, and the values for the template's variables. It works like the "send template message" API of WATI, Interakt or AiSensy.
Any approved template can be sent: marketing, utility and authentication. To send to a list of people at once, use a broadcast or a journey in the dashboard instead.
**Info:** **Setup required.** Before you can send, your workspace needs:
- WhatsApp connected under **WhatsApp → Setup**, with at least one number under **WhatsApp → Numbers**.
- An approved template under **WhatsApp → Templates**.
- Money in your **WhatsApp balance**. Recharge under **Usage & Plan → Usage & balances**.
- An API key from **Settings → API Keys**. See [Authentication](https://docs.lemuai.com/api-reference/authentication).
**Endpoint:** `POST /api/v1/whatsapp/messages/template`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your workspace. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
| `Content-Type` | Yes | `application/json` |
## Request body
Name the template with `template_id`, or with `template_name` and `language`.
| Field | Type | Required | Description |
|---|---|---|---|
| `to` | string | Yes | The number to send to, with its country code: `+919876543210` or `919876543210`. Spaces and dashes are fine. A 10-digit number without a country code is refused. |
| `template_id` | integer | One of `template_id` or `template_name` | LemuAI's id for the template, a number such as `44`. Open **WhatsApp → Templates** and click the template: its side panel shows **Template ID** with a copy button. It is not the **Meta template ID** shown next to it. |
| `template_name` | string | One of `template_id` or `template_name` | The template's name exactly as shown under **WhatsApp → Templates**, for example `order_shipped`. |
| `language` | string | With `template_name`, when the template has more than one language | The template's language code, for example `en`, `en_US` or `hi`. `en` also finds `en_US` when that is the template's only English version. Ignored with `template_id`, which already points at one language. |
| `variables` | object | When the template has variables | The values for the template's variables, as text or numbers. See [Variables](#variables). Up to 100 entries. |
| `header_text` | string | When the template's text header has a variable | The value for the header's variable, up to 60 characters. Templates with named variables can give it in `variables` instead. |
| `header_media_url` | string | When the template's header is an image, video or document | A public `https://` link to the file. WhatsApp downloads it when it sends the message. |
| `header_filename` | string | No | The file name WhatsApp shows for a document header, for example `Invoice-10422.pdf`. Default: the file name the link ends in, when it ends in one (`…/Invoice-10422.pdf`). |
| `button_url_value` | string | When a link button's address ends with a variable | The part that goes in place of the variable. For a button to `https://shop.example.com/track/{{1}}`, send `SO-10422`. For a button made with **Count clicks on this button**, send the whole page address to open; see [Link Click Tracking](https://docs.lemuai.com/messaging/link-tracking#template-link-buttons). |
| `coupon_code` | string | When the template has a copy-code button | The code the button copies, up to 15 characters. |
| `product_retailer_ids` | array of strings | For a multi-product template | The content IDs (SKUs) of the products to show, from your WhatsApp catalog. Up to 30. |
| `thumbnail_product_retailer_id` | string | No | For a catalog template: the content ID (SKU) of the product whose photo shows on the message. |
| `from` | string | No | Which of your WhatsApp numbers sends the message, as shown under **WhatsApp → Numbers** (for example `+91 98111 12222`). Default: your default number. |
| `reference` | string | No | Your own id for this message, up to 100 characters, for example your order id. It comes back in the response and in [Get a WhatsApp Message](https://docs.lemuai.com/api-reference/whatsapp/get-message). |
A field that isn't in this table is refused with `422`, so a typo in a field name doesn't go unnoticed.
## Variables
`variables` holds one value for each variable in the template's header and body. The keys depend on how the template was written:
| The template's variables look like | Send |
|---|---|
| `{{1}}`, `{{2}}` (positional) | `{"1": "Priya", "2": "SO-10422"}` |
| `{{first_name}}`, `{{order_id}}` (named) | `{"first_name": "Priya", "order_id": "SO-10422"}` |
| An authentication template (login or verification code) | The code: `{"1": "482913"}`, up to 15 characters. It fills the message and the template's copy-code or autofill button. |
- Every variable needs a value. If one is missing, nothing is sent and the error lists the keys to send.
- `"1"` and `"{{1}}"` both work as keys. Numbers are sent as text: `2499` becomes `2499`.
- WhatsApp doesn't allow a new line, a tab or more than four spaces in a row inside a value. Such a value is refused before sending.
- A text header with a variable takes its value from `header_text`. In a template with positional variables, the header's `{{1}}` is separate from the body's `{{1}}`.
- Keys the template doesn't use are ignored.
**Example request:** the template `order_shipped` has the header "Order `{{1}}`", the body "Hi `{{1}}`, your order `{{2}}` is on its way." and a **Track** button that opens `https://shop.example.com/track/{{1}}`.
**cURL**
```bash
curl -X POST https://app.lemuai.com/api/v1/whatsapp/messages/template \
-H "X-API-Key: lemu_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"to": "+919876543210",
"template_id": 44,
"variables": { "1": "Priya", "2": "SO-10422" },
"header_text": "SO-10422",
"button_url_value": "SO-10422",
"reference": "order-10422"
}'
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/whatsapp/messages/template", {
method: "POST",
headers: {
"X-API-Key": process.env.LEMU_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
to: "+919876543210",
template_id: 44,
variables: { 1: "Priya", 2: "SO-10422" },
header_text: "SO-10422",
button_url_value: "SO-10422",
reference: "order-10422",
}),
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const data = await res.json();
console.log(data.message_id);
```
**Python**
```python
import os
import requests
response = requests.post(
"https://app.lemuai.com/api/v1/whatsapp/messages/template",
headers={
"X-API-Key": os.environ["LEMU_API_KEY"],
},
json={
"to": "+919876543210",
"template_id": 44,
"variables": {"1": "Priya", "2": "SO-10422"},
"header_text": "SO-10422",
"button_url_value": "SO-10422",
"reference": "order-10422",
},
timeout=30,
)
response.raise_for_status()
print(response.json()["message_id"])
```
More examples of the body:
```json
{
"to": "919876543210",
"template_name": "plan_renewal",
"language": "en",
"variables": { "first_name": "Priya", "plan": "Growth" }
}
```
```json
{
"to": "+919876543210",
"template_name": "invoice_ready",
"language": "en",
"variables": { "1": "INV-10422" },
"header_media_url": "https://files.example.com/invoices/INV-10422.pdf",
"header_filename": "Invoice-10422.pdf",
"from": "+91 98111 13333"
}
```
```json
{
"to": "+919876543210",
"template_name": "login_code",
"language": "en",
"variables": { "1": "482913" }
}
```
## Response
**`200`**: WhatsApp accepted the message.
```json
{
"message_id": 90311,
"provider_message_id": "wamid.HBgMOTE5ODc2NTQzMjEwFQIAERgSNkQ5QjE0RjU2QzM0RTI3QjdBAA==",
"status": "sent",
"to": "+919876543210",
"contact_id": 5821,
"template": {
"id": 44,
"name": "order_shipped",
"language": "en",
"category": "utility"
},
"reference": "order-10422"
}
```
| Field | Type | Description |
|---|---|---|
| `message_id` | integer | The message's id in LemuAI. Pass it to [Get a WhatsApp Message](https://docs.lemuai.com/api-reference/whatsapp/get-message) to see whether it was delivered and read. |
| `provider_message_id` | string | WhatsApp's id for the message (`wamid…`). Get a WhatsApp Message accepts it too. |
| `status` | string | Always `sent` here: WhatsApp accepted the message. Delivered, read or failed comes later. |
| `to` | string | The number it was sent to, in `+` and digits form. |
| `contact_id` | integer | The contact the message belongs to. A contact is created when no contact has this number yet. |
| `template` | object | The template that was sent: `id`, `name`, `language` and `category` (`marketing`, `utility` or `authentication`). |
| `reference` | string or null | The `reference` you sent. |
## What happens with the message
- **Cost:** each message is paid from your WhatsApp balance at WhatsApp's rate for the template's category and the recipient's country. A message WhatsApp refuses is refunded.
- **Inbox and contact:** the message shows in the contact's conversation in the [Inbox](https://docs.lemuai.com/messaging/inbox), labelled **API**, and in the contact's messages. When the person replies, the reply lands in the same conversation and opens WhatsApp's 24-hour window, like any other reply.
- **Delivery:** `sent` means WhatsApp accepted it. Whether it was delivered or read, or why it failed, shows a few seconds later in [Get a WhatsApp Message](https://docs.lemuai.com/api-reference/whatsapp/get-message), in the Inbox and in [Contact Messages](https://docs.lemuai.com/api-reference/contacts/messages).
- **Opt-out:** a contact who opted out of all messages is never sent anything, and a marketing template isn't sent to a contact who stopped WhatsApp marketing (STOP, Stop promotions or Stop marketing in WhatsApp). Utility and authentication templates still go. The request returns `422` with `opted_out`.
- **Sending limits:** the per-channel limits under **Settings → Sending Limits** apply to journeys and campaigns, not to this API. Your system decides how often a person gets a message.
- **Marketing templates:** WhatsApp limits how many marketing messages one person gets from all businesses. When it holds one back, the message's status becomes `failed` with WhatsApp's reason.
## Errors
Nothing is charged or sent when the request has a problem. The body is:
```json
{
"detail": {
"error": "missing_values",
"message": "Missing a value for {{2}}. Send variables: {\"2\": \"...\"}.",
"missing": ["2"],
"variables": ["1", "2"]
}
}
```
`error` is a fixed word your code can check. `message` is a sentence that says what to change. `missing_values` also lists the `missing` keys and every key the template takes in `variables`.
| Status | `detail.error` | When |
|---|---|---|
| `400` | `whatsapp_not_ready` | WhatsApp isn't connected, setup isn't finished, payment setup with Meta is still pending, Meta restricted the account, or marketing messages are paused on the sending number. `detail.message` says which. |
| `400` | `template_not_approved` | The template is pending, rejected, paused or disabled. `detail.template_status` holds its status. |
| `401` | | The API key is missing or not valid. |
| `402` | `balance_too_low` | The WhatsApp balance is too low. Recharge under **Usage & Plan → Usage & balances**. |
| `404` | `template_not_found` | No template with this `template_id` in your workspace, no template with this name on the sending number's WhatsApp account, or no version in this `language` (`detail.languages` lists the template's languages). |
| `422` | `template_required` | Neither `template_id` nor `template_name` was sent. |
| `422` | `language_required` | `template_name` matches the template in more than one language. Send `language`. |
| `422` | `missing_values` | A variable, the header value, `header_media_url`, `button_url_value`, `coupon_code` or `product_retailer_ids` is missing. |
| `422` | `invalid_values` | A value has a new line, a tab or more than four spaces in a row, is too long, or isn't text or a number, or a click-counting button got something other than a full `https://` address. |
| `422` | `invalid_number` | `to` isn't a phone number, or has no country code. |
| `422` | `unknown_from_number` | `from` isn't one of your numbers under **WhatsApp → Numbers**. |
| `422` | `opted_out` | The contact opted out of all messages, or stopped WhatsApp marketing and this is a marketing template. |
| `422` | | A field is missing, has the wrong type, or isn't a field of this endpoint. `detail` is then a list of the fields to fix. |
| `502` | `send_failed` | WhatsApp refused the message when it was sent. `detail.message` holds WhatsApp's reason. It shows as failed in the Inbox and is refunded. A number without WhatsApp is usually accepted first and then turns `failed` in [Get a WhatsApp Message](https://docs.lemuai.com/api-reference/whatsapp/get-message). |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the general error format.
---
# Get a WhatsApp Message
> See whether a WhatsApp message was delivered and read, or why it failed
URL: https://docs.lemuai.com/api-reference/whatsapp/get-message
For: Developers
Checked against LemuAI app version 1.0.50
Related: [Send a WhatsApp Template](https://docs.lemuai.com/api-reference/whatsapp/send-template), [Contact Messages](https://docs.lemuai.com/api-reference/contacts/messages), [WhatsApp and Inbox](https://docs.lemuai.com/troubleshooting/whatsapp)
Returns one WhatsApp message with its status: sent, delivered, read or failed, with the time of each step and WhatsApp's reason when it failed. Use it after [Send a WhatsApp Template](https://docs.lemuai.com/api-reference/whatsapp/send-template) to check that the message reached the person.
It works for any WhatsApp message of your workspace, including ones sent by journeys, broadcasts or the Inbox, and replies people sent you.
**Endpoint:** `GET /api/v1/whatsapp/messages/{message_id}`
## Headers
| Name | Required | Description |
|---|---|---|
| `X-API-Key` | Yes | An API key from your workspace. See [Authentication](https://docs.lemuai.com/api-reference/authentication). |
## Path parameters
| Name | Type | Description |
|---|---|---|
| `message_id` | string | The `message_id` that [Send a WhatsApp Template](https://docs.lemuai.com/api-reference/whatsapp/send-template) returned (a number, for example `90311`), or WhatsApp's id for the message (`provider_message_id`, starting with `wamid.`). |
**Example request:**
**cURL**
```bash
curl https://app.lemuai.com/api/v1/whatsapp/messages/90311 \
-H "X-API-Key: lemu_your_api_key"
```
**JavaScript**
```js
const res = await fetch("https://app.lemuai.com/api/v1/whatsapp/messages/90311", {
headers: { "X-API-Key": process.env.LEMU_API_KEY },
});
if (!res.ok) throw new Error(`LemuAI API ${res.status}: ${await res.text()}`);
const message = await res.json();
console.log(message.status);
```
**Python**
```python
import os
import requests
response = requests.get(
"https://app.lemuai.com/api/v1/whatsapp/messages/90311",
headers={"X-API-Key": os.environ["LEMU_API_KEY"]},
timeout=30,
)
response.raise_for_status()
print(response.json()["status"])
```
## Response
**`200`**
```json
{
"message_id": 90311,
"provider_message_id": "wamid.HBgMOTE5ODc2NTQzMjEwFQIAERgSNkQ5QjE0RjU2QzM0RTI3QjdBAA==",
"direction": "outbound",
"status": "read",
"to": "+919876543210",
"contact_id": 5821,
"template_name": "order_shipped",
"source": "api",
"reference": "order-10422",
"error": null,
"text": "Order SO-10422\n\nHi Priya, your order SO-10422 is on its way.\n\n▸ Track",
"created_at": "2026-12-04T10:15:02.118Z",
"sent_at": "2026-12-04T10:15:02.118Z",
"delivered_at": "2026-12-04T10:15:04.530Z",
"read_at": "2026-12-04T10:16:41.002Z",
"clicked_at": null,
"failed_at": null
}
```
| Field | Type | Description |
|---|---|---|
| `message_id` | integer | The message's id in LemuAI. |
| `provider_message_id` | string or null | WhatsApp's id for the message. |
| `direction` | string | `outbound` for a message you sent, `inbound` for one the person sent you. |
| `status` | string | Where the message is now. See the table below. |
| `to` | string or null | The number it was sent to. Null for an inbound message. |
| `contact_id` | integer or null | The contact the message belongs to. |
| `template_name` | string or null | The template's name, for a template message. |
| `source` | string or null | What sent it: `api` for this API, `automation` for a journey, `broadcast`, `inbox` for your team, `ai_assistant` and others. |
| `reference` | string or null | The `reference` sent with [Send a WhatsApp Template](https://docs.lemuai.com/api-reference/whatsapp/send-template). |
| `error` | string or null | Why the message failed, as WhatsApp gave it. |
| `text` | string or null | What the person sees: the template's text with its values filled in, then its button labels. Up to 1,000 characters. |
| `created_at` | string | When LemuAI recorded the message (ISO 8601, UTC). |
| `sent_at`, `delivered_at`, `read_at`, `clicked_at`, `failed_at` | string or null | When the message reached each step. Null for a step it hasn't reached. |
### Statuses
| `status` | Meaning |
|---|---|
| `sent` | WhatsApp accepted the message. |
| `delivered` | It reached the person's phone. |
| `read` | The person opened it. Only shows when the person has read receipts turned on in WhatsApp; otherwise it stays `delivered`. |
| `clicked` | The person opened a link in it that counts clicks. |
| `failed` | WhatsApp couldn't deliver it. `error` says why, for example the number has no WhatsApp account or WhatsApp held back a marketing message. A failed template message is refunded. |
| `received` | A message the person sent you. |
Statuses only move forward: a message that was `read` doesn't go back to `delivered`. WhatsApp usually reports delivery within seconds, but a phone that is off reports it when it comes back online. If you check in a loop, wait at least 30 seconds between checks.
## Errors
| Status | When |
|---|---|
| `401` | The API key is missing or not valid. |
| `404` | No WhatsApp message with this id in your workspace. `detail.error` is `message_not_found`. |
See [Errors](https://docs.lemuai.com/api-reference/errors) for the error format.
---
# Overview
> Create and work LemuTickets tickets from your ERP or other systems with the LemuTickets REST API
URL: https://docs.lemuai.com/tickets-api/overview
LemuTickets is the service desk in the Lemu family: complaints, requests, tasks and incidents become tickets with an owner, a status, a deadline and a full history. The app at [tickets.lemuai.com](https://tickets.lemuai.com) is built on this same API, so anything your team does in the app, your own systems can do too.
This reference covers what an ERP or back-office system usually needs:
| Task | Endpoint |
|---|---|
| Raise a ticket when something goes wrong in your system | [Create a ticket](https://docs.lemuai.com/tickets-api/tickets/create) |
| Show a customer's tickets, or a queue, in your own screens | [List and search tickets](https://docs.lemuai.com/tickets-api/tickets/list) with [TQL](https://docs.lemuai.com/tickets-api/tql) |
| Read one ticket with its status, SLA and fields | [Get a ticket](https://docs.lemuai.com/tickets-api/tickets/get) |
| Change the priority, assignee, labels or custom fields | [Update a ticket](https://docs.lemuai.com/tickets-api/tickets/update) |
| Move a ticket through its workflow (start work, resolve, close) | [List available transitions](https://docs.lemuai.com/tickets-api/tickets/list-transitions) and [Transition a ticket](https://docs.lemuai.com/tickets-api/tickets/transition) |
| Reply to the customer or add an internal note | [Add a comment](https://docs.lemuai.com/tickets-api/tickets/add-comment) |
| Record time spent | [Log work](https://docs.lemuai.com/tickets-api/tickets/log-work) |
| Keep customers in sync with your records | [Requesters](https://docs.lemuai.com/tickets-api/requesters/upsert) and [Accounts](https://docs.lemuai.com/tickets-api/accounts/list) |
| Attach files, such as invoices or photos | [Upload an attachment](https://docs.lemuai.com/tickets-api/attachments/upload) |
| Hear about changes as they happen | [Webhooks](https://docs.lemuai.com/tickets-api/webhooks) |
| Show tickets inside your ERP without building screens | [Embedding in your ERP](https://docs.lemuai.com/tickets-api/embedding) |
Setting up projects, workflows, SLAs, automations and teams is done in the LemuTickets app.
## Base URL
All requests go to:
```
https://api.tickets.lemuai.com/v1
```
The version (`v1`) is part of the path. Changes within `v1` only add things: new endpoints, new optional fields and new response fields. Write your code so it ignores response fields it does not know.
## Authentication
Send an API key in the `Authorization` header. Create keys in LemuTickets under **Settings → API keys and webhooks**. See [Authentication](https://docs.lemuai.com/tickets-api/authentication) for scopes and OAuth apps.
## Your first request
Find the key of the project you want to create tickets in:
```bash
curl https://api.tickets.lemuai.com/v1/projects \
-H "Authorization: Bearer ltk_live_your_api_key"
```
```json
{
"data": [
{
"id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13",
"key": "SUP",
"name": "Customer Support",
"open_tickets": 128
}
]
}
```
The response above is shortened. Then create a ticket in that project:
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: erp-complaint-58213" \
-d '{
"project": "SUP",
"title": "Refund not received for order 58213",
"priority": "p2",
"requester": { "name": "Priya Sharma", "email": "priya@example.com" }
}'
```
The response is the new ticket, with its key (for example `SUP-1042`). Use the key or the `id` in every other ticket endpoint.
## Request and response format
- Send request bodies as JSON with `Content-Type: application/json`. The one exception is [Upload an attachment](https://docs.lemuai.com/tickets-api/attachments/upload), which takes a file as `multipart/form-data`.
- Responses are JSON. Times are ISO 8601 in UTC, for example `2026-11-25T09:12:40.512000+00:00`. Ids are UUIDs.
- Lists return `{"data": [...]}`, and paged lists add `next_cursor`. See [Conventions](https://docs.lemuai.com/tickets-api/conventions).
- Errors always have the same shape. See [Errors](https://docs.lemuai.com/tickets-api/errors).
- Every response has an `X-Request-Id` header. Include it when you contact support about a request.
---
# Authentication
> Authenticate LemuTickets API requests with a scoped API key or an OAuth app
URL: https://docs.lemuai.com/tickets-api/authentication
There are two ways to call the LemuTickets API:
| Use | When |
|---|---|
| **API key** | Your own server talks to LemuTickets, for example your ERP syncing tickets. This is the usual choice. |
| **OAuth app** | You build an app that acts for a person who approves it (authorization code), or a server integration that should not use a long-lived key (client credentials). |
Both are sent as a bearer token in the `Authorization` header.
**Warning:** API keys, client secrets and access tokens act on your organization's data. Keep them on your server. Never put them in a browser, a mobile app or a public repository. To show tickets in a browser, use an [embed token](https://docs.lemuai.com/tickets-api/embedding) instead.
## API keys
### Create a key
1. In LemuTickets, open **Settings → API keys and webhooks** and stay on the **API keys** tab.
2. Click **Create key**.
3. Fill in the form:
- **Name**: where the key is used, for example `ERP sync`.
- **Mode**: **Live** keys start with `ltk_live_`, **Test** keys with `ltk_test_`. The mode only labels the key; both work on the same organization and data.
- **Scopes**: pick a preset (**Read only**, **Agent** or **Full access**) or **Custom** to choose scopes one by one. See [scopes](#scopes) below.
- **Projects**: limit the key to some projects. Empty means every project.
- **Requests per minute**: the key's [rate limit](https://docs.lemuai.com/tickets-api/conventions#rate-limits). The default is 600.
- **Allowed IP addresses**: single addresses or CIDR ranges the key may be used from. Empty means any address.
- **Expires**: never, or on a date you choose.
4. Copy the key. The full key is shown **only once**. Store it straight away in a secrets manager or an environment variable.
You need the `api_keys.manage` permission to see this page (organization owners and admins have it). You cannot give a key a scope you do not have yourself.
To stop a key working, revoke it on the same page. A revoked or expired key is rejected at once.
### Send the key
```bash
curl https://api.tickets.lemuai.com/v1/projects \
-H "Authorization: Bearer ltk_live_your_api_key"
```
The `X-API-Key: ltk_live_your_api_key` header also works.
### Who the key acts as
Each key acts as its own user, named **API:** followed by the key's name (for example `API: ERP sync`). Tickets the key creates show this user as the reporter, and comments it writes show it as the author.
A key does not see restricted tickets unless they are shared with that user, and it only sees the projects you chose when you created it.
## Scopes
Scopes are the same permissions team members have. A request that needs a scope the key does not have fails with `403` and the code `missing_capability`.
| Scope | Allows |
|---|---|
| `tickets.read` | See tickets in projects the key can access |
| `tickets.write` | Create and edit tickets, comment, transition |
| `tickets.delete` | Delete and merge tickets |
| `tickets.assign` | Assign tickets to others |
| `tickets.bulk` | Bulk update tickets |
| `comments.internal` | Read and write internal notes |
| `requesters.read` | See requesters and accounts |
| `requesters.write` | Create and edit requesters and accounts |
| `pii.read` | See unmasked phone numbers and emails |
| `projects.read` | See projects |
| `projects.admin` | Create projects, edit workflows, types and fields |
| `config.admin` | SLAs, escalations, automations, assignment, calendars, macros |
| `teams.admin` | Manage teams, skills and shifts |
| `integrations.admin` | Connect Slack, email, Lemu, Jira and other integrations |
| `api_keys.manage` | Create and revoke API keys and webhooks |
| `reports.read` | See reports and dashboards |
| `audit.read` | See and export the audit log |
| `security.admin` | Roles, SSO, IP allowlist, retention, sandboxes |
| `data.export` | Export and import data |
| `copilot.use` | Use the Copilot |
| `approvals.decide` | Approve or reject approval requests |
| `assets.read` | See assets |
| `assets.write` | Create and edit assets |
| `field_service.dispatch` | Schedule and dispatch field visits |
| `kb.write` | Write knowledge base articles |
The presets give a key these scopes:
| Preset | Scopes |
|---|---|
| **Read only** | `tickets.read`, `requesters.read`, `projects.read`, `reports.read` |
| **Agent** | `tickets.read`, `tickets.write`, `tickets.assign`, `tickets.bulk`, `comments.internal`, `requesters.read`, `requesters.write`, `pii.read`, `projects.read`, `reports.read`, `copilot.use`, `assets.read`, `assets.write`, `kb.write` |
| **Full access** | Every scope |
Without `pii.read`, emails and phone numbers in responses are partly hidden, for example `p•••@example.com` and `+91•••••••210`.
## OAuth apps
Register an OAuth app when someone other than your own server needs access, or when you want short-lived tokens instead of a key.
### Register an app
1. Open **Settings → API keys and webhooks** and select the **OAuth apps** tab.
2. Click **Register app** and fill in **App name**, an optional **Logo URL** and **Description**, the **Redirect URIs**, and the scopes it can ask for.
3. Leave **Can keep a secret** on for apps with a server. Turn it off for mobile or single-page apps: they get no client secret and must use PKCE.
4. Copy the **client ID** (`ltc_...`) and, for apps that can keep a secret, the **client secret** (`ltcs_...`). The secret is shown only once.
Redirect URIs must match exactly and use `https` (`http` is allowed only for `localhost`).
### Authorization code with PKCE
Use this when your app acts for a LemuTickets user. The token can never do more than that user can do now, and only within the scopes they approved.
**1. Send the user to the consent screen.** Create a random `code_verifier` (43 to 128 characters) and its SHA-256 `code_challenge` (base64url, no padding), then open:
```
https://tickets.lemuai.com/oauth/authorize
?response_type=code
&client_id=ltc_your_client_id
&redirect_uri=https://erp.example.com/oauth/callback
&scope=tickets.read tickets.write
&state=af0ifjsldkj
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
&code_challenge_method=S256
```
The URL is split over lines here to make it easier to read; send it as one line with the values URL-encoded. PKCE with `S256` is required for every app. `scope` is a space-separated list; leave it out to ask for all of the app's scopes. After the user approves, they return to your `redirect_uri` with `code` and your `state`. The code expires after 5 minutes and works once.
**2. Exchange the code for tokens:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/oauth/token \
-u "ltc_your_client_id:ltcs_your_client_secret" \
-d grant_type=authorization_code \
-d code=ltac_code_from_the_redirect \
-d redirect_uri=https://erp.example.com/oauth/callback \
-d code_verifier=your_code_verifier
```
Apps without a secret send `client_id` in the body instead of `-u`, and no secret.
```json
{
"access_token": "lto_9kq2...",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "tickets.read tickets.write",
"refresh_token": "ltr_X4b7..."
}
```
**3. Call the API** with `Authorization: Bearer lto_...`. Access tokens last 1 hour.
**4. Refresh** before the access token expires. Refresh tokens last 30 days and change every time you use one: store the new one each time. Using an old refresh token again ends the whole grant, and the user has to approve the app again.
```bash
curl -X POST https://api.tickets.lemuai.com/v1/oauth/token \
-u "ltc_your_client_id:ltcs_your_client_secret" \
-d grant_type=refresh_token \
-d refresh_token=ltr_X4b7...
```
You can send a smaller `scope` when refreshing, but not a wider one.
### Client credentials
Use this for a server integration that acts for your organization, not for a person. It needs an app that can keep a secret.
```bash
curl -X POST https://api.tickets.lemuai.com/v1/oauth/token \
-u "ltc_your_client_id:ltcs_your_client_secret" \
-d grant_type=client_credentials \
-d "scope=tickets.read tickets.write"
```
The response has an `access_token` that lasts 1 hour and no refresh token: ask for a new one when it expires. Leave out `scope` to get all of the app's scopes.
A client credentials token is not tied to a user, so endpoints that record a person need one in the request. For example, [Log work](https://docs.lemuai.com/tickets-api/tickets/log-work) needs `user_id`.
### Token endpoint details
| | |
|---|---|
| Token URL | `POST https://api.tickets.lemuai.com/v1/oauth/token` |
| Revoke URL | `POST https://api.tickets.lemuai.com/v1/oauth/revoke` with `token=...` |
| Client authentication | HTTP Basic (`client_secret_basic`), or `client_id` and `client_secret` in the body (`client_secret_post`) |
| Body format | `application/x-www-form-urlencoded` or JSON |
| Server metadata | `https://api.tickets.lemuai.com/.well-known/oauth-authorization-server` |
Token endpoint errors use the OAuth format, not the API's usual error shape:
```json
{
"error": "invalid_grant",
"error_description": "The code expired"
}
```
| `error` | Meaning |
|---|---|
| `invalid_client` | Unknown client, wrong secret, or a secret sent for an app that has none (`401`) |
| `invalid_grant` | The code or refresh token is unknown, used, expired or revoked, or the PKCE check or `redirect_uri` does not match |
| `invalid_scope` | The app may not ask for these scopes |
| `unauthorized_client` | Client credentials asked for by an app without a secret |
| `unsupported_grant_type` | `grant_type` is not `authorization_code`, `refresh_token` or `client_credentials` |
Removing an app in **Settings → API keys and webhooks** revokes all of its tokens.
## Authentication errors
| Status | Code | Meaning |
|---|---|---|
| `401` | `unauthenticated` | No key or token was sent |
| `401` | `invalid_api_key` | The key is wrong, revoked or expired |
| `401` | `invalid_token` | The OAuth access token is wrong, revoked or expired, or the app was removed |
| `403` | `ip_not_allowed` | The request came from an IP address the key, or your organization, does not allow |
| `403` | `missing_capability` | The key or token does not have the scope this endpoint needs |
```json
{
"error": {
"type": "unauthorized",
"code": "invalid_api_key",
"message": "Invalid API key",
"request_id": "4f1d9c2b7a6e4e0f8c3b1a2d5e6f7a8b"
}
}
```
---
# Conventions
> Pagination, idempotency keys, ticket versions with If-Match, and rate limits in the LemuTickets API
URL: https://docs.lemuai.com/tickets-api/conventions
These rules work the same way on every endpoint that uses them.
## Pagination
List endpoints that can return many items use cursors. Send `limit` to choose the page size, and pass the `next_cursor` from one response as `cursor` in the next request. Keep every other parameter the same.
```bash
curl -G https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode "q=project = SUP ORDER BY created ASC" \
--data-urlencode "limit=100"
```
```json
{
"data": [ ... ],
"next_cursor": "eyJvIjogMTAwfQ",
"total": null
}
```
| Field | Description |
|---|---|
| `data` | The items on this page. |
| `next_cursor` | Pass it as `cursor` to get the next page. `null` on the last page. |
| `total` | Only on [List and search tickets](https://docs.lemuai.com/tickets-api/tickets/list): the number of matching tickets when you send `with_total=true`, otherwise `null`. |
Treat the cursor as an opaque string. It is a position in the result list, so if tickets change while you page through them, a ticket can show up twice or move to a page you already read. For a full sync, sort by a field that does not change (`ORDER BY created ASC`) and de-duplicate by `id`.
Shorter lists (comments on a ticket, transitions, projects, webhooks) return everything at once as `{"data": [...]}`, without a cursor.
## Idempotency keys
Networks fail. If you send a request and get no answer, you cannot tell whether it worked. An idempotency key lets you send it again safely.
Add an `Idempotency-Key` header with a value that is unique to the action, for example your own record id:
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: erp-complaint-58213" \
-d '{ "project": "SUP", "title": "Refund not received for order 58213" }'
```
- The first request runs normally and its response is saved.
- A later request with the same key and the same body gets the saved response back, with the header `Idempotent-Replayed: true`. Nothing is created twice.
- The same key with a different body fails with `409` and the code `idempotency_mismatch`.
Keys are kept per organization and per endpoint path for 24 hours. Keys can be up to 200 characters; a longer key fails with `422` and the code `idempotency_key_too_long`.
The `Idempotency-Key` header is honored by [Create a ticket](https://docs.lemuai.com/tickets-api/tickets/create) and [Add a comment](https://docs.lemuai.com/tickets-api/tickets/add-comment). Other endpoints ignore it.
Tickets have two more ways to avoid duplicates, which work without the header:
- **`source_ref`**: if a ticket with the same `source` and `source_ref` already exists, creating it again returns the existing ticket with status `200` instead of `201`.
- **`external_id`**: must be unique. Creating a second ticket with the same `external_id` fails with `409` and the code `duplicate_external_id`.
## Versions and If-Match
Every ticket has a `version` number. It goes up every time the ticket changes, including when someone comments, logs work, transitions it, or an automation updates it. The current version is in the ticket's `version` field and in the `ETag` header of [Get a ticket](https://docs.lemuai.com/tickets-api/tickets/get), [Create a ticket](https://docs.lemuai.com/tickets-api/tickets/create) and [Update a ticket](https://docs.lemuai.com/tickets-api/tickets/update).
To make sure you do not overwrite someone else's change, send the version you last read in an `If-Match` header on [Update a ticket](https://docs.lemuai.com/tickets-api/tickets/update) and [Transition a ticket](https://docs.lemuai.com/tickets-api/tickets/transition):
```bash
curl -X PATCH https://api.tickets.lemuai.com/v1/tickets/SUP-1042 \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "If-Match: 7" \
-d '{ "priority": "p1" }'
```
If the ticket changed since then, nothing is saved and you get `412`:
```json
{
"error": {
"type": "precondition_failed",
"code": "version_mismatch",
"message": "The ticket changed since you loaded it",
"request_id": "4f1d9c2b7a6e4e0f8c3b1a2d5e6f7a8b",
"data": { "current_version": 8 }
}
}
```
Get the ticket again, decide whether your change still makes sense, and retry with the new version. `If-Match` accepts the plain number (`7`) or the quoted forms (`"7"`, `W/"7"`). Without `If-Match`, the change is applied to whatever is current.
## Rate limits
Each API key has its own limit per minute, set when the key is created (600 by default). OAuth tokens that act for a user share that user's limit of 1,200 requests per minute. The window slides, so a short burst does not lock you out for a full minute.
Responses carry the current state:
| Header | Description |
|---|---|
| `RateLimit-Limit` | Requests allowed per minute. |
| `RateLimit-Remaining` | Requests left in the current window. |
Over the limit, requests fail with `429`. The `Retry-After` header and the error's `data.retry_after` both say how many seconds to wait:
```json
{
"error": {
"type": "rate_limited",
"code": "rate_limited",
"message": "Too many requests. Try again in 12 seconds.",
"request_id": "9a0b1c2d3e4f40a1b2c3d4e5f6a7b8c9",
"data": { "retry_after": 12, "limit": 600, "window": 60 }
}
}
```
If you need a higher limit for a key, create a new key with a higher **Requests per minute** value.
## Request ids
Every response has an `X-Request-Id` header, and every error repeats it as `request_id`. You can send your own `X-Request-Id` and it is used instead, which makes it easy to match your logs with ours.
---
# Errors
> The error shape, HTTP status codes and common error codes returned by the LemuTickets API
URL: https://docs.lemuai.com/tickets-api/errors
## Error format
Every error from the LemuTickets API has the same shape:
```json
{
"error": {
"type": "validation_error",
"code": "invalid_fields",
"message": "Some fields are invalid",
"field_errors": {
"title": "Field required",
"requester.email": "Input should be a valid string"
},
"request_id": "4f1d9c2b7a6e4e0f8c3b1a2d5e6f7a8b"
}
}
```
| Field | Description |
|---|---|
| `type` | The kind of error. One `type` per HTTP status (see the table below). |
| `code` | A stable, specific reason, for example `version_mismatch` or `duplicate_external_id`. Use this in your code. |
| `message` | A plain-language description for people. It can change; do not match on it. |
| `field_errors` | Only when specific fields are wrong: an object from field name to problem. Nested fields use dots, for example `custom_fields.order_id`. |
| `data` | Only on some errors: extra details, such as `current_version` on a version conflict or `retry_after` on a rate limit. |
| `request_id` | The id of this request, also in the `X-Request-Id` header. Include it when you contact support. |
The [OAuth token endpoint](https://docs.lemuai.com/tickets-api/authentication#token-endpoint-details) is the one exception: it returns errors in the standard OAuth format.
## Status codes
| Status | `type` | Meaning |
|---|---|---|
| `401` | `unauthorized` | No credentials, or the key or token is wrong, revoked or expired |
| `403` | `forbidden` | The credentials are valid but not allowed to do this |
| `404` | `not_found` | The id or key does not exist, or you are not allowed to see it |
| `409` | `conflict` | The request clashes with something that already exists |
| `412` | `precondition_failed` | The ticket changed since you read it (`If-Match`) |
| `422` | `validation_error` | The body or a parameter is invalid |
| `429` | `rate_limited` | Too many requests; see [rate limits](https://docs.lemuai.com/tickets-api/conventions#rate-limits) |
| `500` | | Something went wrong on our side |
A ticket in a project you cannot access returns `404`, not `403`, so the API never confirms that it exists.
## Common error codes
| Status | `code` | When |
|---|---|---|
| `401` | `unauthenticated` | No API key or token was sent |
| `401` | `invalid_api_key` | The API key is wrong, revoked or expired |
| `401` | `invalid_token` | The OAuth access token is wrong, revoked or expired |
| `403` | `missing_capability` | The key or token lacks a scope. `data.missing` lists the scopes needed |
| `403` | `ip_not_allowed` | The request came from an IP address that is not allowed |
| `403` | `transition_forbidden` | The workflow only lets certain roles, or the assignee, make this transition |
| `403` | `transition_condition` | The ticket does not meet the transition's conditions |
| `404` | `ticket_not_found` | No ticket with this key or id that you can see |
| `404` | `project_not_found` | No project with this key or id |
| `404` | `attachment_not_found` | No attachment with this id that you can see |
| `404` | `webhook_not_found` | No webhook with this id |
| `409` | `duplicate_external_id` | A ticket with this `external_id` already exists. `data` has its `ticket_id` and `key` |
| `409` | `idempotency_mismatch` | An `Idempotency-Key` was reused with a different body |
| `412` | `version_mismatch` | The ticket's version is not the one in `If-Match`. `data.current_version` has the current one |
| `422` | `invalid_fields` | The body or a query parameter failed validation. See `field_errors` |
| `422` | `missing_title` | The ticket title is empty |
| `422` | `project_archived` | The project is archived and takes no new tickets |
| `422` | `invalid_type` | The ticket type does not exist in this project |
| `422` | `invalid_status` | The status does not exist in this ticket's workflow |
| `422` | `invalid_priority` | Priority is not `p1`, `p2`, `p3` or `p4` |
| `422` | `invalid_source` | `source` is not one of the allowed values |
| `422` | `invalid_assignee` | The assignee is not an active member of your organization |
| `422` | `invalid_team` | The team does not exist |
| `422` | `invalid_requester` | The requester does not exist |
| `422` | `invalid_custom_fields` | One or more custom field values are wrong. See `field_errors` |
| `422` | `invalid_if_match` | `If-Match` is not a version number |
| `422` | `invalid_transition` | The ticket cannot move to that status from its current status |
| `422` | `transition_validation` | The transition needs fields or a comment you did not send. See `field_errors` |
| `422` | `missing_target` | A transition request had neither `to_status` nor `transition_id` |
| `422` | `empty_comment` | The comment body is empty |
| `422` | `invalid_link` | A ticket cannot link to itself |
| `422` | `invalid_minutes` | Logged minutes are not between 1 and 1440 |
| `422` | `missing_user` | The caller is not a user (for example a client credentials token), so `user_id` is required |
| `422` | `file_too_large` | The file is over 25 MB |
| `422` | `blocked_file_type` | The file is an executable or script type that is not allowed |
| `422` | `invalid_events` | A webhook event name or pattern matches no event |
| `422` | `invalid_url` | A webhook URL is not `http://` or `https://` |
| `422` | `private_address` | A webhook URL points at a private or local address |
| `422` | `tql_syntax` | The TQL query could not be parsed. `data.position` points at the problem |
| `422` | `tql_field` | The TQL query uses a field that does not exist |
| `429` | `rate_limited` | Too many requests. The `Retry-After` header and `data.retry_after` say how many seconds to wait |
New codes can be added over time. Handle unknown codes by falling back to the HTTP status.
## Handling errors
- **Retry `429`** after the number of seconds in `Retry-After`.
- **Retry `500` and other `5xx` responses** with exponential backoff. They are usually temporary. A `5xx` can come back without the JSON body above, so check the status before parsing. Use an [idempotency key](https://docs.lemuai.com/tickets-api/conventions#idempotency-keys) on creates so a retry never makes a duplicate.
- **On `412`**, get the ticket again, check that your change still applies, and retry with the new version.
- **On `409` `duplicate_external_id`**, the ticket already exists: use the `key` in `data` instead of creating another.
- **Do not retry other `4xx` responses** without changing the request. Read `code` and `field_errors` to see what to fix.
---
# Searching with TQL
> Find tickets with the Ticket Query Language: fields, operators, dates, sorting and examples
URL: https://docs.lemuai.com/tickets-api/tql
TQL (Ticket Query Language) is how you search tickets. It is the same language the LemuTickets app uses for filters, queues and saved views, so a filter you build in the app works in the API too.
Send a query as the `q` parameter of [List and search tickets](https://docs.lemuai.com/tickets-api/tickets/list):
```bash
curl -G https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode 'q=project = SUP AND status_category != done AND priority in (p1, p2) ORDER BY sla.next_due ASC'
```
## How a query is built
A query is one or more conditions joined with `AND` and `OR`, followed by an optional `ORDER BY`:
```
field operator value [AND|OR field operator value ...] [ORDER BY field [ASC|DESC], ...]
```
- `AND` binds tighter than `OR`. Use parentheses to group: `(priority = p1 OR sla.breached = true) AND project = SUP`.
- Two conditions side by side without a keyword are joined with `AND`.
- `NOT` in front of a condition or group negates it: `NOT labels in (spam)`.
- Keywords (`AND`, `OR`, `NOT`, `IN`, `IS`, `EMPTY`, `ORDER BY`, `ASC`, `DESC`) are not case sensitive. Field names are not case sensitive.
- Put values with spaces or special characters in double or single quotes: `status = "Waiting on customer"`.
- A quoted text or a word on its own is a full-text search of the title and description: `"refund not received"`. A ticket key on its own, like `SUP-1042`, finds that ticket.
## Operators
| Operator | Meaning | Example |
|---|---|---|
| `=` | Equals | `priority = p1` |
| `!=` | Does not equal (also matches tickets where the field is empty) | `status_category != done` |
| `>` `>=` `<` `<=` | Greater or less than (dates, numbers, priority) | `created >= -7d` |
| `~` | Contains (case insensitive) | `title ~ invoice` |
| `!~` | Does not contain | `title !~ test` |
| `IN (...)` | Any of the values | `priority in (p1, p2)` |
| `NOT IN (...)` | None of the values | `source not in (email, slack)` |
| `IS EMPTY` | Has no value | `assignee is empty` |
| `IS NOT EMPTY` | Has a value | `due is not empty` |
For `priority`, "greater" means more urgent: `priority >= p2` finds `p1` and `p2`.
## Fields
| Field | What it matches | Values |
|---|---|---|
| `project` | The project | Key (`SUP`), name or id |
| `key` | The ticket key | `SUP-1042` |
| `type` | The ticket type | Name (`Complaint`) or id |
| `status` | The exact status | Name (`"In progress"`) or id |
| `status_category` | The status group | `new`, `open`, `waiting`, `done` |
| `priority` | Priority | `p1`, `p2`, `p3`, `p4` |
| `severity` | Severity | Text |
| `source` | Where the ticket came from | `voice`, `whatsapp`, `web_chat`, `email`, `slack`, `teams`, `api`, `portal`, `web_form`, `manual`, `lemu_copilot`, `automation`, `journey` |
| `assignee` | The assigned person | `me()`, email, name or user id |
| `reporter` | Who created the ticket | `me()`, email, name or user id |
| `team` | The assigned team | Name or id |
| `requester` | The customer who raised it | Email, phone, name or requester id |
| `account` | The customer's account | Name or id |
| `account.tier` | The account's tier | For example `enterprise` |
| `requester.vip` | Requester is marked VIP | `true` or `false` |
| `labels` | Labels on the ticket | Label text. `labels in (refund, urgent)` matches tickets with any of them |
| `title` | The title | Text (use `~` to search inside it) |
| `description` | The description | Text |
| `text` | Full-text search of title and description | Text |
| `created` | When it was created | Date |
| `updated` | Last change | Date |
| `resolved` | When it was resolved | Date |
| `closed` | When it was closed | Date |
| `due` | The due date | Date |
| `first_response` | First public reply | Date |
| `status_changed` | Last status change | Date |
| `sla.next_due` | The next SLA deadline | Date |
| `sla.breached` | An SLA target was missed | `true` or `false` |
| `escalation_level` | How many times it was escalated | Number |
| `reopened` | How many times it was reopened | Number |
| `csat` | The customer's satisfaction score | Number |
| `time_spent` | Logged work, in minutes | Number |
| `restricted` | Visible only to some people | `true` or `false` |
| `parent` | The parent ticket | Ticket key |
| `watcher` | A user watching the ticket | User id |
| `external_id` | Your own id for the ticket | Text |
| `cf.` | A custom field | Depends on the field. Numbers can use `>` and `<` |
| `ai.` | A value the AI set during triage, such as `ai.category` | Text |
`status_category` is usually better than `status` in integrations: each project names its statuses differently, but every status belongs to one of the four categories.
## Dates
Date fields accept:
- **Relative times** from now: `-30m`, `-12h`, `-7d`, `-2w` for the past, `+1d` for the future. `created >= -7d` is "created in the last 7 days".
- **ISO dates and times**: `2026-11-01` or `2026-11-01T09:00:00+05:30`. Times without a zone are read as UTC.
- **Functions**: `now()`, `startOfDay()`, `endOfDay()`, `startOfWeek()` (Monday), `startOfMonth()`. These use UTC.
## Functions
| Function | Value |
|---|---|
| `me()` or `currentUser()` | The calling user. For an API key, the key's own user |
| `now()` | The current time |
| `startOfDay()`, `endOfDay()` | Start or end of today (UTC) |
| `startOfWeek()` | Monday 00:00 of this week (UTC) |
| `startOfMonth()` | The first of this month, 00:00 (UTC) |
## Sorting
Add `ORDER BY` at the end with one or more fields, each `ASC` (default) or `DESC`. Empty values sort last. Without `ORDER BY`, the most recently updated tickets come first.
You can sort by `created`, `updated`, `resolved`, `due`, `sla.next_due`, `key` (or `number`), `title`, `priority`, `status` (or `status_category`), `escalation_level`, `csat` and `status_changed`.
## Examples
| You want | Query |
|---|---|
| Open tickets in one project, most urgent first | `project = SUP AND status_category != done ORDER BY priority ASC, created ASC` |
| Breached or about to breach today | `sla.breached = true OR sla.next_due <= endOfDay()` |
| Unassigned high-priority tickets | `assignee is empty AND priority >= p2 AND status_category in (new, open)` |
| One customer's tickets this month | `requester = "priya@example.com" AND created >= startOfMonth()` |
| Enterprise accounts waiting on you | `account.tier = enterprise AND status_category = open` |
| Complaints from WhatsApp last week | `type = Complaint AND source = whatsapp AND created >= -1w` |
| A custom field value | `cf.order_id = "58213"` |
| Ticket synced from your ERP | `external_id = "ERP-CMP-58213"` |
| Free text | `"refund not received" AND project = SUP` |
## Checking a query
Send a query to `POST /v1/tql/validate` to check it before you save it in your system:
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tql/validate \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{ "q": "project = SUP AND priorty = p1" }'
```
```json
{
"valid": false,
"message": "Unknown field priorty",
"data": { "field": "priorty" },
"fields": ["project", "key", "type", "status", "..."]
}
```
A valid query returns `"valid": true` and the same `fields` list. When a query in [List and search tickets](https://docs.lemuai.com/tickets-api/tickets/list) is invalid, the request fails with `422` and a `tql_*` error code.
---
# Webhooks
> Get signed LemuTickets events at your endpoint: subscribing, the event list, payloads, verifying signatures and retries
URL: https://docs.lemuai.com/tickets-api/webhooks
Webhooks tell your system when something happens in LemuTickets, such as a new ticket, a status change or a customer reply, so you don't have to poll. LemuTickets sends an HTTPS `POST` with a JSON body to your URL for every event you subscribe to.
## Subscribe
Either in the app:
1. Open **Settings → API keys and webhooks** and select the **Webhooks** tab.
2. Click **Add webhook**.
3. Enter the **Endpoint URL**, an optional **Description**, the **Events** to send (use `area.*` for every event of that kind, for example `ticket.*`), and optionally the **Projects** to send events for. Empty means all projects.
4. Copy the signing secret. It is shown only once.
Or with the API: [Create a webhook](https://docs.lemuai.com/tickets-api/webhook-subscriptions/create).
The URL must be public. Private, local and internal addresses are refused.
On the same tab you can see each webhook's **Deliveries** with the response your endpoint gave, **Send again** a delivery, **Send test event**, and **Rotate secret**. The old secret stops working as soon as you rotate it.
## Events
| Event | When |
|---|---|
| `ticket.created` | A ticket was created |
| `ticket.updated` | Fields on a ticket changed |
| `ticket.transitioned` | A ticket moved to another status |
| `ticket.assigned` | The assignee or team changed |
| `ticket.resolved` | A ticket reached a resolved status |
| `ticket.reopened` | A resolved or closed ticket was reopened |
| `ticket.closed` | A ticket was closed |
| `ticket.deleted` | A ticket was deleted |
| `ticket.merged` | A ticket was merged into another |
| `ticket.escalated` | A ticket was escalated |
| `ticket.linked` | A link between tickets was added |
| `ticket.major_incident` | A ticket was flagged or unflagged as a major incident |
| `comment.created` | A reply or internal note was added |
| `comment.delivery_updated` | A reply's delivery status changed (for example, the email or WhatsApp message was delivered or failed) |
| `sla.warning` | An SLA target is close to breach |
| `sla.breached` | An SLA target was breached |
| `csat.submitted` | A requester rated a ticket |
| `approval.requested` | An approval was requested |
| `approval.decided` | An approval was approved or rejected |
| `worklog.created` | Time was logged on a ticket |
| `requester.created` | A requester was created |
| `requester.updated` | A requester was updated |
| `account.updated` | An account was created or updated |
| `assignment.unassigned` | A ticket stayed unassigned longer than the project allows |
| `asset.created` | An asset was created |
| `asset.updated` | An asset changed |
| `problem.created` | A problem record was created |
| `problem.updated` | A problem record changed |
| `change.created` | A change request was created |
| `change.updated` | A change request changed status or was voted on |
| `visit.updated` | A field visit was scheduled or changed |
| `visit.reminder` | A field visit is due tomorrow |
| `ai.triaged` | The AI classified a new ticket |
| `autopilot.action_proposed` | Autopilot proposed an action (inside its review window) |
| `autopilot.action_done` | Autopilot carried out an action |
| `lemu.issue_suggested` | Lemu AI found an issue in a conversation and it is waiting for review |
| `webhook.disabled` | A webhook subscription was turned off after repeated failures |
`GET /v1/events/catalog` returns the same list as `{"data": [{"type", "description"}]}`.
Patterns use `*` as a wildcard: `ticket.*` matches every ticket event, `*` matches everything. Each pattern must match at least one event.
When a webhook is limited to some projects, it only gets events that belong to a ticket in those projects. Events that are not about a ticket (requesters, accounts, `webhook.disabled`) are only sent to webhooks without a project filter.
## Payload
Every delivery has the same envelope:
```json
{
"id": "evt_48213",
"type": "ticket.transitioned",
"created_at": "2026-11-25T09:30:02.114210+00:00",
"org_id": "5e7a9c1b-3d2f-4a6e-8b0c-2d4f6a8c0e1b",
"data": {
"actor": {
"type": "user",
"id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"name": "Arjun Mehta"
},
"ticket": {
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"title": "Refund not received for order 58213",
"status": { "id": "6e1f2a3b-8c4d-4f5e-a6b7-c8d9e0f1a2b3", "name": "In progress", "category": "open", "color": "blue" },
"status_category": "open",
"priority": "p2",
"external_id": "ERP-CMP-58213",
"version": 4
},
"changes": {},
"details": {
"from": "Open",
"to": "In progress",
"from_category": "open",
"to_category": "open",
"transition": "Start work"
}
}
}
```
| Field | Description |
|---|---|
| `id` | The event id. It stays the same on every retry and redelivery, so use it to ignore events you have already handled. |
| `type` | The event name from the list above. |
| `created_at` | When the event was queued. |
| `org_id` | Your organization's id. |
| `data.actor` | Who caused it: `type` is `user`, `api_key`, `integration`, `requester`, `automation`, `ai` or `system`, with `id` and `name`. |
| `data.ticket` | For ticket and comment events: the whole ticket as it is when the event is sent. See [the ticket object](https://docs.lemuai.com/tickets-api/tickets/overview). Shortened above. |
| `data.changes` | For `ticket.updated`: each changed field as `[old, new]`, for example `{"priority": ["p3", "p1"]}`. Empty for other events. |
| `data.comment` | For `comment.*` events: the comment, in the same shape as [List comments](https://docs.lemuai.com/tickets-api/tickets/list-comments). |
| `data.details` | Event-specific details, for example the `from` and `to` status of a transition, or the `minutes` of a worklog. |
Events that are not about a ticket put their fields directly in `data`, for example `{"actor": {"type": "system"}, "requester_id": "8b4d6f2a-..."}` for `requester.created`. Fetch the full object with the API if you need it.
**Note:** `comment.created` is sent for internal notes too. Check `data.comment.visibility` (`public` or `internal`) before showing a comment to a customer.
## Headers
| Header | Value |
|---|---|
| `Content-Type` | `application/json` |
| `User-Agent` | `LemuTickets-Webhooks/1.0` |
| `X-LemuTickets-Event` | The event type, for example `ticket.created` |
| `X-LemuTickets-Delivery` | The delivery id. A manual **Send again** gets a new one |
| `X-LemuTickets-Signature` | `t=,v1=` (see below) |
## Verify the signature
Check every delivery before you trust it. The signature is an HMAC-SHA256, in hex, of the timestamp, a dot, and the raw request body, using your webhook's signing secret (`whsec_...`) as the key:
```
v1 = hex(HMAC_SHA256(secret, "."))
```
1. Read `t` and `v1` from the `X-LemuTickets-Signature` header.
2. Compute the HMAC over the **raw** body bytes as received. Parsing and re-encoding the JSON changes the bytes and breaks the check.
3. Compare with `v1` in constant time.
4. Reject the delivery if `t` is more than 5 minutes from your clock, to stop replays.
**Node.js**
```js
import crypto from "node:crypto";
import express from "express";
const app = express();
const SECRET = process.env.LEMU_TICKETS_WEBHOOK_SECRET; // whsec_...
app.post("/lemutickets/webhook", express.raw({ type: "application/json" }), (req, res) => {
const header = req.get("X-LemuTickets-Signature") || "";
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
const t = Number(parts.t);
const expected = crypto
.createHmac("sha256", SECRET)
.update(`${parts.t}.`)
.update(req.body)
.digest("hex");
const ok =
parts.v1 &&
parts.v1.length === expected.length &&
crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected)) &&
Math.abs(Date.now() / 1000 - t) <= 300;
if (!ok) return res.status(400).send("bad signature");
const event = JSON.parse(req.body.toString("utf8"));
// Handle the event, then answer quickly with a 2xx
res.sendStatus(204);
});
```
**Python**
```python
import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["LEMU_TICKETS_WEBHOOK_SECRET"] # whsec_...
@app.post("/lemutickets/webhook")
def lemutickets_webhook():
header = request.headers.get("X-LemuTickets-Signature", "")
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
t, sig = parts.get("t", ""), parts.get("v1", "")
body = request.get_data() # raw bytes
expected = hmac.new(SECRET.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
if not t.isdigit() or not hmac.compare_digest(sig, expected):
abort(400)
if abs(time.time() - int(t)) > 300:
abort(400)
event = request.get_json()
# Handle the event, then answer quickly with a 2xx
return "", 204
```
## Responding and retries
- Answer with any `2xx` status within 10 seconds. Do slow work after you answer, for example in a queue.
- Redirects are not followed, and any other status, a timeout or a connection error counts as a failure.
- Failed deliveries are retried with growing gaps (30 seconds, 1 minute, 2 minutes, 4 minutes and so on, up to 1 hour between tries) for 24 hours. After that the delivery is marked failed. You can still send it again from **Deliveries**.
- Deliveries go out within about 10 seconds of the event, several at a time, so they can arrive out of order. Use `created_at` and the ticket's `version` to tell which is newer.
- After 50 failed attempts in a row, the webhook is turned off, its pending deliveries are marked failed, and a `webhook.disabled` event is sent to any other webhook subscribed to it. Fix your endpoint, then turn **Send events** back on in the webhook's settings. That resets the failure count.
## Test your endpoint
**Send test event** on the webhook (or `POST /v1/webhooks/{webhook_id}/ping`) sends a signed `webhook.ping` event straight away:
```json
{
"id": "ping_Xk2pQ9aB",
"type": "webhook.ping",
"created_at": "2026-11-25T09:31:10.004512+00:00",
"org_id": "5e7a9c1b-3d2f-4a6e-8b0c-2d4f6a8c0e1b",
"data": {
"webhook_id": "f2a4c6e8-0b1d-4f3a-8c5e-a7c9e1b3d5f7",
"message": "Webhook is reachable"
}
}
```
---
# Embedding in Your ERP
> Show a customer's tickets, a request form or one ticket inside your own app with embed tokens and the element
URL: https://docs.lemuai.com/tickets-api/embedding
The `` element puts LemuTickets screens inside your ERP, customer portal or website, without you building them. It shows one customer (a requester) their own tickets, lets them raise a new one, and lets them reply. Your agents see and answer everything in LemuTickets as usual.
It works in two steps:
1. **Your server** asks the API for a short-lived **embed token** for the signed-in customer.
2. **Your page** loads the script and adds a `` element with that token.
**Warning:** Never put an API key in a web page. An embed token is safe to put in the page: it only works for one requester, only on the embed screens, only from the sites you list, and only for a short time.
## 1. Get an embed token on your server
**Endpoint:** `POST /v1/embed/tokens`
Call this with an [API key](https://docs.lemuai.com/tickets-api/authentication) or OAuth token that has the `tickets.write` scope.
| Field | Type | Required | Description |
|---|---|---|---|
| `requester_id` | string (UUID) | One of the three | The LemuTickets requester id. |
| `requester_external_id` | string | One of the three | Your own id for the customer, as set with [Upsert a requester by external ID](https://docs.lemuai.com/tickets-api/requesters/upsert-by-external-id). |
| `requester` | object | One of the three | `email`, `phone` and `name`. Finds the requester by email or phone, or creates one. Needs an `email` or a `phone`. |
| `scope` | string | No | What the token allows. `list` (default), `create` or `ticket`. See below. |
| `ticket_key` | string | For `ticket` | The ticket to show, for example `SUP-1042`. It must belong to this requester. |
| `project` | string | No | Project key or id for tickets the customer creates. Without it, new tickets go to your first open service desk project. |
| `ttl_minutes` | integer | No | How long the token lasts, `1` to `1440` minutes. Default `60`. |
| `allowed_origins` | array of strings | No | The sites allowed to use the token, as origins like `https://erp.example.com` (no path). Strongly recommended. Empty means any site. |
| Scope | The customer can |
|---|---|
| `list` | See all their tickets, open any of them, reply, and raise new tickets |
| `create` | Raise new tickets only |
| `ticket` | Open and reply on the one ticket in `ticket_key` |
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/embed/tokens \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"requester_external_id": "CUST-20931",
"scope": "list",
"project": "SUP",
"ttl_minutes": 60,
"allowed_origins": ["https://erp.example.com"]
}'
```
**`201`**
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_at": "2026-11-25T10:12:40.512000+00:00",
"scope": "list",
"requester_id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"ticket_key": null,
"allowed_origins": ["https://erp.example.com"],
"script_url": "https://api.tickets.lemuai.com/v1/public/embed.js",
"snippet": "\n"
}
```
`snippet` is ready-made HTML for this token.
| Status | `code` | When |
|---|---|---|
| `422` | `missing_requester` | None of `requester_id`, `requester_external_id` or `requester` (with an email or phone) was sent |
| `422` | `invalid_requester` | No requester with that id or external id |
| `422` | `requester_unavailable` | The requester's self-service access is turned off, or their data was anonymised |
| `422` | `missing_ticket_key` | `scope` is `ticket` but there is no `ticket_key` |
| `422` | `ticket_not_requesters` | The ticket belongs to another requester |
| `422` | `invalid_origin` | An entry in `allowed_origins` is not an origin like `https://erp.example.com` |
## 2. Add the element to your page
Load the script once per page, then add an element for each screen:
```html
```
| Attribute | Description |
|---|---|
| `token` | The embed token from step 1. Required. |
| `view` | `list` (default), `create` or `ticket`. It should match the token's scope. |
| `ticket` | The ticket key, for `view="ticket"`. |
| `status` | Optional, for `view="list"`. `open` shows every ticket that is not done. Otherwise a comma-separated list of status categories, for example `waiting` or `new,open`. |
The customer only ever sees their own tickets and public replies. Internal notes stay hidden. Tickets they raise have the source `portal`.
## Refreshing tokens
Tokens expire (after 60 minutes by default). Ask your server for a new token each time the page loads. If the page stays open a long time, fetch a new token before `expires_at` and set it on the element:
```js
document.querySelector("lemu-tickets").setAttribute("token", newToken);
```
Changing an attribute redraws the element.
## Events
The element sends DOM events you can listen to, for example to refresh your own screen:
| Event | `event.detail` |
|---|---|
| `lemu:ticket-created` | The new ticket: `id`, `key`, `title`, `status`, `status_category`, `priority`, `type`, `created_at` and more |
| `lemu:reply-sent` | The reply: `id`, `ticket_key`, `body_text`, `created_at` |
| `lemu:error` | `{ code, message }`, for example `embed_token_expired` when the token ran out |
```js
document.addEventListener("lemu:error", (e) => {
if (e.detail.code === "embed_token_expired") refreshToken();
});
```
## Styling
The element draws inside its own shadow DOM, so your page's styles do not leak into it. Set these CSS variables on the element to match your brand:
```css
lemu-tickets {
--accent: #0b6e4f;
--accent-hover: #095c42;
--ink: #1d1d1f;
--slate: #6b6b73;
--mist: #f4f4f5;
--line: #ececee;
--radius: 12px;
}
```
## When something goes wrong
| What you see | Why |
|---|---|
| "Missing token." | The `token` attribute is empty. |
| `network_error` ("Could not reach the support service.") | Often the page's origin is not in the token's `allowed_origins`, so the browser blocks the response. Origins must match exactly, including `https` and any port. |
| `embed_token_expired` | The token ran out. Get a new one from your server. |
| `embed_scope` | The token's scope does not allow this view, for example a `create` token used with `view="list"`. |
---
# The Ticket Object
> The fields of a LemuTickets ticket, as returned by every ticket endpoint and webhook
URL: https://docs.lemuai.com/tickets-api/tickets/overview
A **ticket** is one complaint, request, task, incident or question, with an owner, a status, a deadline and a full history. Every ticket belongs to a **project** (for example `SUP`) and gets a key from it (`SUP-1042`). Wherever an endpoint takes `{ref}`, you can pass the key or the ticket's `id`.
| Method | Endpoint | Purpose |
|---|---|---|
| `POST` | `/v1/tickets` | [Create a ticket](https://docs.lemuai.com/tickets-api/tickets/create) |
| `GET` | `/v1/tickets` | [List and search tickets](https://docs.lemuai.com/tickets-api/tickets/list) |
| `GET` | `/v1/tickets/{ref}` | [Get a ticket](https://docs.lemuai.com/tickets-api/tickets/get) |
| `PATCH` | `/v1/tickets/{ref}` | [Update a ticket](https://docs.lemuai.com/tickets-api/tickets/update) |
| `GET` | `/v1/tickets/{ref}/transitions` | [List available transitions](https://docs.lemuai.com/tickets-api/tickets/list-transitions) |
| `POST` | `/v1/tickets/{ref}/transitions` | [Transition a ticket](https://docs.lemuai.com/tickets-api/tickets/transition) to another status |
| `POST` | `/v1/tickets/{ref}/comments` | [Add a comment](https://docs.lemuai.com/tickets-api/tickets/add-comment): a reply or an internal note |
| `GET` | `/v1/tickets/{ref}/comments` | [List comments](https://docs.lemuai.com/tickets-api/tickets/list-comments) |
| `POST` | `/v1/tickets/{ref}/worklogs` | [Log work](https://docs.lemuai.com/tickets-api/tickets/log-work) |
| `POST` | `/v1/tickets/{ref}/links` | [Link tickets](https://docs.lemuai.com/tickets-api/tickets/link) |
## Example
```json
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"number": 1042,
"project": { "id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13", "key": "SUP", "name": "Customer Support" },
"type": { "id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47", "name": "Complaint", "icon": "message-square-warning", "color": "red" },
"title": "Refund not received for order 58213",
"description": "Customer paid on 12 November and the order was cancelled the same day.",
"status": { "id": "5c8a1d3e-7f2b-4e6a-9b0c-d4e1f2a3b5c6", "name": "Open", "category": "open", "color": "blue" },
"status_category": "open",
"priority": "p2",
"severity": null,
"source": "api",
"source_ref": null,
"requester": {
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"is_vip": false,
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e"
},
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"assignee": null,
"team": { "id": "1c3e5a7b-9d2f-4e6a-b8c0-a2e4f6b8d0c1", "name": "L1 Support" },
"reporter": {
"id": "d1f3b5a7-c9e2-4b4d-8f6a-0c2e4a6b8d0f",
"name": "API: ERP sync",
"email": "ltk_live_ab12cd34@bots.lemutickets",
"avatar_url": null
},
"parent_id": null,
"labels": ["refund"],
"due_at": null,
"restricted": false,
"sla": {
"policy_id": "7e9a1c3b-5d2f-4a6e-8b0c-1d3f5a7c9e2b",
"targets": {
"first_response": {
"minutes": 240.0,
"business_hours": true,
"status": "running",
"started_at": "2026-11-25T09:12:40.512000+00:00",
"due_at": "2026-11-25T13:12:40.512000+00:00",
"met_at": null,
"breached_at": null
}
},
"paused": false,
"next_due_at": "2026-11-25T13:12:40.512000+00:00",
"breached": false
},
"sla_next_due_at": "2026-11-25T13:12:40.512000+00:00",
"sla_breached": false,
"escalation_level": 0,
"first_response_at": null,
"resolved_at": null,
"closed_at": null,
"reopened_count": 0,
"csat_score": null,
"time_spent_minutes": 0,
"estimate_minutes": null,
"custom_fields": { "order_id": "58213" },
"ai": {},
"lemu": {},
"channel_thread": {},
"external_id": "ERP-CMP-58213",
"merged_into_id": null,
"version": 3,
"created_at": "2026-11-25T09:12:40.512000+00:00",
"updated_at": "2026-11-25T09:12:41.087000+00:00"
}
```
## Ticket fields
| Field | Type | Description |
|---|---|---|
| `id` | string (UUID) | The ticket's id. |
| `key` | string | The project key and number, for example `SUP-1042`. |
| `number` | integer | The number within the project. |
| `project` | object | `id`, `key` and `name` of the project. |
| `type` | object | The ticket type: `id`, `name`, `icon`, `color`. Types are set up per project, for example Complaint, Request, Question, Incident and Task. |
| `title` | string | Up to 500 characters. |
| `description` | string | The body of the ticket. |
| `status` | object | The current status: `id`, `name`, `category`, `color`. Status names differ per project. |
| `status_category` | string | The group the status belongs to: `new`, `open`, `waiting` or `done`. Use this, not the status name, to tell whether a ticket is finished. |
| `priority` | string | `p1` (most urgent) to `p4`. |
| `severity` | string or null | Optional severity, for incidents. |
| `source` | string | Where the ticket came from: `voice`, `whatsapp`, `web_chat`, `email`, `slack`, `teams`, `api`, `portal`, `web_form`, `manual`, `lemu_copilot`, `automation` or `journey`. |
| `source_ref` | string or null | An id in the source system, such as a message or call id. Prevents duplicates (see [Create a ticket](https://docs.lemuai.com/tickets-api/tickets/create)). |
| `requester` | object or null | The customer who raised it: `id`, `name`, `email`, `phone`, `is_vip`, `account_id`. Email and phone are partly hidden without the `pii.read` scope. |
| `account_id` | string or null | The requester's account (the customer company). |
| `assignee` | object or null | The assigned person: `id`, `name`, `email`, `avatar_url`. |
| `team` | object or null | The assigned team: `id`, `name`. |
| `reporter` | object or null | Who created the ticket, in the same shape as `assignee`. For API keys this is the key's own user. |
| `parent_id` | string or null | The parent ticket, for sub-tasks. |
| `labels` | array of strings | Labels, sorted. |
| `due_at` | string or null | The due date you set (separate from SLA deadlines). |
| `restricted` | boolean | `true` if only some people may see the ticket. |
| `sla` | object | The SLA state: `policy_id`, `targets`, `paused`, `next_due_at`, `breached`. See below. |
| `sla_next_due_at` | string or null | The next SLA deadline across all targets. |
| `sla_breached` | boolean | `true` once any SLA target was missed. |
| `escalation_level` | integer | How many escalation levels have fired. |
| `first_response_at` | string or null | When the first public reply was sent. |
| `resolved_at` | string or null | When it reached a resolved status. Cleared if it is reopened. |
| `closed_at` | string or null | When it reached a final status. Cleared if it is reopened. |
| `reopened_count` | integer | How many times it was reopened. |
| `csat_score` | integer or null | The customer's satisfaction rating, if they gave one. |
| `time_spent_minutes` | integer | Total logged work. |
| `estimate_minutes` | integer or null | The estimate, if set. |
| `custom_fields` | object | Your project's custom fields, by key. Fields you are not allowed to see are left out. |
| `ai` | object | What the AI worked out during triage, for example `summary`, `category` and `sentiment`. Empty when AI triage is off. |
| `lemu` | object | Links to the Lemu AI conversation the ticket came from (call, WhatsApp chat), when there is one. |
| `channel_thread` | object | The conversation replies go back to, for tickets that came from a channel. |
| `external_id` | string or null | Your own id for the ticket. Unique in your organization. |
| `merged_into_id` | string or null | Set when this ticket was merged into another. |
| `version` | integer | Goes up on every change. Use it with `If-Match` (see [Conventions](https://docs.lemuai.com/tickets-api/conventions#versions-and-if-match)). |
| `created_at`, `updated_at` | string | Times in UTC. |
[Get a ticket](https://docs.lemuai.com/tickets-api/tickets/get) also returns `transitions`, the statuses the ticket can move to next.
## SLA targets
`sla.targets` has one entry per target in the ticket's SLA policy: `first_response`, `next_response` and `resolution`. Each has:
| Field | Description |
|---|---|
| `minutes` | The target length. |
| `business_hours` | `true` if the clock only runs in business hours. |
| `status` | `running`, `paused`, `met` or `breached`. |
| `started_at` | When the clock started. |
| `due_at` | The deadline. Empty while the target is paused. |
| `met_at` | When the target was met, if it was. |
| `breached_at` | When the target was missed, if it was. |
Targets can carry more fields (such as `remaining_minutes` while paused). Ignore fields you do not use.
---
# Create a Ticket
> Create a ticket in a LemuTickets project, with its requester, priority, assignee and custom fields
URL: https://docs.lemuai.com/tickets-api/tickets/create
Creates a ticket in a project. The ticket starts in the workflow's first status unless you choose one, and gets the next number in the project (for example `SUP-1042`).
After it is created, the project's assignment rules, SLA policy and AI triage run as they do for tickets made in the app.
**Endpoint:** `POST /v1/tickets`
Needs the `tickets.write` scope in the project.
## Headers
| Name | Required | Description |
|---|---|---|
| `Idempotency-Key` | No, but recommended | A unique value for this ticket, for example your own record id. Sending the same request again returns the first response instead of a second ticket. See [idempotency keys](https://docs.lemuai.com/tickets-api/conventions#idempotency-keys). |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `project` | string | Yes | Project key (`SUP`) or id. |
| `title` | string | Yes | 1 to 500 characters. |
| `description` | string | No | The body of the ticket. |
| `type` | string | No | Ticket type name (`Complaint`) or id. Defaults to the project's default type. |
| `priority` | string | No | `p1`, `p2`, `p3` or `p4`. Default `p3`. |
| `severity` | string | No | Optional severity, for incidents. |
| `status` | string | No | Status name or id to start in. Defaults to the workflow's first status. |
| `source` | string | No | Where the ticket came from. Default `api`. One of `voice`, `whatsapp`, `web_chat`, `email`, `slack`, `teams`, `api`, `portal`, `web_form`, `manual`, `lemu_copilot`, `automation`, `journey`. |
| `source_ref` | string | No | The id of the item in the source system. If a ticket with the same `source` and `source_ref` exists, it is returned instead of creating a new one. |
| `external_id` | string | No | Your own id for the ticket. Must be unique: a second ticket with the same value fails with `409`. |
| `requester_id` | string (UUID) | No | An existing requester. |
| `requester` | object | No | Find or create the requester inline (see below). Used when `requester_id` is not sent. |
| `account_id` | string (UUID) | No | The customer account. Defaults to the requester's account. |
| `assignee_user_id` | string (UUID) | No | Assign to this person. They must be an active member of your organization. |
| `assignee_team_id` | string (UUID) | No | Assign to this team. Defaults to the project's default team when no person is set. |
| `labels` | array of strings | No | Labels to add. |
| `due_at` | string (date-time) | No | A due date, separate from SLA deadlines. |
| `custom_fields` | object | No | Values for the project's custom fields, by key. Required custom fields must be sent. |
| `parent_id` | string (UUID) | No | Make this a sub-task of another ticket. |
| `restricted` | boolean | No | Only the assignee, the reporter, admins and people it is shared with can see it. Default `false`. |
| `watchers` | array of UUIDs | No | Users to notify about changes. |
| `estimate_minutes` | integer | No | An estimate of the work. |
| `auto_assign` | boolean | No | Run the project's assignment rules. Default `true`. |
| `auto_triage` | boolean | No | Let the AI classify the ticket. Default `true`. |
### Inline requester
Send `requester` to link the ticket to a customer without looking them up first. LemuTickets finds an existing requester by `lemu_contact_id`, email, phone, WhatsApp id or `external_id`, in that order, and creates one if there is no match. Details on an existing requester are only filled in where they are empty, never overwritten.
| Field | Type | Description |
|---|---|---|
| `name` | string | Full name. |
| `email` | string | Email address. |
| `phone` | string | Phone number. Numbers without a country code are read as Indian (`+91`). |
| `whatsapp_id` | string | WhatsApp number. |
| `external_id` | string | Your own id for the customer. |
| `lemu_contact_id` | integer | The contact's id in Lemu AI, if you use both products. |
| `language` | string | Preferred language, for example `hi` or `en`. |
A new requester whose email domain matches an [account](https://docs.lemuai.com/tickets-api/accounts/list) is added to that account.
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: ERP-CMP-58213" \
-d '{
"project": "SUP",
"type": "Complaint",
"title": "Refund not received for order 58213",
"description": "Customer paid on 12 November and the order was cancelled the same day.",
"priority": "p2",
"external_id": "ERP-CMP-58213",
"labels": ["refund"],
"custom_fields": { "order_id": "58213" },
"requester": {
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"external_id": "CUST-20931"
}
}'
```
## Response
**`201`** with the new ticket. The `ETag` header holds its `version`.
```json
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"number": 1042,
"project": { "id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13", "key": "SUP", "name": "Customer Support" },
"type": { "id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47", "name": "Complaint", "icon": "message-square-warning", "color": "red" },
"title": "Refund not received for order 58213",
"description": "Customer paid on 12 November and the order was cancelled the same day.",
"status": { "id": "4d7b9e1f-3a5c-4e8b-a0d2-f4b6c8e0a1d3", "name": "New", "category": "new", "color": "sky" },
"status_category": "new",
"priority": "p2",
"severity": null,
"source": "api",
"source_ref": null,
"requester": {
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"is_vip": false,
"account_id": null
},
"account_id": null,
"assignee": null,
"team": { "id": "1c3e5a7b-9d2f-4e6a-b8c0-a2e4f6b8d0c1", "name": "L1 Support" },
"reporter": {
"id": "d1f3b5a7-c9e2-4b4d-8f6a-0c2e4a6b8d0f",
"name": "API: ERP sync",
"email": "ltk_live_ab12cd34@bots.lemutickets",
"avatar_url": null
},
"parent_id": null,
"labels": ["refund"],
"due_at": null,
"restricted": false,
"sla": {
"policy_id": "7e9a1c3b-5d2f-4a6e-8b0c-1d3f5a7c9e2b",
"targets": {
"first_response": {
"minutes": 240.0,
"business_hours": true,
"status": "running",
"started_at": "2026-11-25T09:12:40.512000+00:00",
"due_at": "2026-11-25T13:12:40.512000+00:00",
"met_at": null,
"breached_at": null
}
},
"paused": false,
"next_due_at": "2026-11-25T13:12:40.512000+00:00",
"breached": false
},
"sla_next_due_at": "2026-11-25T13:12:40.512000+00:00",
"sla_breached": false,
"escalation_level": 0,
"first_response_at": null,
"resolved_at": null,
"closed_at": null,
"reopened_count": 0,
"csat_score": null,
"time_spent_minutes": 0,
"estimate_minutes": null,
"custom_fields": { "order_id": "58213" },
"ai": {},
"lemu": {},
"channel_thread": {},
"external_id": "ERP-CMP-58213",
"merged_into_id": null,
"version": 1,
"created_at": "2026-11-25T09:12:40.512000+00:00",
"updated_at": "2026-11-25T09:12:40.512000+00:00"
}
```
See [the ticket object](https://docs.lemuai.com/tickets-api/tickets/overview) for every field. Assignment, SLA and triage can still change the ticket right after it is created, so `version` and the assignee may move on quickly.
**`200`** with the existing ticket, when a ticket with the same `source` and `source_ref` already exists.
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `project_not_found` | No project with that key or id, or the key cannot access it |
| `409` | `duplicate_external_id` | A ticket with this `external_id` exists. `data.key` is its key |
| `409` | `idempotency_mismatch` | The `Idempotency-Key` was used before with a different body |
| `422` | `project_archived` | The project is archived |
| `422` | `invalid_type`, `invalid_status` | The type or status does not exist in this project |
| `422` | `invalid_assignee`, `invalid_team`, `invalid_requester` | The assignee, team or requester does not exist |
| `422` | `invalid_source` | `source` is not one of the allowed values |
| `422` | `invalid_custom_fields` | A custom field value is wrong or a required one is missing. See `field_errors` |
| `422` | `invalid_fields` | A field has the wrong type or length. See `field_errors` |
---
# List and Search Tickets
> List LemuTickets tickets a page at a time, filtered with simple parameters or a TQL query
URL: https://docs.lemuai.com/tickets-api/tickets/list
Returns the tickets you can see, a page at a time. Filter with the simple parameters, with a [TQL](https://docs.lemuai.com/tickets-api/tql) query in `q`, or both. All filters are combined with `AND`.
**Endpoint:** `GET /v1/tickets`
Needs the `tickets.read` scope. Deleted tickets are never returned.
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `q` | string | No | A [TQL](https://docs.lemuai.com/tickets-api/tql) query, for example `project = SUP AND priority in (p1, p2)`. May end with `ORDER BY`. |
| `project` | string | No | Only tickets in this project (key or id). |
| `status_category` | string | No | Comma-separated status categories: `new`, `open`, `waiting`, `done`. |
| `assignee` | string | No | `me` (the caller), `none` (unassigned), or a user id or email. |
| `requester_id` | string (UUID) | No | Only this requester's tickets. |
| `view_id` | string (UUID) | No | Use the query and sort of a saved view from the app. |
| `limit` | integer | No | Tickets per page, `1` to `200`. Default `50`. |
| `cursor` | string | No | The `next_cursor` from the previous page. See [pagination](https://docs.lemuai.com/tickets-api/conventions#pagination). |
| `with_total` | boolean | No | Also count all matching tickets in `total`. Default `false`. Leave it off when you don't need it; it makes the request slower. |
Without `ORDER BY` in `q`, the most recently updated tickets come first.
**Example request:**
```bash
curl -G https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode "project=SUP" \
--data-urlencode "status_category=new,open,waiting" \
--data-urlencode "q=requester = \"priya@example.com\" ORDER BY created DESC" \
--data-urlencode "limit=25" \
--data-urlencode "with_total=true"
```
To sync every ticket that changed since your last run:
```bash
curl -G https://api.tickets.lemuai.com/v1/tickets \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode "q=updated >= \"2026-11-24T00:00:00+00:00\" ORDER BY updated ASC" \
--data-urlencode "limit=200"
```
## Response
**`200`**
```json
{
"data": [
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"number": 1042,
"project": { "id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13", "key": "SUP", "name": "Customer Support" },
"type": { "id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47", "name": "Complaint", "icon": "message-square-warning", "color": "red" },
"title": "Refund not received for order 58213",
"status": { "id": "5c8a1d3e-7f2b-4e6a-9b0c-d4e1f2a3b5c6", "name": "Open", "category": "open", "color": "blue" },
"status_category": "open",
"priority": "p2",
"requester": {
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"is_vip": false,
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e"
},
"assignee": {
"id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"name": "Arjun Mehta",
"email": "arjun@yourcompany.com",
"avatar_url": null
},
"team": { "id": "1c3e5a7b-9d2f-4e6a-b8c0-a2e4f6b8d0c1", "name": "L1 Support" },
"sla_next_due_at": "2026-11-25T13:12:40.512000+00:00",
"sla_breached": false,
"external_id": "ERP-CMP-58213",
"version": 4,
"created_at": "2026-11-25T09:12:40.512000+00:00",
"updated_at": "2026-11-25T09:30:02.114210+00:00"
}
],
"next_cursor": null,
"total": 1
}
```
| Field | Type | Description |
|---|---|---|
| `data` | array | The tickets on this page. Each one is a full [ticket object](https://docs.lemuai.com/tickets-api/tickets/overview); the example above is shortened. |
| `next_cursor` | string or null | Pass as `cursor` for the next page. `null` on the last page. |
| `total` | integer or null | All matching tickets, when `with_total=true`. Otherwise `null`. |
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `not_found` | `view_id` does not exist |
| `422` | `tql_syntax`, `tql_field`, `tql_value`, `tql_operator`, `tql_order` | The TQL query is invalid. `message` says what is wrong and `data.position` where |
| `422` | `invalid_fields` | `limit` is out of range or a parameter has the wrong type |
---
# Get a Ticket
> Get one LemuTickets ticket by key or id, with the transitions it can make next
URL: https://docs.lemuai.com/tickets-api/tickets/get
Returns one ticket, by its key or id, together with the statuses it can move to next.
**Endpoint:** `GET /v1/tickets/{ref}`
Needs the `tickets.read` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`, not case sensitive) or id. |
**Example request:**
```bash
curl https://api.tickets.lemuai.com/v1/tickets/SUP-1042 \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`200`** with the [ticket object](https://docs.lemuai.com/tickets-api/tickets/overview) and a `transitions` list. The `ETag` header holds the ticket's `version`, for use with [If-Match](https://docs.lemuai.com/tickets-api/conventions#versions-and-if-match).
```json
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"number": 1042,
"project": { "id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13", "key": "SUP", "name": "Customer Support" },
"type": { "id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47", "name": "Complaint", "icon": "message-square-warning", "color": "red" },
"title": "Refund not received for order 58213",
"description": "Customer paid on 12 November and the order was cancelled the same day.",
"status": { "id": "5c8a1d3e-7f2b-4e6a-9b0c-d4e1f2a3b5c6", "name": "Open", "category": "open", "color": "blue" },
"status_category": "open",
"priority": "p2",
"severity": null,
"source": "api",
"source_ref": null,
"requester": {
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"is_vip": false,
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e"
},
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"assignee": {
"id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"name": "Arjun Mehta",
"email": "arjun@yourcompany.com",
"avatar_url": null
},
"team": { "id": "1c3e5a7b-9d2f-4e6a-b8c0-a2e4f6b8d0c1", "name": "L1 Support" },
"reporter": {
"id": "d1f3b5a7-c9e2-4b4d-8f6a-0c2e4a6b8d0f",
"name": "API: ERP sync",
"email": "ltk_live_ab12cd34@bots.lemutickets",
"avatar_url": null
},
"parent_id": null,
"labels": ["refund"],
"due_at": null,
"restricted": false,
"sla": {
"policy_id": "7e9a1c3b-5d2f-4a6e-8b0c-1d3f5a7c9e2b",
"targets": {
"first_response": {
"minutes": 240.0,
"business_hours": true,
"status": "running",
"started_at": "2026-11-25T09:12:40.512000+00:00",
"due_at": "2026-11-25T13:12:40.512000+00:00",
"met_at": null,
"breached_at": null
}
},
"paused": false,
"next_due_at": "2026-11-25T13:12:40.512000+00:00",
"breached": false
},
"sla_next_due_at": "2026-11-25T13:12:40.512000+00:00",
"sla_breached": false,
"escalation_level": 0,
"first_response_at": null,
"resolved_at": null,
"closed_at": null,
"reopened_count": 0,
"csat_score": null,
"time_spent_minutes": 0,
"estimate_minutes": null,
"custom_fields": { "order_id": "58213" },
"ai": {},
"lemu": {},
"channel_thread": {},
"external_id": "ERP-CMP-58213",
"merged_into_id": null,
"version": 4,
"created_at": "2026-11-25T09:12:40.512000+00:00",
"updated_at": "2026-11-25T09:20:15.301000+00:00",
"transitions": [
{
"id": "e8a0c2d4-f6b1-4d3e-9a5c-7b9d1f3e5a7c",
"name": "Start work",
"to_status_id": "6e1f2a3b-8c4d-4f5e-a6b7-c8d9e0f1a2b3",
"to_status": "In progress",
"category": "open",
"validators": {},
"approval": {}
},
{
"id": "b1d3f5a7-9c2e-4b4d-8f6a-1c3e5a7b9d0f",
"name": "Resolve",
"to_status_id": "7a2b3c4d-9e5f-4a6b-b7c8-d9e0f1a2b3c4",
"to_status": "Resolved",
"category": "done",
"validators": { "require_comment": true },
"approval": {}
}
]
}
```
`transitions` has the same items as [List available transitions](https://docs.lemuai.com/tickets-api/tickets/list-transitions) (shortened above).
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
---
# Update a Ticket
> Change fields on a LemuTickets ticket, safely with If-Match
URL: https://docs.lemuai.com/tickets-api/tickets/update
Changes the fields you send and leaves the rest alone. To change the status, use [Transition a ticket](https://docs.lemuai.com/tickets-api/tickets/transition) instead.
**Endpoint:** `PATCH /v1/tickets/{ref}`
Needs the `tickets.write` scope in the ticket's project. Assigning a ticket to someone other than the caller also needs `tickets.assign`.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`) or id. |
## Headers
| Name | Required | Description |
|---|---|---|
| `If-Match` | No, but recommended | The `version` you last read. If the ticket changed since, nothing is saved and you get `412`. See [versions and If-Match](https://docs.lemuai.com/tickets-api/conventions#versions-and-if-match). |
## Request body
Send only the fields you want to change. Send `null` to clear a field.
| Field | Type | Description |
|---|---|---|
| `title` | string | The title. |
| `description` | string | The body of the ticket. |
| `priority` | string | `p1`, `p2`, `p3` or `p4`. |
| `severity` | string | Optional severity. |
| `type_id` | string (UUID) | Another ticket type in the same project. It must use the same workflow. |
| `assignee_user_id` | string (UUID) | The person to assign. `null` unassigns. |
| `assignee_team_id` | string (UUID) | The team to assign. |
| `requester_id` | string (UUID) | Change the requester. The account follows the new requester unless you also send `account_id`. |
| `account_id` | string (UUID) | The customer account. |
| `labels` | array of strings | **Replaces** all labels. |
| `due_at` | string (date-time) | The due date. |
| `custom_fields` | object | **Merged** into the existing values: keys you send are updated, others are kept. |
| `parent_id` | string (UUID) | Make it a sub-task of another ticket. |
| `estimate_minutes` | integer | Estimated work. |
| `story_points` | number | Story points, for task tracking projects. |
| `external_id` | string | Your own id for the ticket. |
| `restricted` | boolean | Only organization or project admins may change this. |
| `restricted_to` | object | Who else may see a restricted ticket: `{"user_ids": [...], "roles": [...]}`. Only organization or project admins may change this. |
Any other field is rejected with `422`.
**Example request:**
```bash
curl -X PATCH https://api.tickets.lemuai.com/v1/tickets/SUP-1042 \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "If-Match: 4" \
-d '{
"priority": "p1",
"assignee_user_id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"labels": ["refund", "escalated"],
"custom_fields": { "refund_reference": "RF-99120" }
}'
```
## Response
**`200`** with the updated [ticket object](https://docs.lemuai.com/tickets-api/tickets/overview). The `ETag` header holds the new `version`.
```json
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"title": "Refund not received for order 58213",
"status": { "id": "5c8a1d3e-7f2b-4e6a-9b0c-d4e1f2a3b5c6", "name": "Open", "category": "open", "color": "blue" },
"status_category": "open",
"priority": "p1",
"assignee": {
"id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"name": "Arjun Mehta",
"email": "arjun@yourcompany.com",
"avatar_url": null
},
"labels": ["escalated", "refund"],
"custom_fields": { "order_id": "58213", "refund_reference": "RF-99120" },
"version": 5,
"updated_at": "2026-11-25T09:41:07.220000+00:00"
}
```
The example is shortened; the response has every ticket field. A change fires the `ticket.updated` [webhook](https://docs.lemuai.com/tickets-api/webhooks) with the changed fields, and `ticket.assigned` when the assignee or team changed. The new assignee becomes a watcher.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | You assigned someone else without `tickets.assign`, or changed `restricted` without being an admin |
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
| `412` | `version_mismatch` | The ticket changed since the version in `If-Match`. `data.current_version` has the current one |
| `422` | `invalid_if_match` | `If-Match` is not a version number |
| `422` | `invalid_fields` | An unknown field was sent, or a value has the wrong type |
| `422` | `invalid_priority`, `invalid_assignee`, `invalid_team`, `invalid_type` | A value does not exist or is not allowed |
| `422` | `workflow_change` | The new type uses another workflow |
| `422` | `invalid_parent` | A ticket cannot be its own parent |
| `422` | `invalid_custom_fields` | A custom field value is wrong. See `field_errors` |
---
# List Available Transitions
> See which statuses a LemuTickets ticket can move to from its current status
URL: https://docs.lemuai.com/tickets-api/tickets/list-transitions
Returns the transitions a ticket can make from its current status, as set in the project's workflow. Use it to build "Start work", "Resolve" or "Close" buttons in your own system, and to find the `transition_id` or `to_status` for [Transition a ticket](https://docs.lemuai.com/tickets-api/tickets/transition).
**Endpoint:** `GET /v1/tickets/{ref}/transitions`
Needs the `tickets.read` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`) or id. |
**Example request:**
```bash
curl https://api.tickets.lemuai.com/v1/tickets/SUP-1042/transitions \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`200`**
```json
{
"data": [
{
"id": "e8a0c2d4-f6b1-4d3e-9a5c-7b9d1f3e5a7c",
"name": "Start work",
"to_status_id": "6e1f2a3b-8c4d-4f5e-a6b7-c8d9e0f1a2b3",
"to_status": "In progress",
"category": "open",
"validators": {},
"approval": {}
},
{
"id": "a3c5e7b9-1d2f-4a4c-8e6b-0d2f4a6c8e1b",
"name": "Ask customer",
"to_status_id": "8b3c4d5e-0f6a-4b7c-c8d9-e0f1a2b3c4d5",
"to_status": "Waiting on customer",
"category": "waiting",
"validators": { "require_comment": true },
"approval": {}
},
{
"id": "b1d3f5a7-9c2e-4b4d-8f6a-1c3e5a7b9d0f",
"name": "Resolve",
"to_status_id": "7a2b3c4d-9e5f-4a6b-b7c8-d9e0f1a2b3c4",
"to_status": "Resolved",
"category": "done",
"validators": { "required_fields": ["resolution_note"] },
"approval": {}
}
]
}
```
| Field | Type | Description |
|---|---|---|
| `id` | string or null | The transition's id, for `transition_id`. `null` when the workflow lets tickets move to any status. |
| `name` | string | The button label, for example `Resolve`. |
| `to_status_id` | string | The status the ticket moves to. |
| `to_status` | string | That status's name. |
| `category` | string | That status's category: `new`, `open`, `waiting` or `done`. |
| `validators` | object | What the transition needs: `required_fields` (field names that must have a value) and `require_comment`. Only on workflows with defined transitions. |
| `approval` | object | Set when the transition needs approval first. Empty otherwise. Only on workflows with defined transitions. |
A transition can still be refused when you try it, for example when it is limited to some roles or to the assignee.
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
---
# Transition a Ticket
> Move a LemuTickets ticket to another status in its workflow, with an optional comment
URL: https://docs.lemuai.com/tickets-api/tickets/transition
Moves a ticket to another status, following the project's workflow. You can add a comment and change fields in the same request.
**Endpoint:** `POST /v1/tickets/{ref}/transitions`
Needs the `tickets.write` scope in the ticket's project.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`) or id. |
## Headers
| Name | Required | Description |
|---|---|---|
| `If-Match` | No | The `version` you last read. If the ticket changed since, nothing happens and you get `412`. See [versions and If-Match](https://docs.lemuai.com/tickets-api/conventions#versions-and-if-match). |
## Request body
Send either `to_status` or `transition_id`.
| Field | Type | Required | Description |
|---|---|---|---|
| `to_status` | string | One of the two | The status to move to, by name (`Resolved`, not case sensitive) or id. |
| `transition_id` | string (UUID) | One of the two | A transition `id` from [List available transitions](https://docs.lemuai.com/tickets-api/tickets/list-transitions). |
| `comment` | string | No | A comment to add with the move. Some transitions require one. |
| `comment_visibility` | string | No | `internal` (default) for a note to your team, or `public` to reply to the requester. |
| `fields` | object | No | Ticket fields to change at the same time, with the same names as [Update a ticket](https://docs.lemuai.com/tickets-api/tickets/update), for example `{"priority": "p3"}`. |
If the transition has `required_fields`, they must already have a value or be set in `fields`. For required custom fields, set them with [Update a ticket](https://docs.lemuai.com/tickets-api/tickets/update) first.
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets/SUP-1042/transitions \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "If-Match: 5" \
-d '{
"to_status": "Resolved",
"comment": "Your refund of Rs 4,250 was processed today. It reaches your account in 3 to 5 working days.",
"comment_visibility": "public"
}'
```
## Response
**`200`** with the updated [ticket object](https://docs.lemuai.com/tickets-api/tickets/overview).
```json
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"title": "Refund not received for order 58213",
"status": { "id": "7a2b3c4d-9e5f-4a6b-b7c8-d9e0f1a2b3c4", "name": "Resolved", "category": "done", "color": "green" },
"status_category": "done",
"priority": "p1",
"first_response_at": "2026-11-25T10:02:18.640000+00:00",
"resolved_at": "2026-11-25T10:02:18.640000+00:00",
"closed_at": null,
"version": 8,
"updated_at": "2026-11-25T10:02:18.640000+00:00"
}
```
The example is shortened; the response has every ticket field.
Moving to a status in the `done` category sets `resolved_at` (or `closed_at` for a final status) and fires `ticket.resolved` or `ticket.closed`. Moving a done ticket back to another category reopens it: `reopened_count` goes up and `ticket.reopened` fires. Every move fires `ticket.transitioned`. See [Webhooks](https://docs.lemuai.com/tickets-api/webhooks).
### When the transition needs approval
If the transition needs approval, the ticket does not move yet. The response is the ticket in its current status, with a `notes` object:
```json
{
"key": "SUP-1042",
"status_category": "open",
"notes": {
"transition_blocked": true,
"approval_request_id": "c7e9b1d3-5f2a-4c6e-8b0d-3f5a7c9e1b2d",
"approval_required": {
"status": "pending",
"created": true,
"approver_user_ids": ["0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b"],
"approver_roles": []
}
}
}
```
Once approved, the transition is made with the comment and fields you sent. `notes` can also appear with other information, such as how the ticket was assigned. Always check `status_category` to see where the ticket ended up.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `transition_forbidden` | The transition is limited to certain roles, or to the assignee |
| `403` | `transition_condition` | The ticket does not meet the transition's conditions |
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
| `412` | `version_mismatch` | The ticket changed since the version in `If-Match` |
| `422` | `missing_target` | Neither `to_status` nor `transition_id` was sent |
| `422` | `invalid_status` | No status with that name or id in this ticket's workflow |
| `422` | `invalid_transition` | The ticket cannot move to that status from its current status. `data` has `from` and `to` |
| `422` | `transition_validation` | A required field or comment is missing. `field_errors` lists them |
Moving a ticket to the status it is already in does nothing and returns `200`.
---
# Add a Comment
> Reply to the requester on their channel or add an internal note to a LemuTickets ticket
URL: https://docs.lemuai.com/tickets-api/tickets/add-comment
Adds a comment to a ticket. A comment is either:
- a **public reply**, sent to the requester on the ticket's channel (email, WhatsApp, the portal), or
- an **internal note**, seen only by your team.
**Endpoint:** `POST /v1/tickets/{ref}/comments`
A public reply needs the `tickets.write` scope. An internal note needs `comments.internal`.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`) or id. |
## Headers
| Name | Required | Description |
|---|---|---|
| `Idempotency-Key` | No, but recommended | A unique value for this comment. Sending the same request again returns the first comment instead of posting twice. See [idempotency keys](https://docs.lemuai.com/tickets-api/conventions#idempotency-keys). |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `body` | string | Yes | The text. Plain text or simple HTML. |
| `visibility` | string | No | `internal` (default) or `public`. |
| `channel` | string | No | For public replies: `email`, `whatsapp`, `portal`, `slack` or `voice`. Defaults to the channel the ticket came in on. |
| `mentions` | array of UUIDs | No | Users to mention. They are notified and become watchers. |
| `attachment_ids` | array of UUIDs | No | Files from [Upload an attachment](https://docs.lemuai.com/tickets-api/attachments/upload) to attach to this comment. |
| `whatsapp_template` | object | No | An approved WhatsApp template (`name`, `language`, `variables`) to send instead of free text. WhatsApp only allows free text within 24 hours of the customer's last message. |
**Note:** Public replies on WhatsApp go out through Lemu AI, so your organization needs the Lemu AI connection set up in LemuTickets. A ticket that came from a phone call has no channel to reply on: the reply is saved on the ticket but not sent.
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets/SUP-1042/comments \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: erp-note-77812" \
-d '{
"body": "Finance confirmed the refund was approved. Reference RF-99120.",
"visibility": "internal",
"mentions": ["0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b"]
}'
```
## Response
**`201`**
```json
{
"id": "c5e7a9b1-d3f2-4c6e-8a0b-2e4c6a8b0d1f",
"ticket_id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"visibility": "internal",
"body": "Finance confirmed the refund was approved. Reference RF-99120.",
"body_text": "Finance confirmed the refund was approved. Reference RF-99120.",
"author_type": "user",
"author": {
"type": "user",
"id": "d1f3b5a7-c9e2-4b4d-8f6a-0c2e4a6b8d0f",
"name": "API: ERP sync",
"avatar_url": null
},
"channel": "none",
"delivery_status": null,
"delivery_error": null,
"mentions": ["0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b"],
"meta": {},
"attachments": [],
"created_at": "2026-11-25T09:52:11.018000+00:00",
"edited_at": null
}
```
| Field | Type | Description |
|---|---|---|
| `id` | string | The comment's id. |
| `ticket_id` | string | The ticket. |
| `visibility` | string | `public` or `internal`. |
| `body` | string | The text as sent. |
| `body_text` | string | The text without HTML. |
| `author_type` | string | `user`, `requester`, `ai` or `system`. |
| `author` | object | `type`, `id` and `name` of the author (`avatar_url` for users). |
| `channel` | string | Where a public reply was sent: `email`, `whatsapp`, `portal`, `slack`, `voice`, or `none` for internal notes and replies with no channel. |
| `delivery_status` | string or null | For public replies sent on a channel: `queued` at first, then for example `sent`, `delivered`, `read` or `failed`. `null` when nothing is sent. |
| `delivery_error` | string or null | Why delivery failed. |
| `mentions` | array of strings | Mentioned user ids. |
| `meta` | object | Extra details, such as the WhatsApp template used. |
| `attachments` | array | Files on the comment: `id`, `filename`, `content_type`, `size_bytes`. |
| `created_at` | string | When it was added. |
| `edited_at` | string or null | When it was last edited. |
Delivery happens after the response. Listen for the `comment.delivery_updated` [webhook](https://docs.lemuai.com/tickets-api/webhooks), or read the comment again with [List comments](https://docs.lemuai.com/tickets-api/tickets/list-comments), to see whether it arrived.
The first public reply on a ticket sets its `first_response_at`, which meets the first response SLA.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key cannot write internal notes, or cannot reply to requesters |
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
| `409` | `idempotency_mismatch` | The `Idempotency-Key` was used before with a different body |
| `422` | `invalid_fields` | `body` is missing or `visibility` is not `public` or `internal` |
| `422` | `empty_comment` | `body` only has spaces |
---
# List Comments
> List the replies and internal notes on a LemuTickets ticket, oldest first
URL: https://docs.lemuai.com/tickets-api/tickets/list-comments
Returns every comment on a ticket, oldest first: public replies (from your team, the requester, AI and automations) and internal notes.
**Endpoint:** `GET /v1/tickets/{ref}/comments`
Needs the `tickets.read` scope. Internal notes are only returned with the `comments.internal` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`) or id. |
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `visibility` | string | No | `public` for replies only, `internal` for notes only. Default: both. |
**Example request:**
```bash
curl -G https://api.tickets.lemuai.com/v1/tickets/SUP-1042/comments \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode "visibility=public"
```
## Response
**`200`** with all comments at once (this list is not paged).
```json
{
"data": [
{
"id": "f4a6c8e0-2b1d-4f3a-9c5e-7b9d1f3a5c7e",
"ticket_id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"visibility": "public",
"body": "Hi, I still have not received the refund for order 58213.",
"body_text": "Hi, I still have not received the refund for order 58213.",
"author_type": "requester",
"author": {
"type": "requester",
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma"
},
"channel": "email",
"delivery_status": null,
"delivery_error": null,
"mentions": [],
"meta": {},
"attachments": [
{
"id": "a9c1e3b5-d7f2-4a4c-9e6b-8d0f2a4c6e8b",
"filename": "bank-statement.pdf",
"content_type": "application/pdf",
"size_bytes": 182344
}
],
"created_at": "2026-11-25T09:40:02.771000+00:00",
"edited_at": null
},
{
"id": "1b3d5f7a-9c2e-4a4b-8d6f-0a2c4e6b8d1f",
"ticket_id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"visibility": "public",
"body": "Your refund of Rs 4,250 was processed today. It reaches your account in 3 to 5 working days.",
"body_text": "Your refund of Rs 4,250 was processed today. It reaches your account in 3 to 5 working days.",
"author_type": "user",
"author": {
"type": "user",
"id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"name": "Arjun Mehta",
"avatar_url": null
},
"channel": "email",
"delivery_status": "sent",
"delivery_error": null,
"mentions": [],
"meta": {},
"attachments": [],
"created_at": "2026-11-25T10:02:18.640000+00:00",
"edited_at": null
}
]
}
```
Each item has the fields described in [Add a comment](https://docs.lemuai.com/tickets-api/tickets/add-comment#response). Download links for attachments come from `GET /v1/attachments/{attachment_id}` (see [Upload an attachment](https://docs.lemuai.com/tickets-api/attachments/upload#downloading-a-file)).
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
---
# Log Work
> Record time spent on a LemuTickets ticket
URL: https://docs.lemuai.com/tickets-api/tickets/log-work
Records time someone spent on a ticket. Logged time adds up in the ticket's `time_spent_minutes` and appears in reports, separately from how long the ticket was open.
**Endpoint:** `POST /v1/tickets/{ref}/worklogs`
Use a key with the `tickets.write` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket key (`SUP-1042`) or id. |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `minutes` | integer | Yes | Time spent, `1` to `1440` (24 hours). |
| `started_at` | string (date-time) | No | When the work started. Defaults to now. |
| `note` | string | No | What was done. |
| `billable` | boolean | No | Whether the time can be billed to the customer. Default `false`. |
| `user_id` | string (UUID) | No | The team member who did the work. Defaults to the caller: for an API key, the key's own user. Required with a client credentials token. |
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets/SUP-1042/worklogs \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"minutes": 45,
"started_at": "2026-11-25T08:30:00+05:30",
"note": "Checked the payment gateway logs and raised the refund.",
"billable": false,
"user_id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b"
}'
```
This endpoint does not use idempotency keys. If you retry after a timeout, check the ticket's `time_spent_minutes` first so the time is not logged twice.
## Response
**`201`**
```json
{
"id": "b3d5f7a9-c1e2-4b6d-8f0a-2c4e6a8b0d2f",
"minutes": 45,
"total_minutes": 105
}
```
| Field | Type | Description |
|---|---|---|
| `id` | string | The worklog's id. |
| `minutes` | integer | The minutes logged by this request. |
| `total_minutes` | integer | All time logged on the ticket so far. |
This fires the `worklog.created` [webhook](https://docs.lemuai.com/tickets-api/webhooks).
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `ticket_not_found` | No ticket with this key or id, or you cannot see it |
| `422` | `invalid_fields` | `minutes` is missing or not between `1` and `1440` |
| `422` | `missing_user` | The caller is not a user and no `user_id` was sent |
---
# Link Tickets
> Link two LemuTickets tickets: relates to, blocks, duplicates, caused by or clones
URL: https://docs.lemuai.com/tickets-api/tickets/link
Links one ticket to another, for example to show that a delivery issue blocks a refund, or that two complaints are about the same problem.
**Endpoint:** `POST /v1/tickets/{ref}/links`
Use a key with the `tickets.write` scope. You must be able to see both tickets.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The ticket the link starts from: key (`SUP-1042`) or id. |
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `target` | string | Yes | The other ticket: key or id. |
| `kind` | string | No | How they relate, read as "this ticket *kind* target". Default `relates_to`. |
| `kind` | Meaning | Seen from the target as |
|---|---|---|
| `relates_to` | The tickets are related | `relates_to` |
| `blocks` | This ticket blocks the target | `blocked_by` |
| `duplicates` | This ticket duplicates the target | `duplicated_by` |
| `caused_by` | This ticket was caused by the target | `causes` |
| `clones` | This ticket is a copy of the target | `cloned_by` |
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets/SUP-1042/links \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{ "target": "SUP-1039", "kind": "caused_by" }'
```
## Response
**`201`**
```json
{
"id": "0a2c4e6b-8d0f-4a1c-9e3b-5d7f9a1c3e5b",
"kind": "caused_by",
"target": "SUP-1039"
}
```
| Field | Type | Description |
|---|---|---|
| `id` | string | The link's id. |
| `kind` | string | The link kind. |
| `target` | string | The target ticket's key. |
Linking the same two tickets with the same `kind` again returns the existing link, so it is safe to retry. A new link fires the `ticket.linked` [webhook](https://docs.lemuai.com/tickets-api/webhooks) on the source ticket.
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `ticket_not_found` | Either ticket does not exist, or you cannot see it |
| `422` | `invalid_link` | A ticket cannot link to itself |
| `422` | `invalid_fields` | `target` is missing or `kind` is not one of the values above |
---
# Create or Update a Requester
> Find a LemuTickets requester by email, phone or other ids, or create one
URL: https://docs.lemuai.com/tickets-api/requesters/upsert
A **requester** is the customer who raises tickets: a person with a name, email, phone, WhatsApp number and, optionally, an account (their company). This endpoint finds the requester that matches the details you send, or creates one.
**Endpoint:** `POST /v1/requesters`
Needs the `requesters.write` scope.
To keep requesters in step with records in your ERP, [Upsert a requester by external ID](https://docs.lemuai.com/tickets-api/requesters/upsert-by-external-id) is usually simpler: it matches on your own id and updates exactly the fields you send.
## How the requester is found
LemuTickets looks for an existing requester in this order and uses the first match:
1. `lemu_contact_id`
2. `email` (not case sensitive)
3. `phone` (formatting is ignored; numbers without a country code are read as `+91`)
4. `whatsapp_id`
5. `external_id`
If there is a match, empty details on it are filled in from your request. Details that are already set (by your team or an earlier request) are **not** overwritten. If there is no match, a new requester is created. A new requester whose email domain matches an [account's](https://docs.lemuai.com/tickets-api/accounts/list) domain is added to that account.
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | No | Full name. |
| `email` | string | No | Email address. |
| `phone` | string | No | Phone number, ideally in international format. |
| `whatsapp_id` | string | No | WhatsApp number. |
| `external_id` | string | No | Your own id for the customer. |
| `account_id` | string (UUID) | No | The account (company) the requester belongs to. |
| `language` | string | No | Preferred language, for example `en` or `hi`. |
| `lemu_contact_id` | integer | No | The contact's id in Lemu AI, if you use both products. |
| `is_vip` | boolean | No | Mark as VIP. Default `false`. |
| `tags` | array of strings | No | Tags. |
| `custom_fields` | object | No | Extra values. Merged into existing custom fields. |
Send at least one of `email`, `phone`, `whatsapp_id`, `external_id` or `lemu_contact_id`, or every request creates a new requester.
**Note:** `is_vip` and `tags` always replace the stored values, even on an existing requester. If you leave them out, the requester's VIP flag is set to `false` and its tags are cleared. Send the current values, or use [Upsert a requester by external ID](https://docs.lemuai.com/tickets-api/requesters/upsert-by-external-id), which only changes the fields you send.
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/requesters \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "98765 43210",
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"language": "en",
"is_vip": true,
"tags": ["distributor"],
"custom_fields": { "gstin": "29ABCDE1234F1Z5" }
}'
```
## Response
**`201`** with the requester, whether it was created or found.
```json
{
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"whatsapp_id": null,
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"language": "en",
"is_vip": true,
"external_id": null,
"lemu_contact_id": null,
"tags": ["distributor"],
"custom_fields": { "gstin": "29ABCDE1234F1Z5" },
"anonymised": false,
"created_at": "2026-11-25T09:05:12.330000+00:00",
"open_tickets": null
}
```
## Requester fields
| Field | Type | Description |
|---|---|---|
| `id` | string | The requester's id. Use it as `requester_id` when [creating tickets](https://docs.lemuai.com/tickets-api/tickets/create). |
| `name` | string | Full name. |
| `email` | string or null | Email, stored in lower case. Partly hidden without the `pii.read` scope. |
| `phone` | string or null | Phone in international format. Partly hidden without `pii.read`. |
| `whatsapp_id` | string or null | WhatsApp number. Partly hidden without `pii.read`. |
| `account_id` | string or null | The account (company). |
| `language` | string or null | Preferred language. |
| `is_vip` | boolean | Marked as VIP. Find their tickets with the TQL query `requester.vip = true`. |
| `external_id` | string or null | Your own id. |
| `lemu_contact_id` | integer or null | The matching Lemu AI contact, if any. |
| `tags` | array of strings | Tags. |
| `custom_fields` | object | Extra values. |
| `anonymised` | boolean | `true` if the requester's personal data was erased. |
| `created_at` | string | When the requester was created. |
| `open_tickets` | integer or null | Tickets that are not done. Filled in by [List requesters](https://docs.lemuai.com/tickets-api/requesters/list); `null` here. |
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `requesters.write` |
| `422` | `invalid_fields` | A field has the wrong type |
---
# Upsert a Requester by External ID
> Create or update a LemuTickets requester using your own customer id
URL: https://docs.lemuai.com/tickets-api/requesters/upsert-by-external-id
Creates or updates the requester with your own id for the customer, for example the customer number in your ERP. Use it whenever a customer record is created or changes in your system.
**Endpoint:** `PUT /v1/requesters/by-external-id/{external_id}`
Needs the `requesters.write` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `external_id` | string | Yes | Your own id for the customer, URL-encoded. |
## How it works
- **A requester with this `external_id` exists:** the fields you send are updated. Fields you leave out keep their values.
- **None exists yet:** LemuTickets looks for the same person by email, phone or WhatsApp number (see [how the requester is found](https://docs.lemuai.com/tickets-api/requesters/upsert#how-the-requester-is-found)), or creates a new requester, and then applies the fields you send. Later requests with the same id update the same requester.
## Request body
The same fields as [Create or update a requester](https://docs.lemuai.com/tickets-api/requesters/upsert#request-body), all optional. `external_id` in the body is ignored; the one in the path is used.
| Field | What happens |
|---|---|
| `name`, `email`, `phone`, `whatsapp_id`, `account_id`, `language`, `is_vip`, `lemu_contact_id` | Set to the value you send. |
| `tags` | Replaces all tags. |
| `custom_fields` | Replaces all custom fields. |
**Example request:**
```bash
curl -X PUT https://api.tickets.lemuai.com/v1/requesters/by-external-id/CUST-20931 \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"is_vip": true,
"custom_fields": { "gstin": "29ABCDE1234F1Z5", "credit_limit": 500000 }
}'
```
## Response
**`200`** with the requester.
```json
{
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"whatsapp_id": null,
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"language": "en",
"is_vip": true,
"external_id": "CUST-20931",
"lemu_contact_id": null,
"tags": ["distributor"],
"custom_fields": { "gstin": "29ABCDE1234F1Z5", "credit_limit": 500000 },
"anonymised": false,
"created_at": "2026-11-25T09:05:12.330000+00:00",
"open_tickets": null
}
```
See [requester fields](https://docs.lemuai.com/tickets-api/requesters/upsert#requester-fields).
A requester created by this endpoint has your id in `external_id`. You can then use it to [issue embed tokens](https://docs.lemuai.com/tickets-api/embedding) (`requester_external_id`) and to search with `GET /v1/requesters?q=CUST-20931`.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `requesters.write` |
| `422` | `invalid_fields` | A field has the wrong type |
---
# List Requesters
> List and search the requesters (customers) in LemuTickets
URL: https://docs.lemuai.com/tickets-api/requesters/list
Returns requesters a page at a time, newest first, with how many open tickets each one has.
**Endpoint:** `GET /v1/requesters`
Needs the `requesters.read` scope.
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `q` | string | No | Search. Matches part of the name, email or phone, or the exact `external_id`. |
| `account_id` | string (UUID) | No | Only requesters in this account. |
| `limit` | integer | No | Requesters per page, up to `200`. Default `50`. |
| `cursor` | string | No | The `next_cursor` from the previous page. See [pagination](https://docs.lemuai.com/tickets-api/conventions#pagination). |
**Example request:**
```bash
curl -G https://api.tickets.lemuai.com/v1/requesters \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode "q=priya" \
--data-urlencode "limit=20"
```
## Response
**`200`**
```json
{
"data": [
{
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"whatsapp_id": "+919876543210",
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"language": "en",
"is_vip": true,
"external_id": "CUST-20931",
"lemu_contact_id": 901,
"tags": ["distributor"],
"custom_fields": { "gstin": "29ABCDE1234F1Z5" },
"anonymised": false,
"created_at": "2026-11-25T09:05:12.330000+00:00",
"open_tickets": 2
}
],
"next_cursor": null
}
```
| Field | Type | Description |
|---|---|---|
| `data` | array | The requesters on this page. See [requester fields](https://docs.lemuai.com/tickets-api/requesters/upsert#requester-fields). `open_tickets` counts tickets that are not done. |
| `next_cursor` | string or null | Pass as `cursor` for the next page. `null` on the last page. |
Without the `pii.read` scope, `email`, `phone` and `whatsapp_id` are partly hidden, for example `p•••@example.com`.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `requesters.read` |
| `422` | `invalid_fields` | `limit` is over `200`, or `account_id` is not a UUID |
---
# Get a Requester
> Get one LemuTickets requester with their account, recent tickets and average satisfaction score
URL: https://docs.lemuai.com/tickets-api/requesters/get
Returns one requester with their account, their 50 most recent tickets and their average CSAT score. Useful for a customer view in your ERP.
**Endpoint:** `GET /v1/requesters/{requester_id}`
Needs the `requesters.read` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `requester_id` | string (UUID) | Yes | The requester's `id`. |
**Example request:**
```bash
curl https://api.tickets.lemuai.com/v1/requesters/8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`200`**
```json
{
"id": "8b4d6f2a-0c1e-4a3b-9d5f-7e6a8c0b2d4f",
"name": "Priya Sharma",
"email": "priya@example.com",
"phone": "+919876543210",
"whatsapp_id": "+919876543210",
"account_id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"language": "en",
"is_vip": true,
"external_id": "CUST-20931",
"lemu_contact_id": 901,
"tags": ["distributor"],
"custom_fields": { "gstin": "29ABCDE1234F1Z5" },
"anonymised": false,
"created_at": "2026-11-25T09:05:12.330000+00:00",
"open_tickets": null,
"account": {
"id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"name": "Sharma Traders",
"tier": "premium"
},
"tickets": [
{
"id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"key": "SUP-1042",
"title": "Refund not received for order 58213",
"status_category": "done",
"priority": "p1",
"created_at": "2026-11-25T09:12:40.512000+00:00",
"csat_score": 5
},
{
"id": "6d8f0a2c-4e6b-4c8d-a0f2-c4e6a8b0d2f4",
"key": "SUP-1039",
"title": "Order 58213 cancelled without notice",
"status_category": "open",
"priority": "p2",
"created_at": "2026-11-24T16:45:03.118000+00:00",
"csat_score": null
}
],
"csat_average": 5.0
}
```
The response has the [requester fields](https://docs.lemuai.com/tickets-api/requesters/upsert#requester-fields), plus:
| Field | Type | Description |
|---|---|---|
| `account` | object or null | The requester's account: `id`, `name`, `tier`. |
| `tickets` | array | Up to 50 of the requester's tickets, newest first: `id`, `key`, `title`, `status_category`, `priority`, `created_at`, `csat_score`. Use [List and search tickets](https://docs.lemuai.com/tickets-api/tickets/list) with `requester_id` for all of them. |
| `csat_average` | number or null | The average of the requester's ratings on these tickets, or `null` if they never rated one. |
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `requesters.read` |
| `404` | `not_found` | No requester with this id |
---
# List Accounts
> List and search the customer accounts (companies) in LemuTickets
URL: https://docs.lemuai.com/tickets-api/accounts/list
An **account** is a customer company, such as a distributor, dealer or business customer. Requesters belong to an account, and tickets carry the requester's account. This endpoint returns accounts a page at a time, sorted by name, with how many open tickets each one has.
**Endpoint:** `GET /v1/accounts`
Needs the `requesters.read` scope.
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `q` | string | No | Search. Matches part of the name, or the exact `external_id`. |
| `limit` | integer | No | Accounts per page, up to `200`. Default `50`. |
| `cursor` | string | No | The `next_cursor` from the previous page. See [pagination](https://docs.lemuai.com/tickets-api/conventions#pagination). |
**Example request:**
```bash
curl -G https://api.tickets.lemuai.com/v1/accounts \
-H "Authorization: Bearer ltk_live_your_api_key" \
--data-urlencode "q=sharma"
```
## Response
**`200`**
```json
{
"data": [
{
"id": "4a6c8e0b-2d1f-4b3a-8c5e-9f7d1b3a5c6e",
"name": "Sharma Traders",
"domains": ["sharmatraders.in"],
"tier": "premium",
"owner_user_id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"phone": "+918041234567",
"address": "14 MG Road",
"city": "Bengaluru",
"region": "Karnataka",
"notes": "",
"health": "good",
"external_id": "DIST-0412",
"custom_fields": { "gstin": "29ABCDE1234F1Z5" },
"created_at": "2026-10-02T11:20:45.000000+00:00",
"open_tickets": 3
}
],
"next_cursor": null
}
```
| Field | Type | Description |
|---|---|---|
| `id` | string | The account's id. |
| `name` | string | Company name. |
| `domains` | array of strings | Email domains. New requesters with an email at one of these domains join the account automatically. |
| `tier` | string | `standard`, `premium` or `enterprise`. Use it in TQL as `account.tier`. |
| `owner_user_id` | string or null | The team member who owns the relationship. |
| `phone`, `address`, `city`, `region` | string or null | Contact details. |
| `notes` | string | Free-text notes. |
| `health` | string or null | `good`, `at_risk` or `unhappy`, when set. |
| `external_id` | string or null | Your own id for the account, for example the customer code in your ERP. |
| `custom_fields` | object | Extra values. |
| `created_at` | string | When the account was created. |
| `open_tickets` | integer | Tickets on the account that are not done. |
| `next_cursor` | string or null | Pass as `cursor` for the next page. `null` on the last page. |
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `requesters.read` |
| `422` | `invalid_fields` | `limit` is over `200` |
---
# List Projects
> List the LemuTickets projects you can create tickets in
URL: https://docs.lemuai.com/tickets-api/projects/list
A **project** is where tickets live, for example `SUP` for customer support or `LOG` for logistics. Each project has its own ticket types, workflow, fields and SLAs. This endpoint returns every project the key can access, sorted by name.
**Endpoint:** `GET /v1/projects`
Needs the `projects.read` scope.
## Query parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `include_archived` | boolean | No | Also return archived projects. Default `false`. |
**Example request:**
```bash
curl https://api.tickets.lemuai.com/v1/projects \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`200`** with all projects at once (this list is not paged).
```json
{
"data": [
{
"id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13",
"key": "SUP",
"name": "Customer Support",
"description": "Complaints and requests from customers on every channel",
"type": "service_desk",
"visibility": "open",
"lead_user_id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"default_team_id": "1c3e5a7b-9d2f-4e6a-b8c0-a2e4f6b8d0c1",
"default_type_id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47",
"color": "blue",
"icon": "headset",
"settings": {},
"external_id": null,
"archived": false,
"created_at": "2026-10-01T06:30:00.000000+00:00",
"open_tickets": 128,
"permissions": null
}
]
}
```
## Project fields
| Field | Type | Description |
|---|---|---|
| `id` | string | The project's id. |
| `key` | string | The short key used in ticket keys, for example `SUP`. Use it as `project` when [creating tickets](https://docs.lemuai.com/tickets-api/tickets/create). |
| `name` | string | The project's name. |
| `description` | string | What the project is for. |
| `type` | string | `service_desk`, `task_tracker`, `field_service`, `incident`, `itsm` or `internal_ops`. |
| `visibility` | string | `open` (every member sees it) or `private` (project members only). |
| `lead_user_id` | string or null | The project lead. |
| `default_team_id` | string or null | New tickets go to this team when no one is assigned. |
| `default_type_id` | string or null | The ticket type used when you don't send `type`. |
| `color`, `icon` | string | How the project looks in the app. |
| `settings` | object | Project settings. |
| `external_id` | string or null | Your own id for the project. |
| `archived` | boolean | Archived projects take no new tickets. |
| `created_at` | string | When the project was created. |
| `open_tickets` | integer | Tickets in the project that are not done. |
| `permissions` | array or null | Only on [Get a project](https://docs.lemuai.com/tickets-api/projects/get): what the caller may do in this project. `null` in this list. |
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `projects.read` |
---
# Get a Project
> Get one LemuTickets project with its ticket types, workflow statuses and transitions
URL: https://docs.lemuai.com/tickets-api/projects/get
Returns one project with its ticket types and workflows. Use it to learn the status names, categories and transitions to use in your integration, and the ticket type names you can send when [creating tickets](https://docs.lemuai.com/tickets-api/tickets/create).
**Endpoint:** `GET /v1/projects/{ref}`
Needs the `projects.read` scope in the project.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `ref` | string | Yes | The project key (`SUP`, not case sensitive) or id. |
**Example request:**
```bash
curl https://api.tickets.lemuai.com/v1/projects/SUP \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`200`**
```json
{
"id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13",
"key": "SUP",
"name": "Customer Support",
"description": "Complaints and requests from customers on every channel",
"type": "service_desk",
"visibility": "open",
"lead_user_id": "0e2a4c6b-8d1f-4a3e-9b5c-7d9f1a3c5e7b",
"default_team_id": "1c3e5a7b-9d2f-4e6a-b8c0-a2e4f6b8d0c1",
"default_type_id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47",
"color": "blue",
"icon": "headset",
"settings": {},
"external_id": null,
"archived": false,
"created_at": "2026-10-01T06:30:00.000000+00:00",
"open_tickets": 128,
"permissions": ["comments.internal", "projects.read", "requesters.read", "requesters.write", "tickets.read", "tickets.write"],
"types": [
{
"id": "9d2e4f60-1b3a-4c8d-a7e5-6f0b2c9d1e47",
"project_id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13",
"name": "Complaint",
"description": "",
"icon": "message-square-warning",
"color": "red",
"workflow_id": "2c4e6a8b-0d1f-4a3c-9e5b-7d9f1b3d5f7a",
"sla_policy_id": "7e9a1c3b-5d2f-4a6e-8b0c-1d3f5a7c9e2b",
"field_layout": [],
"is_subtask": false,
"archived": false
}
],
"workflows": [
{
"id": "2c4e6a8b-0d1f-4a3c-9e5b-7d9f1b3d5f7a",
"name": "Service desk",
"description": "",
"project_id": "3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13",
"initial_status_id": "4d7b9e1f-3a5c-4e8b-a0d2-f4b6c8e0a1d3",
"allow_any_transition": false,
"layout": {},
"statuses": [
{
"id": "4d7b9e1f-3a5c-4e8b-a0d2-f4b6c8e0a1d3",
"name": "New",
"category": "new",
"color": "sky",
"position": 0,
"pauses_sla": false,
"is_resolution": false,
"is_final": false,
"wip_limit": null
},
{
"id": "7a2b3c4d-9e5f-4a6b-b7c8-d9e0f1a2b3c4",
"name": "Resolved",
"category": "done",
"color": "green",
"position": 5,
"pauses_sla": false,
"is_resolution": true,
"is_final": false,
"wip_limit": null
}
],
"transitions": [
{
"id": "b1d3f5a7-9c2e-4b4d-8f6a-1c3e5a7b9d0f",
"name": "Resolve",
"from_status_id": null,
"to_status_id": "7a2b3c4d-9e5f-4a6b-b7c8-d9e0f1a2b3c4",
"conditions": {},
"validators": {},
"post_actions": [],
"approval": {}
}
]
}
]
}
```
The response has the [project fields](https://docs.lemuai.com/tickets-api/projects/list#project-fields) (with `permissions` filled in), plus:
| Field | Type | Description |
|---|---|---|
| `permissions` | array of strings | The scopes the caller has in this project. |
| `types` | array | The project's ticket types: `id`, `name`, `description`, `icon`, `color`, the `workflow_id` it uses, its `sla_policy_id`, `is_subtask` and `archived`. |
| `workflows` | array | The workflows the types use (shortened above). |
Each workflow has:
| Field | Description |
|---|---|
| `initial_status_id` | The status new tickets start in. |
| `allow_any_transition` | `true` if tickets can move to any status, ignoring `transitions`. |
| `statuses` | Each status: `id`, `name`, `category` (`new`, `open`, `waiting`, `done`), `color`, `position`, `pauses_sla` (the SLA clock stops in this status), `is_resolution` (reaching it counts as resolved), `is_final` (reaching it closes the ticket) and `wip_limit`. |
| `transitions` | Each transition: `id`, `name`, `from_status_id` (`null` means from any status), `to_status_id`, `conditions` (who may use it), `validators` (`required_fields`, `require_comment`), `post_actions` and `approval`. |
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `projects.read` in this project |
| `404` | `project_not_found` | No project with this key or id, or the key cannot access it |
---
# Upload an Attachment
> Upload a file to a LemuTickets ticket, or to attach to a comment
URL: https://docs.lemuai.com/tickets-api/attachments/upload
Uploads a file of up to 25 MB, such as an invoice, a photo of a damaged product or a log file. You can attach it to a ticket straight away, or upload it first and then attach it to a comment with [Add a comment](https://docs.lemuai.com/tickets-api/tickets/add-comment) (`attachment_ids`).
**Endpoint:** `POST /v1/attachments`
Attaching to a ticket needs the `tickets.write` scope in the ticket's project.
## Request body
Send the file as `multipart/form-data`, not JSON.
| Field | Type | Required | Description |
|---|---|---|---|
| `file` | file | Yes | The file. Up to 25 MB. |
| `ticket` | string | No | The ticket key (`SUP-1042`) or id to attach the file to. Leave it out to upload a file for a comment you post next. |
| `inline` | boolean | No | `true` for an image shown inside a comment's text rather than as a separate file. Default `false`. |
Executables and scripts are refused, by extension (for example `.exe`, `.msi`, `.bat`, `.sh`, `.js`, `.apk`, `.dmg`, `.ps1`, `.vbs`, `.jar`) and by content.
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/attachments \
-H "Authorization: Bearer ltk_live_your_api_key" \
-F "file=@invoice-58213.pdf;type=application/pdf" \
-F "ticket=SUP-1042"
```
To attach the file to a comment, upload it without `ticket` (or with the same ticket), then send its `id` in `attachment_ids`:
```bash
curl -X POST https://api.tickets.lemuai.com/v1/tickets/SUP-1042/comments \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"body": "Please find the credit note attached.",
"visibility": "public",
"attachment_ids": ["a9c1e3b5-d7f2-4a4c-9e6b-8d0f2a4c6e8b"]
}'
```
## Response
**`201`**
```json
{
"id": "a9c1e3b5-d7f2-4a4c-9e6b-8d0f2a4c6e8b",
"filename": "invoice-58213.pdf",
"content_type": "application/pdf",
"size_bytes": 182344,
"scan_status": "clean",
"inline": false,
"ticket_id": "2f9c7e1a-5b3d-4c8e-9a6f-1d0e2b4c6a8f",
"comment_id": null,
"created_at": "2026-11-25T10:05:33.902000+00:00",
"download_url": "",
"download_expires_in": 900
}
```
| Field | Type | Description |
|---|---|---|
| `id` | string | The attachment's id. Use it in `attachment_ids`. |
| `filename` | string | The file name, cleaned of unsafe characters. |
| `content_type` | string | The file's type. |
| `size_bytes` | integer | The size. |
| `scan_status` | string | `clean` when the file is stored and can be downloaded. |
| `inline` | boolean | Whether it is an inline image. |
| `ticket_id` | string or null | The ticket it belongs to. |
| `comment_id` | string or null | The comment it belongs to, once attached to one. |
| `created_at` | string | When it was uploaded. |
| `download_url` | string or null | A link to download the file. It works for 15 minutes. |
| `download_expires_in` | integer or null | Seconds until `download_url` stops working (`900`). |
### Downloading a file
`download_url` expires after 15 minutes, so don't store it. To get a fresh link later, call:
```bash
curl https://api.tickets.lemuai.com/v1/attachments/a9c1e3b5-d7f2-4a4c-9e6b-8d0f2a4c6e8b \
-H "Authorization: Bearer ltk_live_your_api_key"
```
It returns the same fields with a new `download_url`.
## Errors
| Status | `code` | When |
|---|---|---|
| `404` | `ticket_not_found` | `ticket` does not exist, or you cannot see it |
| `422` | `file_too_large` | The file is over 25 MB |
| `422` | `empty_file` | The file is empty |
| `422` | `blocked_file_type` | The file is an executable or script |
| `422` | `invalid_fields` | `file` is missing |
---
# Create a Webhook
> Subscribe a URL to LemuTickets events; the signing secret is returned once
URL: https://docs.lemuai.com/tickets-api/webhook-subscriptions/create
Creates a webhook subscription: LemuTickets sends a signed `POST` to your URL for every matching event. See [Webhooks](https://docs.lemuai.com/tickets-api/webhooks) for the event list, the payload, verifying signatures and retries.
**Endpoint:** `POST /v1/webhooks`
Needs the `api_keys.manage` scope.
## Request body
| Field | Type | Required | Description |
|---|---|---|---|
| `url` | string | Yes | Where to send events. `https://` is recommended. Must resolve to a public address. Up to 1,000 characters. |
| `events` | array of strings | Yes | Event names or patterns, for example `["ticket.created", "ticket.transitioned", "comment.*"]`. Each must match at least one [event](https://docs.lemuai.com/tickets-api/webhooks#events). |
| `description` | string | No | A note for your team, for example `ERP ticket sync`. |
| `project_ids` | array of UUIDs | No | Only send events for tickets in these projects. Empty (default) means all projects and also events that are not about a ticket. |
| `enabled` | boolean | No | Default `true`. Set `false` to create it switched off. |
**Example request:**
```bash
curl -X POST https://api.tickets.lemuai.com/v1/webhooks \
-H "Authorization: Bearer ltk_live_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"url": "https://erp.example.com/lemutickets/webhook",
"events": ["ticket.created", "ticket.transitioned", "ticket.updated", "comment.created"],
"description": "ERP ticket sync",
"project_ids": ["3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13"]
}'
```
## Response
**`201`**
```json
{
"id": "f2a4c6e8-0b1d-4f3a-8c5e-a7c9e1b3d5f7",
"url": "https://erp.example.com/lemutickets/webhook",
"description": "ERP ticket sync",
"events": ["comment.created", "ticket.created", "ticket.transitioned", "ticket.updated"],
"project_ids": ["3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13"],
"enabled": true,
"failure_count": 0,
"disabled_reason": null,
"last_success_at": null,
"last_failure_at": null,
"created_at": "2026-11-25T10:10:00.120000+00:00",
"updated_at": "2026-11-25T10:10:00.120000+00:00",
"secret": "whsec_Lr6c0Xh2vJ9kQ1pT8sW3nB5mA7dF4gE2"
}
```
**Warning:** `secret` is only returned here. Store it straight away: you need it to [verify signatures](https://docs.lemuai.com/tickets-api/webhooks#verify-the-signature). If you lose it, issue a new one with **Rotate secret** in **Settings → API keys and webhooks**.
| Field | Type | Description |
|---|---|---|
| `id` | string | The webhook's id. |
| `url` | string | The endpoint URL. |
| `description` | string | Your note. |
| `events` | array of strings | The event patterns, sorted and without duplicates. |
| `project_ids` | array of strings | The project filter. Empty means all. |
| `enabled` | boolean | Whether events are being sent. |
| `failure_count` | integer | Failed attempts in a row. Resets on a successful delivery. |
| `disabled_reason` | string or null | Why the webhook was turned off automatically, if it was. |
| `last_success_at`, `last_failure_at` | string or null | The last successful and failed delivery. |
| `created_at`, `updated_at` | string | Timestamps. |
| `secret` | string | The signing secret (`whsec_...`). Only in this response. |
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `api_keys.manage` |
| `422` | `missing_events` | `events` is empty |
| `422` | `invalid_events` | A pattern matches no event. `data.unknown` lists them |
| `422` | `invalid_url` | The URL does not start with `http://` or `https://` |
| `422` | `private_address` | The URL points at a private, local or internal address |
| `422` | `unresolvable_host` | The URL's host name does not resolve |
---
# List Webhooks
> List your organization's LemuTickets webhook subscriptions and their delivery health
URL: https://docs.lemuai.com/tickets-api/webhook-subscriptions/list
Returns every webhook subscription in your organization, oldest first. Check `enabled`, `failure_count` and `disabled_reason` to spot an endpoint that stopped accepting deliveries.
**Endpoint:** `GET /v1/webhooks`
Needs the `api_keys.manage` scope.
**Example request:**
```bash
curl https://api.tickets.lemuai.com/v1/webhooks \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`200`** with all webhooks at once (this list is not paged).
```json
{
"data": [
{
"id": "f2a4c6e8-0b1d-4f3a-8c5e-a7c9e1b3d5f7",
"url": "https://erp.example.com/lemutickets/webhook",
"description": "ERP ticket sync",
"events": ["comment.created", "ticket.created", "ticket.transitioned", "ticket.updated"],
"project_ids": ["3b0f6c1e-8a2d-4f5b-9c71-0e4d2a6b8f13"],
"enabled": true,
"failure_count": 0,
"disabled_reason": null,
"last_success_at": "2026-11-25T10:02:21.447000+00:00",
"last_failure_at": null,
"created_at": "2026-11-25T10:10:00.120000+00:00",
"updated_at": "2026-11-25T10:10:00.120000+00:00"
}
]
}
```
The fields are described in [Create a webhook](https://docs.lemuai.com/tickets-api/webhook-subscriptions/create#response). The signing secret is never returned here.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `api_keys.manage` |
---
# Delete a Webhook
> Remove a LemuTickets webhook subscription so no more events are sent to it
URL: https://docs.lemuai.com/tickets-api/webhook-subscriptions/delete
Deletes a webhook subscription. No more events are sent to its URL. This cannot be undone; to stop deliveries for a while instead, turn off **Send events** on the webhook in **Settings → API keys and webhooks**.
**Endpoint:** `DELETE /v1/webhooks/{webhook_id}`
Needs the `api_keys.manage` scope.
## Path parameters
| Name | Type | Required | Description |
|---|---|---|---|
| `webhook_id` | string (UUID) | Yes | The webhook's `id`, from [List webhooks](https://docs.lemuai.com/tickets-api/webhook-subscriptions/list). |
**Example request:**
```bash
curl -X DELETE https://api.tickets.lemuai.com/v1/webhooks/f2a4c6e8-0b1d-4f3a-8c5e-a7c9e1b3d5f7 \
-H "Authorization: Bearer ltk_live_your_api_key"
```
## Response
**`204`** with no body.
## Errors
| Status | `code` | When |
|---|---|---|
| `403` | `missing_capability` | The key does not have `api_keys.manage` |
| `404` | `webhook_not_found` | No webhook with this id |
| `422` | `invalid_fields` | `webhook_id` is not a UUID |