# Send a template by id

POST /v1/messages. Sends an approved WhatsApp template by its id.

`POST https://api.chatwise.so/v1/messages`

Sends an approved WhatsApp template by its id. The answer means WhatsApp accepted the message, not that it was delivered.

This route only sends WhatsApp templates. With another `channel`, or without `templateId`, it answers 201 and sends nothing.

Sending twice sends two messages. After a timeout or a 500 the message may have been sent, so check before you retry.

The API key needs the `messages:send` scope. See [authentication and scopes](https://chatwise.so/docs/authentication.md).

## Example

**curl**:

```bash
curl -X POST 'https://api.chatwise.so/v1/messages' \
  -H "Authorization: Bearer $CHATWISE_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
  "to": "12025550147",
  "channel": "WHATSAPP",
  "templateId": "123456789012345",
  "templateParams": [
    {
      "parameter_name": "order_number",
      "text": "A-1042"
    }
  ]
}'
```

**Node.js**:

```js
const response = await fetch("https://api.chatwise.so/v1/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CHATWISE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "12025550147",
    "channel": "WHATSAPP",
    "templateId": "123456789012345",
    "templateParams": [
      {
        "parameter_name": "order_number",
        "text": "A-1042"
      }
    ]
  }),
});
const body = await response.json();
if (!response.ok) throw new Error(`${response.status}: ${body.message}`);
console.log(body.data);
```

**Python**:

```python
import json
import os
import urllib.request

request = urllib.request.Request(
    "https://api.chatwise.so/v1/messages",
    method="POST",
    headers={
        "Authorization": f"Bearer {os.environ['CHATWISE_API_KEY']}",
        "Content-Type": "application/json",
    },
    data=json.dumps({
      "to": "12025550147",
      "channel": "WHATSAPP",
      "templateId": "123456789012345",
      "templateParams": [
        {
          "parameter_name": "order_number",
          "text": "A-1042"
        }
      ]
    }).encode(),
)
with urllib.request.urlopen(request) as response:
    print(json.load(response)["data"])
```

## Body

JSON. Unknown fields are refused with a 400.

| Field | Type | Description |
| --- | --- | --- |
| `to` | string | **Required.** The customer's phone number with its country code. |
| `templateId` | string | The template's `id`. Needed to send. |
| `templateParams` | array of objects | Values for the body's variables. A template with a variable or media in its header, a dynamic URL button or a copy code button takes `templateComponents` instead. Keys other than `parameter_name` and `text` are ignored. |
| `templateParams[].parameter_name` | string | **Required.** The variable's name, its number (`1`, `2`, …), or `otp` for the code of an authentication template. |
| `templateParams[].text` | string | **Required.** The variable's value. |
| `templateLanguage` | string | The language code to send it in, such as `en_US`. Without it, the template's own. Spaces around it are ignored. |
| `templateComponents` | array of objects | Values for the header, body and buttons, up to 12 components. Used instead of `templateParams`, except for authentication templates. At most one header and one body, and no two buttons with the same `subType` and `index`. |
| `templateComponents[].type` | string | **Required.** `header`, `body` or `button`. |
| `templateComponents[].parameters` | array of objects | **Required.** The component's values: one for a header or a button, one or more for a body. |
| `templateComponents[].parameters[].type` | string | **Required.** The kind of value. One of `text`, `image`, `video`, `document`, `currency`, `date_time`, `payload`, `coupon_code`. |
| `templateComponents[].parameters[].text` | string | **Required when `type` is `text`.** The text. |
| `templateComponents[].parameters[].parameterName` | string | Only when `type` is `text`, `currency`, or `date_time`. The variable's name, for templates with named variables. Spaces around it are ignored. Can't be blank. At most 64 characters. |
| `templateComponents[].parameters[].image` | object | **Required when `type` is `image` and `templateComponents[].type` is `header`.** An image, by `link` or Meta media `id`. Needs `link` or `id`. |
| `templateComponents[].parameters[].image.link` | string | The image's public URL. |
| `templateComponents[].parameters[].image.id` | string | The image's Meta media id. Spaces around it are ignored. Can't be blank. |
| `templateComponents[].parameters[].video` | object | **Required when `type` is `video` and `templateComponents[].type` is `header`.** A video, by `link` or Meta media `id`. Needs `link` or `id`. |
| `templateComponents[].parameters[].video.link` | string | The video's public URL. |
| `templateComponents[].parameters[].video.id` | string | The video's Meta media id. Spaces around it are ignored. Can't be blank. |
| `templateComponents[].parameters[].document` | object | **Required when `type` is `document` and `templateComponents[].type` is `header`.** A document, by `link` or Meta media `id`. Needs `link` or `id`. |
| `templateComponents[].parameters[].document.link` | string | The document's public URL. |
| `templateComponents[].parameters[].document.id` | string | The document's Meta media id. Spaces around it are ignored. Can't be blank. |
| `templateComponents[].parameters[].document.filename` | string | The file name the customer sees. At most 240 characters. |
| `templateComponents[].parameters[].currency` | object | **Required when `type` is `currency` and `templateComponents[].type` is `body`.** An amount of money. |
| `templateComponents[].parameters[].currency.fallbackValue` | string | **Required.** The amount as text, such as `$12.50`. |
| `templateComponents[].parameters[].currency.code` | string | **Required.** The ISO 4217 currency code. Spaces around it are ignored. |
| `templateComponents[].parameters[].currency.amount1000` | integer | **Required.** The amount times 1000. |
| `templateComponents[].parameters[].dateTime` | object | **Required when `type` is `date_time` and `templateComponents[].type` is `body`.** A date or time. |
| `templateComponents[].parameters[].dateTime.fallbackValue` | string | **Required.** The date or time as text. |
| `templateComponents[].subType` | string | **Required when `type` is `button`.** The button's kind: `url` takes a `text` parameter, `quick_reply` a `payload`, `copy_code` a `coupon_code`. |
| `templateComponents[].index` | integer | **Required when `type` is `button`.** The button's position, from 0. |
| `templateComponents[].parameters[].payload` | string | **Required when `type` is `payload` and `templateComponents[].type` is `button`.** What a quick reply button sends back. At most 256 characters. |
| `templateComponents[].parameters[].couponCode` | string | **Required when `type` is `coupon_code` and `templateComponents[].type` is `button`.** The code a copy code button copies. At most 15 characters. |
| `channel` | string | **Required.** Use `WHATSAPP`. One of `WHATSAPP`, `INSTAGRAM`. |
| `from` | string | The connected WhatsApp number to send from, digits only. Without it: the number on the template's WhatsApp Business Account the customer last wrote to, else the oldest number there. |

## Response

**201.** WhatsApp accepted the message.

```json
{
  "data": {
    "message": "Message accepted",
    "from": "+1 202-555-0199"
  }
}
```

| Field | Type | Description |
| --- | --- | --- |
| `data.message` | string | A confirmation. |
| `data.from` | string | The WhatsApp number it was sent from. Absent when nothing was sent. |

## Errors

| Status | Message | What it means |
| --- | --- | --- |
| 400 | Expected property name or '}' in JSON at position 1 (line 1 column 2) | The request body isn't valid JSON. The message says where. |
| 400 | Validation failed | A parameter or body field is missing, unknown or malformed. `errors` lists each one. |
| 400 | Template must be approved to send messages | Meta hasn't approved the template, or paused or rejected it. |
| 400 | This template is on a different WhatsApp Business Account from the number in from | Use a `from` number on the template's WhatsApp Business Account. |
| 400 | An OTP code is required for authentication templates | Send the code as `templateParams` with `parameter_name` set to `otp`. |
| 400 | Numbered template variables must start at 1 and include each position once | Number the variables from `1`, each once. |
| 400 | That WhatsApp number is not connected to this workspace | Use one of the workspace's connected numbers, digits only. `data.accounts` lists them. |
| 401 | A valid Bearer API key is required | The `Authorization` header is missing or isn't `Bearer <API key>`. |
| 401 | Invalid or revoked API key | The key doesn't exist, was revoked, or has expired. |
| 401 | Invalid API key | Chatwise couldn't check the key. Try again. |
| 402 | `ADMIN_SERVICES_BLOCKED`: Chatwise services have been paused for this workspace by an administrator. Contact support to restore service. | Sending is paused for the workspace. Contact support. |
| 403 | API key does not have the required scope: messages:send | The key lacks the route's scope. Create a key that has it. |
| 403 | `WHATSAPP_REAUTH_REQUIRED`: WhatsApp authorization has expired. Ask an administrator to reconnect WhatsApp in Settings. | Meta no longer accepts Chatwise's access to the number. Reconnect it in the dashboard. `reason` is `expired`, `revoked` or `missing`, and the message depends on it. |
| 404 | Template not found | No such template in the key's workspace. Sending by name finds approved templates only. |
| 404 | Whatsapp account not found | The workspace has no connected WhatsApp number. |
| 404 | No connected WhatsApp number on this template's business account | Connect a number on the template's WhatsApp Business Account. |
| 413 | request entity too large | The request body is larger than 100 KB. |
| 429 | API key rate limit exceeded | Wait the number of seconds in the `Retry-After` header. |
| 500 | Internal server error: WhatsApp send failed: 400 {"error":{"message":"(#132000) Number of parameters does not match the expected number of params"}} | WhatsApp didn't accept the message. The number is Meta's HTTP status, and after it comes Meta's answer when that was JSON. A 429 can be tried later, after a 5xx check first, and for other statuses fix what the answer names. |
| 500 | Internal server error | Something failed in Chatwise. The message may have been sent, even if it isn't in the conversation. Quote `errorId` to support. |

The body of an error is described in [errors](https://chatwise.so/docs/errors.md).
