> ## Documentation Index
> Fetch the complete documentation index at: https://docs.routa.chat/llms.txt
> Use this file to discover all available pages before exploring further.

# Templates

> Create templates with header, footer and buttons, upload the file of a media header and follow approval with the SDK.

`routa.templates` creates templates, uploads the file of a media header, and retrieves and lists templates. For the lifecycle, the statuses and the WhatsApp rules, see [Templates](https://docs.routa.chat/en/concepts/templates.md).

| Method | Endpoint | Scope |
| - | - | - |
| `submit(params)` | [`POST /v1/templates`](https://docs.routa.chat/en/api-reference/endpoint/templates/create) | `templates:write` |
| `uploadMedia({ file, contentType })` | [`POST /v1/templates/media`](https://docs.routa.chat/en/api-reference/endpoint/templates/upload-media) | `templates:write` |
| `retrieve(id)` | [`GET /v1/templates/{id}`](https://docs.routa.chat/en/api-reference/endpoint/templates/retrieve) | `templates:read` |
| `list(params)` | [`GET /v1/templates`](https://docs.routa.chat/en/api-reference/endpoint/templates/list) | `templates:read` |

## Create a template

A body-only template needs `channel`, `name`, `language`, `category` and `bodyText`. When the body has a variable, it also needs `variableExamples`.

```ts theme={null}
const template = await routa.templates.submit({
  channel: 'chan_...',
  name: 'order_confirmation',
  language: 'en_US',
  category: 'utility',
  bodyText: 'Hi {{1}}! Your order {{2}} is confirmed.',
  variableExamples: ['Ana', '1234'], // {{1}} and then {{2}}
})

console.log(template.id, template.status) // "tmpl_...", "submitted"
```

`language` is the code WhatsApp uses, such as `pt_BR`, `en_US` or `en`. The region is joined with an underscore: `en_US`, not `en-US`.

The response carries `status: 'submitted'`, **not** `approved`. Routa records the template first and sends it to the provider afterwards, and the provider decides in its own time. Follow the result through the `template.*` events, with [webhooks](https://docs.routa.chat/en/sdk/webhooks.md) or `routa.events.list()`.

## Variables and examples

The API requires an example for **every** variable. These fields exist from version 0.5.0.

| Where the variable is | Field | What goes in it |
| - | - | - |
| Body | `variableExamples` | One item per variable, the first one for `{{1}}`: the order of the numbers counts, not the order in the text. |
| Text header | `components.header.example` | The example of the header `{{1}}`. |
| URL button | `example` on the button | **Only the value** that replaces `{{1}}`, not the whole URL. |

An example cannot be empty or blank, and whatever has no variable takes no example. A media header, a `quick_reply` button and a `phone_number` button have no variable, so the types do not accept `example` on them. See [Variable examples](https://docs.routa.chat/en/concepts/templates.md#variable-examples).

> [!WARNING]
>
> Use made-up values. Examples are stored with the template, returned by the API and sent in `template.*` events and webhooks, so do not put real personal data or a real token in them.

> [!NOTE]
>
> A version earlier than 0.5.0 does not have these fields and drops a value passed anyway. That is why the API refuses the `submit()` of a template with a variable, with `422 template_variables_invalid`. [Upgrade the SDK](https://docs.routa.chat/en/sdk/upgrading.md).

## Components

`components` accepts a header, a footer and up to 10 buttons. Leave `components` out for a body-only template.

```ts theme={null}
const template = await routa.templates.submit({
  channel: 'chan_...',
  name: 'order_shipped',
  language: 'en_US',
  category: 'utility',
  bodyText: 'Your order {{1}} has shipped.',
  variableExamples: ['1234'],
  components: {
    header: { kind: 'text', text: 'Order on the way' },
    footer: { text: 'Reply STOP to stop receiving these' },
    buttons: [
      {
        kind: 'url',
        text: 'Track order',
        url: 'https://example.com/orders/{{1}}',
        example: '1234', // only the value
      },
      { kind: 'phone_number', text: 'Call us', phoneNumber: '+5581999999999' },
    ],
  },
})
```

Each part is a union on `kind`. That is why a `url` button without `url`, a `media` header without `mediaId` or a `quick_reply` with `example` does not compile.

| Part | Shape |
| - | - |
| Text header | `{ kind: 'text', text, example? }`. `example` when `text` has `{{1}}`. |
| Media header | `{ kind: 'media', mediaId }` |
| Footer | `{ text }` |
| Quick reply button | `{ kind: 'quick_reply', text }` |
| Phone button | `{ kind: 'phone_number', text, phoneNumber }` |
| URL button | `{ kind: 'url', text, url, example? }`. `example` when `url` has `{{1}}`. |

The SDK only checks the **shape**. Lengths, the number of buttons, the URL and phone formats and the WhatsApp rules belong to the API, which responds `422` with the field at fault. See the rules in [Templates](https://docs.routa.chat/en/concepts/templates.md).

## Image, video or document header

Upload the file with `uploadMedia()` and pass the returned `id` as `mediaId`:

```ts theme={null}
import { readFile } from 'node:fs/promises'

const media = await routa.templates.uploadMedia({
  file: await readFile('./header.png'), // a Uint8Array (a Buffer is one) or a Blob
  contentType: 'image/png',
})

const template = await routa.templates.submit({
  channel: 'chan_...',
  name: 'weekly_deals',
  language: 'en_US',
  category: 'marketing',
  bodyText: 'Check out the deals of the week, {{1}}!',
  variableExamples: ['Ana'],
  components: {
    header: { kind: 'media', mediaId: media.id },
  },
})
```

The upload is synchronous: the `TemplateMedia` can be used right away. The API derives the `format` from the `contentType`.

This file is the sample WhatsApp reviews. To send the template, upload the file of the message with [`media.upload()`](https://docs.routa.chat/en/sdk/media) and pass its `id` in `headerParameter.mediaId`. See [Send a template](https://docs.routa.chat/en/sdk/messages.md#send-a-template).

| `contentType` | `format` | Maximum size |
| - | - | - |
| `image/jpeg`, `image/png` | `image` | 5 MiB |
| `video/mp4` | `video` | 16 MiB |
| `application/pdf` | `document` | 100 MiB |

* `contentType` is sent as the `Content-Type` of the request. The SDK does **not** read it from the `type` of a `Blob`.
* The first bytes of the file must match the `contentType`.
* `contentType` is compared exactly: `image/png; charset=binary` is refused.
* Unlike `media.upload()`, there is no `sourceUrl` mode.

### The `TemplateMediaId`

`media.id` is a `TemplateMediaId` (`tmedia_...`), a *branded* type of its own. A `MediaId` from [`media.upload()`](https://docs.routa.chat/en/sdk/media) or a plain `string` does not work as `mediaId`: the compiler refuses it. It is a different kind of file, and only a template header can use it.

On a template you read, `components.header.media_id` is already a `TemplateMediaId`, so you can pass it back as `mediaId`.

## Read a template

```ts theme={null}
import { toTemplateId } from '@routa-chat/sdk'

const template = await routa.templates.retrieve(toTemplateId('tmpl_...'))

console.log(template.bodyText, template.components?.buttons?.length ?? 0)
```

`components` **does not exist** on a body-only template: it is omitted, not an empty object. Guard your reads with `template.components?.`.

| Field | Type | Description |
| - | - | - |
| `bodyText` | `string \| null` | The body, with `{{1}}`, `{{2}}`. It is `null` only on an imported template Routa cannot reproduce (`readOnly`). |
| `variables` | `TemplateVariable[]` | One entry per body variable: `index` and, when there is one, `example`. |
| `components` | `TemplateComponents` | Header, footer and buttons. Absent when there are none. |
| `status` | `TemplateStatus` | `draft`, `submitted`, `pending`, `approved`, `rejected`, `paused`, `disabled` or `failed`. |
| `rejectionReason` | `TemplateRejectionReason \| null` | Only when the status is `rejected`. |
| `failureCode` | `TemplateFailureCode \| null` | Only when the status is `failed`. A closed set of Routa values. |
| `failureDetail` | `string \| null` | The provider's sentence about the refusal, when it gave one. It is text for a person: never compare against it; use `failureCode`. |
| `deletionRequested` | `boolean` | `true` while a deletion requested in the dashboard has not finished. The template cannot be sent in between. |
| `deletionFailureDetail` | `string \| null` | Why the last deletion ended without deleting. |
| `origin` | `'routa' \| 'provider'` | `provider` is a template that already existed on WhatsApp and was imported. |
| `readOnly` | `boolean` | `true` on an imported template Routa cannot reproduce. A message that uses it gets `422 template_not_sendable`. |
| `unsupportedComponents` | `TemplateUnsupportedComponent[]` | Why the template is `readOnly`. Empty on the others. |

The new fields of 0.3.0 are `bodyText`, `components`, `failureCode`, `failureDetail`, `deletionRequested`, `deletionFailureDetail`, `origin`, `readOnly` and `unsupportedComponents`.

From 0.5.0, the examples come back in `variables[].example`, `components.header.example` and `components.buttons[].example`. The key is absent when there is no example, as on an old template. On an imported template, the example is whatever WhatsApp stores, so a button example can be a whole URL.

### Handle the status

```ts theme={null}
switch (template.status) {
  case 'approved':
    // ready to be sent
    break
  case 'rejected':
    console.log(template.rejectionReason)
    break
  case 'failed':
    // Routa could not send the template to the provider.
    console.error(template.failureCode, template.failureDetail)
    break
  default:
    // draft, submitted, pending, paused, disabled
    break
}
```

See the values of `failureCode` and what each one means in [When sending for approval fails](https://docs.routa.chat/en/concepts/templates.md#when-sending-for-approval-fails).

## Errors

The API refuses to create an invalid template with one of these errors. The SDK throws them as `RoutaInvalidRequestError`, with the `param` field when the API gives it.

| Status | `code` | `param` |
| - | - | - |
| `422` | `template_name_invalid` | `name` |
| `422` | `template_components_invalid` | `body_text`, `components.header`, `components.footer` or `components.buttons` |
| `422` | `template_variables_invalid` | `variable_examples`, `variable_examples.<position>`, `components.header.example` or `components.buttons.<position>.example` on an example error. None on the others. |
| `422` | `request_invalid`: a field is missing or has the wrong type | The field, when the API can point at it |
| `422` | `capability_unsupported` (the channel does not send templates) | n/a |
| `422` | `template_media_invalid` (on `uploadMedia()`) | n/a |
| `404` | `template_media_not_found`: the `mediaId` does not exist **in this project** | n/a |
| `404` | `channel_not_found` | n/a |
| `403` | `insufficient_scope`: the key lacks `templates:write` | n/a |

* The `param` of `template_components_invalid` names the **component**, not the item inside it. There is no such thing as `components.buttons.0.url`. The `message` says what is wrong.
* `param` uses the API names (`variable_examples`, not `variableExamples`), with positions starting at 0: `variable_examples.1` is the example of `{{2}}`.
* On `template_variables_invalid`, `error.details?.['reason']` says which case it is. See [the reasons](https://docs.routa.chat/en/errors/error-codes.md#reasons-for-each-code).
* The API reports the first problem it finds, so fixing one can reveal the next.
* The API checks the channel before the media: an unknown channel hides an invalid `mediaId`.
* A file over 100 MiB gets `413 payload_too_large`, as a base `RoutaApiError`. It is not retried.

```ts theme={null}
import { RoutaInvalidRequestError } from '@routa-chat/sdk'

try {
  await routa.templates.submit(params)
} catch (error) {
  if (error instanceof RoutaInvalidRequestError && error.code === 'template_components_invalid') {
    console.error(`Fix ${error.param}: ${error.message}`)
  } else {
    throw error
  }
}
```

## Not idempotent

`POST /v1/templates` and `POST /v1/templates/media` do not read `Idempotency-Key`, so the SDK does not send one. The client still retries a network failure or a `5xx`. If the first attempt was already recorded and only the response was lost, the retry creates a second template with the same name (with another `tmpl_...`), which the provider can refuse as a duplicate. On an upload, it stores the file twice.

> [!WARNING]
>
> Set `maxRetries: 0` on the client if a duplicate matters more to you than resilience to an unstable connection. After an error whose response you did not read, use `templates.list()` before you create again.

## What the SDK does not do

The SDK does not **edit**, **delete** or **sync** templates. Those operations exist only in the dashboard, and the API does not offer them to an API key. A `failed` or `rejected` template can be edited and sent again in the dashboard. Through the SDK, create a new one with `submit()`. When the dashboard edits or deletes a template, you receive `template.updated` or `template.deleted`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.