# Sinch Node.js SDK for Conversation The Sinch Node.js SDK allows you to quickly interact with the from inside your Node.js applications. When using the Node.js SDK, the code representing requests and queries sent to and responses received from the are structured similarly to those that are sent and received using the . The fastest way to get started with the SDK is to check out our [getting started](/docs/conversation/getting-started/node-sdk/send-message) guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK. ## Syntax Note: This guide describes the syntactical structure of the Node.js SDK for the Conversation API, including any differences that may exist between the API itself and the SDK. For a full reference on Conversation API calls and responses, see the [Conversation REST API Reference](/docs/conversation/api-reference/). The code sample below is an example of how to use the Node.js SDK to send a text message on the SMS channel of a Conversation API app. We've also provided an example that accomplishes the same task using the REST API (note that this REST API example would be included in an `mjs` instead of a `js` file, and it uses Basic Authentication instead of OAuth2). SDK send-message.js const { SinchClient } = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ projectId: "YOUR_project_id", keyId: "YOUR_access_key", keySecret: "YOUR_access_secret" }); async function run(){ const response = await sinchClient.conversation.messages.send({ sendMessageRequestBody: { app_id: "YOUR_app_ID", recipient: { identified_by: { channel_identities: [ { channel: "SMS", identity: "RECIPIENT_number" } ] } }, message: { text_message: { text: "This is a test message using the Sinch Node.js SDK" } }, channel_properties: { SMS_SENDER: "YOUR_sms_sender" } } }); console.log(JSON.stringify(response)); } run(); REST API ```Javascript // Find your App ID at dashboard.sinch.com/convapi/apps // Find your Project ID at dashboard.sinch.com/settings/project-management // Get your Access Key and Access Secret at dashboard.sinch.com/settings/access-keys const APP_ID = ''; const ACCESS_KEY = ''; const ACCESS_SECRET = ''; const PROJECT_ID = ''; const CHANNEL = ''; const IDENTITY = ''; import fetch from 'node-fetch'; async function run() { const resp = await fetch( 'https://us.conversation.api.sinch.com/v1/projects/' + PROJECT_ID + '/messages:send', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Basic ' + Buffer.from(ACCESS_KEY + ':' + ACCESS_SECRET).toString('base64') }, body: JSON.stringify({ app_id: APP_ID, recipient: { identified_by: { channel_identities: [ { channel: CHANNEL, identity: IDENTITY } ] } }, message: { text_message: { text: 'Text message from Sinch Conversation API.' } } }) } ); const data = await resp.json(); console.log(data); } run(); ``` This example highlights the following required to successfully make a Conversation API call using the Sinch Node.js SDK: - [Client initialization](#client) - [Conversation domain access](#conversation-domain) - [Endpoint usage](#endpoint-categories) - [Field population](#request-and-query-parameters) ## Client When using the Sinch Node.js SDK, you initialize communication with the Sinch backend by initializing the Node.js SDK's main client class. This client allows you to access the functionality of the Sinch Node.js SDK. ### Initialization Before initializing a client using this SDK, you'll need three pieces of information: - Your Project ID - An access key ID - An access key Secret These values can be found on the [Access Keys](https://dashboard.sinch.com/settings/access-keys) page of the Sinch Build Dashboard. You can also [create new access key IDs and Secrets](https://community.sinch.com/t5/Conversation-API/How-to-get-your-access-key-for-Conversation-API/ta-p/8120), if required. Note If you have trouble accessing the above link, ensure that you have gained access to the [Conversation API](https://dashboard.sinch.com/convapi/overview) by accepting the corresponding terms and conditions. To start using the SDK, you need to initialize the main client class with your credentials from your Sinch [dashboard](https://dashboard.sinch.com/dashboard). ```javascript const {SinchClient} = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ projectId: "YOUR_project_id", keyId: "YOUR_access_key", keySecret: "YOUR_access_secret" }); ``` Note For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example: **`.env` File** ```shell PROJECTID="YOUR_project_id" ACCESSKEY="YOUR_access_key" ACCESSSECRET="YOUR_access_secret" ``` **`app.js` File** ```javascript const {SinchClient} = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ projectId: process.env.PROJECTID, keyId: process.env.ACCESSKEY, keySecret: process.env.ACCESSSECRET }); ``` Note If you are using the Node.js SDK for multiple products that use different sets of authentication credentials, you can include all of the relevant credentials in the same configuration object, as in the following example: ```javascript const {SinchClient} = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ projectId: "YOUR_project_id", keyId: "YOUR_access_key", keySecret: "YOUR_access_secret", applicationKey: "YOUR_application_key", applicationSecret: "YOUR_application_secret" }); ``` ## Conversation domain The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, `sinch.conversation.[endpoint_category].[method()]`. ## Endpoint categories In the Sinch Node.js SDK, Conversation API endpoints are accessible through the client (either a general client or a Conversation-specific client). The naming convention of the endpoint's representation in the SDK matches the API: - `messages` - `app` - `contact` - `events` - `transcoding` - `capability` - `templatesV1` - `templatesV2` - `webhooks` - `conversation` For example: ```Javascript const response = await sinchClient.conversation.messages.send({ sendMessageRequestBody: { app_id: "YOUR_app_ID", recipient: { identified_by: { channel_identities: [ { channel: "SMS", identity: "RECIPIENT_number" } ] } }, message: { text_message: { text: "This is a test message using the Sinch Node.js SDK" } }, channel_properties: { SMS_SENDER: "YOUR_sms_sender" } } }); ``` ### `messages` endpoint category The `messages` category of the Node.js SDK corresponds to the [messages](/docs/conversation/api-reference/conversation/messages/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [Send a message](/docs/conversation/api-reference/conversation/messages/messages_sendmessage) | `send`, or you could use any of the following message-specific methods: | | | `sendCardMessage` | | | `sendCarouselMessage` | | | `sendChoiceMessage` | | | `sendContactInfoMessage` | | | `sendListMessage` | | | `sendLocationMessage` | | | `sendMediaMessage` | | | `sendTemplateMessage` | | | `sendTextMessage` | | [Get a message](/docs/conversation/api-reference/conversation/messages/messages_getmessage) | `get` | | [Delete a message](/docs/conversation/api-reference/conversation/messages/messages_deletemessage) | `delete` | | [List messages](/docs/conversation/api-reference/conversation/messages/messages_listmessages) | `list` | | [Update a message's metadata](/docs/conversation/api-reference/conversation/messages/messages_updatemessagemetadata) | `update` | ### `app` endpoint category The `app` category of the Node.js SDK corresponds to the [apps](/docs/conversation/api-reference/conversation/app/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [List all apps for a given project](/docs/conversation/api-reference/conversation/app/app_listapps) | `list` | | [Create an app](/docs/conversation/api-reference/conversation/app/app_createapp) | `create` | | [Get an app](/docs/conversation/api-reference/conversation/app/app_getapp) | `get` | | [Delete an app](/docs/conversation/api-reference/conversation/app/app_deleteapp) | `delete` | | [Update an app](/docs/conversation/api-reference/conversation/app/app_updateapp) | `update` | ### `contact` endpoint category The `contact` category of the Node.js SDK corresponds to the [contacts](/docs/conversation/api-reference/conversation/contact/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [List contacts](/docs/conversation/api-reference/conversation/contact/contact_listcontacts) | `list` | | [Create a contact](/docs/conversation/api-reference/conversation/contact/contact_createcontact) | `create` | | [Get a contact](/docs/conversation/api-reference/conversation/contact/contact_getcontact) | `get` | | [Delete a contact](/docs/conversation/api-reference/conversation/contact/contact_deletecontact) | `delete` | | [Update a contact](/docs/conversation/api-reference/conversation/contact/contact_updatecontact) | `update` | | [Merge two contacts](/docs/conversation/api-reference/conversation/contact/contact_mergecontact) | `mergeContact` | | [Get channel profile](/docs/conversation/api-reference/conversation/contact/contact_getchannelprofile) | `getChannelProfile` | ### `conversation` endpoint category The `conversation` category of the Node.js SDK corresponds to the [conversations](/docs/conversation/api-reference/conversation/conversation/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [List conversations](/docs/conversation/api-reference/conversation/conversation/conversation_listconversations) | `list` | | [Create a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_createconversation) | `create` | | [Get a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_getconversation) | `get` | | [Delete a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_deleteconversation) | `delete` | | [Update a conversation](/docs/conversation/api-reference/conversation/conversation/conversation_updateconversation) | `update` | | [Stop conversation](/docs/conversation/api-reference/conversation/conversation/conversation_stopactiveconversation) | `stopActive` | | [Inject a message](/docs/conversation/api-reference/conversation/conversation/conversation_injectmessage) | `injectMessage` | | [Inject an event](/docs/conversation/api-reference/conversation/conversation/events_injectevent) | `injectEvent` | | [List recent conversations](/docs/conversation/api-reference/conversation/conversation/conversation_listrecentconversations) | `listRecent` | ### `events` endpoint category The `events` category of the Node.js SDK corresponds to the [events](/docs/conversation/api-reference/conversation/events/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [Send an event](/docs/conversation/api-reference/conversation/events/events_sendevent) | `send`, or you could use any of the following message-specific methods: `sendComposingEvent`, `sendComposingEndEvent`, `sendCommentReplyEvent`, `sendAgentJoinedEvent`, `sendAgentLeftEvent`, or `sendGenericEvent` | | [Get an event](/docs/conversation/api-reference/conversation/events/events_getevent) | `get` | | [Delete an event](/docs/conversation/api-reference/conversation/events/events_deleteevents) | `delete` | | [List events](/docs/conversation/api-reference/conversation/events/events_listevents) | `list` | ### `transcoding` endpoint category The `transcoding` category of the Node.js SDK corresponds to the [messages:transcode](/docs/conversation/api-reference/conversation/transcoding/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [Transcode a message](/docs/conversation/api-reference/conversation/transcoding/transcoding_transcodemessage) | `transcodeMessage` | ### `capability` endpoint category The `capability` category of the Node.js SDK corresponds to the [capability](/docs/conversation/api-reference/conversation/capability/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [Capability lookup](/docs/conversation/api-reference/conversation/capability/capability_querycapability) | `lookup` | ### `webhooks` endpoint category The `webhooks` category of the Node.js SDK corresponds to the [webhooks](/docs/conversation/api-reference/conversation/webhooks/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [List webhooks](/docs/conversation/api-reference/conversation/webhooks/webhooks_listwebhooks) | `list` | | [Create a new webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_createwebhook) | `create` | | [Get a webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_getwebhook) | `get` | | [Update an existing webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_updatewebhook) | `update` | | [Delete an existing webhook](/docs/conversation/api-reference/conversation/webhooks/webhooks_deletewebhook) | `delete` | ### `templatesV1` endpoint category The `templatesV1` category of the Node.js SDK corresponds to the [Templates](/docs/conversation/api-reference/template/templates-v1/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [List all templates belonging to a project ID](/docs/conversation/api-reference/template/templates-v1/templates_listtemplates) | `list` | | [Creates a template](/docs/conversation/api-reference/template/templates-v1/templates_createtemplate) | `create` | | [Updates a template](/docs/conversation/api-reference/template/templates-v1/templates_updatetemplate) | `update` | | [Get a template](/docs/conversation/api-reference/template/templates-v1/templates_gettemplate) | `get` | | [Delete a template](/docs/conversation/api-reference/template/templates-v1/templates_deletetemplate) | `delete` | ### `templatesV2` endpoint category The `templatesV2` category of the Node.js SDK corresponds to the [Templates-V2](/docs/conversation/api-reference/template/templates-v2/) endpoint. The mapping between the API operations and corresponding methods are described below: | API operation | SDK method | | --- | --- | | [List all templates belonging to a project ID](/docs/conversation/api-reference/template/templates-v2/templates_v2_listtemplates) | `list` | | [Creates a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_createtemplate) | `create` | | [Lists translations for a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_deletetemplate) | `listTranslations` | | [Updates a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_updatetemplate) | `update` | | [Get a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_gettemplate) | `get` | | [Delete a template](/docs/conversation/api-reference/template/templates-v2/templates_v2_deletetemplate) | `delete` | ## Request and query parameters Requests and queries made using the Node.js SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method. SDK ```Javascript app_id: "{APP_ID}" ``` REST API ```JSON "app_id": "{APP_ID}" ``` Note that the fields have the same name. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding method. For example, consider this example in which the `get` method of the `message` class is invoked: SDK ```Javascript const response = await sinchClient.conversation.messages.get({ message_id:"YOUR_message_id" messages_source:"CONVERSATION_SOURCE" }); ``` REST API ```JSON url = "https://us.conversation.api.sinch.com/v1/projects/" + project_id + "/messages/" + YOUR_message_id payload = { "messages_source": "CONVERSATION_SOURCE" } ``` When using the Conversation API, `message_id` would be included as a path parameter, and `messages_source` would be included as a query parameter in the JSON payload. With the Node.js SDK, both parameters are included as arguments in the `get` method. ## Responses Response fields match the API responses. They are delivered as JavaScript objects. ### Pagination objects For operations that return multiple pages of objects, such as list operations, the API response that would normally be an array is instead wrapped inside an `ApiPromiseList` object. This object can take two forms, depending on how you have made the call: - [`PageResult`](#pageresult) - [`AsyncIteratorIterable`](#asynciteratoriterable) #### `PageResult` If you are using a traditional `await` in front of the method, the `ApiPromiseList` will take the form of a `PageResult`, as demonstrated by the following example: Numbers ```javascript const requestData: ListActiveNumbersRequestData = { regionCode: 'US', type: 'LOCAL', pageSize: 2, }; // This call will return the data of the current page wrapped in a PageResult // We can then loop on the response while it has more pages let response: PageResult = await sinchClient.numbers.activeNumber.list(requestData); // The ActiveNumber are in the `data` property let activeNumbers: ActiveNumber[] = response.data; console.log(activeNumbers); // prints the content of a page ``` Conversation ```javascript const requestData: ListMessagesRequestData = { app_id: "YOUR_Conversation_app_ID, channel: 'MESSENGER', }; // This call will return the data of the current page wrapped in a PageResult // We can then loop on the response while it has more pages let response: PageResult = await sinchClient.conversation.messages.list(requestData); // The ConversationMessage are in the `data` property let messages: ConversationMessage[] = response.data; console.log(messages); // prints the content of a page ``` The array is contained in the `data` field and the object contains a `hasNextPage` boolean as well as a `nextPage()` function which can be used to iterate through the results. Numbers ```javascript // Loop on all the pages to get all the active numbers let reachedEndOfPages = false; while (!reachedEndOfPages) { if (response.hasNextPage) { response = await response.nextPage(); activeNumbers = response.data; console.log(activeNumbers); // prints the content of a page } else { reachedEndOfPages = true; } } ``` Conversation ```javascript // Loop on all the pages to get all the messages let reachedEndOfPages = false; while (!reachedEndOfPages) { if (response.hasNextPage) { response = await response.nextPage(); messages = response.data; console.log(messages); // prints the content of a page } else { reachedEndOfPages = true; } } ``` Each call to the Sinch servers is visible in the code in the `while` loop. #### `AsyncIteratorIterable` If you using an iterator (`for await (... of ...)`), the `ApiPromiseList` will take the form of a `AsyncIteratorIterable` object which can be used to iterate through the results, as demonstrated by the following example: Numbers ```javascript const requestData: ListActiveNumbersRequestData = { regionCode: 'US', type: 'LOCAL', pageSize: 2, }; for await (const activeNumber of sinchClient.numbers.activeNumber.list(requestData)) { console.log(activeNumber); // prints a single ActiveNumber } ``` Conversation ```javascript const requestData: ListMessagesRequestData = { app_id: "YOUR_Conversation_app_ID, channel: 'MESSENGER', }; for await (const message of sinchClient.conversation.messages.list(requestData)) { console.log(message); // prints a single ConversationMessage } ``` With the iterator, the code is more concise but you have less control over the number of calls made to the API; the iterator will continue to make calls to the API to fetch the next page until the final page is returned.