# Tickets (/guides/tickets)

Tickets track customer requests in CallMitra's helpdesk. Your agents and your team open them in calls, WhatsApp chats and the console. With the API you can create tickets from your own systems, keep them in sync, add notes and reply to the customer.

| Endpoint | What it does |
| --- | --- |
| [`GET /api/v1/tickets/`](/api-reference/tickets/listTickets) | List and filter tickets |
| [`POST /api/v1/tickets/`](/api-reference/tickets/createTicket) | Create a ticket |
| [`GET /api/v1/tickets/{ticket_id}`](/api-reference/tickets/getTicket) | Get a ticket with its latest activities |
| [`PATCH /api/v1/tickets/{ticket_id}`](/api-reference/tickets/updateTicket) | Update a ticket |
| [`GET /api/v1/tickets/{ticket_id}/activities`](/api-reference/tickets/listTicketActivities) | Page through older activities |
| [`POST /api/v1/tickets/{ticket_id}/activities`](/api-reference/tickets/addTicketNote) | Add a private team note |
| [`POST /api/v1/tickets/{ticket_id}/replies`](/api-reference/tickets/replyToTicket) | Reply to the customer on WhatsApp |
| [`GET /api/v1/tickets/categories`](/api-reference/tickets/listTicketCategories) | List categories |
| [`GET /api/v1/tickets/teams`](/api-reference/tickets/listTicketTeams) | List teams |

A key limited to resources needs **Tickets** ([Authentication](/authentication)).

## The ticket [#the-ticket]

| Field | Description |
| --- | --- |
| `id` | Ticket ID. |
| `ref` | Short reference shown to people, for example `T-1A2B3C4D`. |
| `subject`, `description` | One-line summary and details. |
| `status` | `open`, `in_progress`, `waiting_on_customer`, `resolved` or `closed`. |
| `priority` | `low`, `normal`, `high` or `urgent`. |
| `type` | `support` or `sales_followup`. |
| `source` | How it was opened: `manual`, `inbound_call`, `outbound_call`, `import` or `whatsapp_conversation`. |
| `leadId`, `leadName`, `leadPhone` | The lead (customer) the ticket is about. Every ticket has one. |
| `sourceCallId` | The call that opened the ticket, if any. |
| `waConversationId` | The WhatsApp conversation it came from, if any. |
| `categoryId`, `categoryName` | The category, or `null`. |
| `teamId`, `teamName` | The team it is routed to, or `null`. |
| `assignees` | Everyone assigned (`userId`, `name`, `email`), in assignment order. |
| `assignedToUserId` | The first assignee's user ID, or `null` when unassigned. |
| `tags` | Tags. |
| `dueAt`, `overdue` | Resolution due time, and whether it has passed without the ticket being resolved. |
| `sla` | Service-level targets: `firstResponse`, `resolution` and `paused`. |
| `createdAt`, `updatedAt`, `resolvedAt`, `closedAt` | Timestamps (ISO 8601). |
| `mergedIntoId` | Set when the ticket was merged into another. A merged ticket is read-only. |
| `version` | Goes up on every change. Send it back to avoid overwriting someone else's change. |

A single ticket ([get](/api-reference/tickets/getTicket), and the `ticket` in update responses) also has `canEdit`, `canManageAssignees` and `canReopenClosed`: what the key's user may do with it.

## List tickets [#list-tickets]

The list is sorted by last change, newest first. It is paged with `page` and `limit` (default 25, up to 200). See [Pagination](/pagination).

| Query parameter | Description |
| --- | --- |
| `page`, `limit` | Page number from 1, and tickets per page (1–200). |
| `search` | Ticket ref, words in the subject or description, or the lead's name or phone. |
| `status` | One status. `open` also matches `in_progress` and `waiting_on_customer`. |
| `priority` | `low`, `normal`, `high` or `urgent`. |
| `type` | `support` or `sales_followup`. |
| `leadId` | Only this lead's tickets. |
| `sourceCallId` | Only tickets opened from this call. |
| `categoryId` | Category ID, or `none` for tickets without one. |
| `teamId` | Team ID, or `none` for tickets without one. |
| `tag` | Only tickets with this tag. |
| `unassigned` | `true` for tickets nobody is assigned to. |
| `sort` | `updated` (the default), `created`, `due`, `priority` or `status`. |
| `dir` | `asc` or `desc`. |

<Tabs groupId="language" persist items={["cURL","Node.js","Python"]}>
<Tab value="cURL">
```bash
curl "https://api.callmitra.ai/api/v1/tickets/?status=open&priority=urgent&limit=50" \
  -H "X-API-Key: $CALLMITRA_API_KEY"
```
</Tab>

<Tab value="Node.js">
```js
const params = new URLSearchParams({ status: 'open', priority: 'urgent', limit: '50' });
const res = await fetch(`https://api.callmitra.ai/api/v1/tickets/?${params}`, {
  headers: { 'X-API-Key': process.env.CALLMITRA_API_KEY },
});
const { tickets, pagination } = await res.json();
```
</Tab>

<Tab value="Python">
```python
import os
import requests

res = requests.get(
    "https://api.callmitra.ai/api/v1/tickets/",
    headers={"X-API-Key": os.environ["CALLMITRA_API_KEY"]},
    params={"status": "open", "priority": "urgent", "limit": 50},
    timeout=30,
)
data = res.json()
tickets, pagination = data["tickets"], data["pagination"]
```
</Tab>
</Tabs>

```json
{
  "success": true,
  "tickets": [
    {
      "id": "a1b2c3d4-0000-4000-8000-000000000001",
      "ref": "T-A1B2C3D4",
      "subject": "Refund not received",
      "status": "open",
      "priority": "urgent",
      "type": "support",
      "leadId": "5e6f7a8b-0000-4000-8000-000000000002",
      "leadName": "Asha Verma",
      "leadPhone": "+919812345678",
      "teamId": null,
      "assignees": [],
      "version": 3
    }
  ],
  "pagination": {
    "currentPage": 1,
    "itemsPerPage": 50,
    "totalItems": 1,
    "totalPages": 1,
    "hasNextPage": false,
    "hasPreviousPage": false,
    "totalCapped": false
  },
  "sort": { "key": "updated", "dir": "desc" }
}
```

The ticket above is shortened. `totalCapped` is `true` when `totalItems` stopped counting at the cap.

## Create a ticket [#create-a-ticket]

Every ticket belongs to a lead. Send `leadId`, or `waConversationId` to open the ticket from a WhatsApp conversation (its contact's lead is used and `source` becomes `whatsapp_conversation`). If you send both, they must point to the same lead. Sending neither fails with `422` [`parameter_invalid`](/errors/parameter_invalid).

| Field | Description |
| --- | --- |
| `subject` | Required. One-line summary, 1–512 characters. |
| `description` | Details, up to 20,000 characters. |
| `leadId` | The lead the ticket is about. |
| `waConversationId` | A WhatsApp conversation, instead of `leadId`. |
| `type` | `support` (the default) or `sales_followup`. |
| `priority` | `low`, `normal`, `high` or `urgent`. Default: the category's priority, else `normal`. |
| `categoryId` | A category ID from [List categories](#categories-and-teams). |
| `tags` | Up to 20 tags. |
| `assignedToUserId` | Assign one team member (user ID). |
| `assignedUserIds` | Assign several team members (up to 50). Wins over `assignedToUserId`. |
| `sourceCallId` | The call the ticket came from. |
| `dueAt` | Resolution due time (ISO 8601). |

The category and the source decide the ticket's team. The team's rules may then assign it automatically. Send an `Idempotency-Key` header so a retry does not create a second ticket ([Idempotency](/idempotency)).

<Tabs groupId="language" persist items={["cURL","Node.js","Python"]}>
<Tab value="cURL">
```bash
curl -X POST https://api.callmitra.ai/api/v1/tickets/ \
  -H "X-API-Key: $CALLMITRA_API_KEY" \
  -H "Idempotency-Key: crm-case-88213" \
  -H "Content-Type: application/json" \
  -d '{
    "leadId": "5e6f7a8b-0000-4000-8000-000000000002",
    "subject": "Refund not received",
    "description": "Order #1042, refund started on 10 Jan.",
    "priority": "high",
    "tags": ["refund"]
  }'
```
</Tab>

<Tab value="Node.js">
```js
const res = await fetch('https://api.callmitra.ai/api/v1/tickets/', {
  method: 'POST',
  headers: {
    'X-API-Key': process.env.CALLMITRA_API_KEY,
    'Idempotency-Key': 'crm-case-88213',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    leadId: '5e6f7a8b-0000-4000-8000-000000000002',
    subject: 'Refund not received',
    description: 'Order #1042, refund started on 10 Jan.',
    priority: 'high',
    tags: ['refund'],
  }),
});
const { ticket } = await res.json();
```
</Tab>

<Tab value="Python">
```python
res = requests.post(
    "https://api.callmitra.ai/api/v1/tickets/",
    headers={
        "X-API-Key": os.environ["CALLMITRA_API_KEY"],
        "Idempotency-Key": "crm-case-88213",
    },
    json={
        "leadId": "5e6f7a8b-0000-4000-8000-000000000002",
        "subject": "Refund not received",
        "description": "Order #1042, refund started on 10 Jan.",
        "priority": "high",
        "tags": ["refund"],
    },
    timeout=30,
)
ticket = res.json()["ticket"]
```
</Tab>
</Tabs>

The response is `{"success": true, "ticket": {...}}`, the same as [Get a ticket](/api-reference/tickets/getTicket).

## Get a ticket [#get-a-ticket]

[`GET /api/v1/tickets/{ticket_id}`](/api-reference/tickets/getTicket) returns the ticket with its latest `activities`, oldest first. When `hasOlderActivities` is `true`, pass `activitiesCursor` as `before` to [`GET /api/v1/tickets/{ticket_id}/activities`](/api-reference/tickets/listTicketActivities) to read older ones (`limit` default 50, up to 200). Each page returns the next `activitiesCursor`; stop when `hasOlderActivities` is `false`.

Each activity has `id`, `ticketId`, `activityType`, `actorUserId` (`null` for the customer or the system), `actorName`, `createdAt` and `payload`. Common `activityType` values are `created`, `comment` (a note, its text in `payload.note`), `reply`, `status_change` and `assignment`.

## Update a ticket [#update-a-ticket]

[`PATCH /api/v1/tickets/{ticket_id}`](/api-reference/tickets/updateTicket) changes only the fields you send:

| Field | Description |
| --- | --- |
| `subject`, `description` | Text fields. |
| `status` | `open`, `in_progress`, `waiting_on_customer`, `resolved` or `closed`. |
| `priority` | `low`, `normal`, `high` or `urgent`. |
| `type` | `support` or `sales_followup`. |
| `dueAt` | Resolution due time (ISO 8601). |
| `categoryId` | Category ID. `null` clears it. |
| `teamId` | Team ID. `null` takes the ticket out of its team. |
| `tags` | Replaces all tags (up to 20). |
| `version` | The `version` you last read. If the ticket changed since, the request fails with `409` [`ticket_version_conflict`](/errors/ticket_version_conflict). Leave it out to skip the check. |

Assignees can be set when you create a ticket. The update endpoint does not change them.

```bash
curl -X PATCH https://api.callmitra.ai/api/v1/tickets/a1b2c3d4-0000-4000-8000-000000000001 \
  -H "X-API-Key: $CALLMITRA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "status": "resolved", "version": 3 }'
```

The response holds `ticket` (the ticket after the change), `changed` (the fields that changed) and `activities` (only the activities this request added).

Who may change what:

- The key acts as the user who created it. If that user is an agent, it can change only tickets assigned to it or unassigned ones. Others fail with `403` [`ticket_edit_forbidden`](/errors/ticket_edit_forbidden).
- Reopening a `closed` ticket needs a manager's key. Otherwise it fails with `403` [`ticket_reopen_forbidden`](/errors/ticket_reopen_forbidden).
- A merged ticket is read-only: changes fail with `409` [`ticket_merged`](/errors/ticket_merged). Update the ticket it was merged into.

If your workspace set up ticket updates in the console (**Tickets → Settings**), a status change can also send the customer a WhatsApp update.

## Notes and replies [#notes-and-replies]

There are two ways to write on a ticket:

| | Note | Reply |
| --- | --- | --- |
| Endpoint | [`POST .../activities`](/api-reference/tickets/addTicketNote) | [`POST .../replies`](/api-reference/tickets/replyToTicket) |
| Who sees it | Your team only | The customer, on WhatsApp |
| `activityType` | `comment` | `reply` |
| Retry safety | `Idempotency-Key` header | `clientId` in the body |

### Add a note [#add-a-note]

Send `note` (up to 8000 characters). You can also send `status` to move the ticket in the same request, and `version` for the conflict check.

```bash
curl -X POST https://api.callmitra.ai/api/v1/tickets/a1b2c3d4-0000-4000-8000-000000000001/activities \
  -H "X-API-Key: $CALLMITRA_API_KEY" \
  -H "Idempotency-Key: crm-note-5521" \
  -H "Content-Type: application/json" \
  -d '{ "note": "Finance confirmed the refund on 14 Jan.", "status": "waiting_on_customer" }'
```

An empty note fails with `422` [`parameter_invalid`](/errors/parameter_invalid).

### Reply to the customer [#reply-to-the-customer]

A reply goes to the ticket's customer on WhatsApp. It is sent from the number of the ticket's WhatsApp chat, or else from the ticket-updates number chosen in **Tickets → Settings**. Replies are off until a manager turns them on there.

| Field | Description |
| --- | --- |
| `clientId` | Required. Your unique ID for this reply, 8–64 characters. A retry with the same `clientId` returns the first reply, with `replayed: true`, and never sends twice. |
| `text` | Reply text, up to 4096 characters. Only within 24 hours of the customer's last message. |
| `templateEvent` | Outside the window: the ticket event whose approved template to send, for example `waiting_on_customer`. Events are `created`, `in_progress`, `waiting_on_customer`, `resolved`, `resolved_rating` and `closed`; the template must be set up for that event in **Tickets → Settings**. Cannot be combined with `text`. |
| `version` | The ticket `version` you last read (optional). |

<Tabs groupId="language" persist items={["cURL","Node.js","Python"]}>
<Tab value="cURL">
```bash
curl -X POST https://api.callmitra.ai/api/v1/tickets/a1b2c3d4-0000-4000-8000-000000000001/replies \
  -H "X-API-Key: $CALLMITRA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "clientId": "crm-reply-5522", "text": "Your refund is on its way." }'
```
</Tab>

<Tab value="Node.js">
```js
const res = await fetch(
  `https://api.callmitra.ai/api/v1/tickets/${ticketId}/replies`,
  {
    method: 'POST',
    headers: {
      'X-API-Key': process.env.CALLMITRA_API_KEY,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ clientId: 'crm-reply-5522', text: 'Your refund is on its way.' }),
  },
);
```
</Tab>

<Tab value="Python">
```python
res = requests.post(
    f"https://api.callmitra.ai/api/v1/tickets/{ticket_id}/replies",
    headers={"X-API-Key": os.environ["CALLMITRA_API_KEY"]},
    json={"clientId": "crm-reply-5522", "text": "Your refund is on its way."},
    timeout=30,
)
```
</Tab>
</Tabs>

The reply is queued for sending and recorded on the ticket right away. When it cannot be sent, nothing is sent and the request fails with `409` [`ticket_reply_blocked`](/errors/ticket_reply_blocked). `detail.code` says why:

| `detail.code` | Reason |
| --- | --- |
| `replies_off` | Customer replies are turned off in **Tickets → Settings**. |
| `no_number` | No WhatsApp number to reply from. |
| `number_offline` | The WhatsApp number is not connected. |
| `no_phone` | The lead has no valid phone number. |
| `dnc` | The customer is on do-not-contact. |
| `opted_out` | The customer opted out of WhatsApp messages. |
| `window_closed` | The 24-hour window is closed. Send `templateEvent` instead of `text`. |

## Categories and teams [#categories-and-teams]

- [`GET /api/v1/tickets/categories`](/api-reference/tickets/listTicketCategories) lists categories in display order. Each has `id`, `name`, `isActive`, `sortOrder`, `defaultPriority` and `defaultTeamId`. Inactive categories are included unless you send `includeInactive=false`.
- [`GET /api/v1/tickets/teams`](/api-reference/tickets/listTicketTeams) lists teams by name. Each has `id`, `name`, `isDefault`, `members` and `assignmentMode` (`manual`, `round_robin` or `least_busy`).

A new ticket goes to its category's `defaultTeamId`. When neither its category nor its source picks a team, it goes to the team with `isDefault: true`. Categories and teams are managed in the console.

## Webhooks [#webhooks]

Get ticket changes pushed to you instead of polling:

| Event | When |
| --- | --- |
| [`ticket.created`](/api-reference/webhooks/onTicketCreated) | A ticket was opened. |
| [`ticket.updated`](/api-reference/webhooks/onTicketUpdated) | A ticket changed. |
| [`ticket.resolved`](/api-reference/webhooks/onTicketResolved) | A ticket was resolved. |
| [`ticket.reopened`](/api-reference/webhooks/onTicketReopened) | A ticket was opened again. |
| [`ticket.rated`](/api-reference/webhooks/onTicketRated) | A customer rated a ticket. |

See [Webhook events](/webhooks/events) for the payloads.

## Errors [#errors]

| Status | Code | When |
| --- | --- | --- |
| `403` | [`ticket_edit_forbidden`](/errors/ticket_edit_forbidden) | The key's user is an agent and the ticket is assigned to someone else. |
| `403` | [`ticket_reopen_forbidden`](/errors/ticket_reopen_forbidden) | Reopening a closed ticket without a manager's key. |
| `404` | [`resource_not_found`](/errors/resource_not_found) | The ticket, lead or conversation does not exist in your workspace. |
| `409` | [`ticket_version_conflict`](/errors/ticket_version_conflict) | The ticket changed since the `version` you sent. Fetch it again and retry. |
| `409` | [`ticket_merged`](/errors/ticket_merged) | The ticket was merged into another and is read-only. |
| `409` | [`ticket_reply_blocked`](/errors/ticket_reply_blocked) | The reply cannot be sent; see `detail.code`. |
| `409` | [`ticket_attachment_unavailable`](/errors/ticket_attachment_unavailable) | One of the `attachmentIds` was already used or removed. Attachments are uploaded in the console; API integrations normally leave `attachmentIds` out. |
| `409` | [`idempotency_key_reused`](/errors/idempotency_key_reused) | Same `Idempotency-Key`, different body. |
| `422` | [`parameter_invalid`](/errors/parameter_invalid) | A field is missing or invalid. |

Every error uses the standard [error envelope](/errors).