# Sinch Node.js SDK for SMS 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/sms/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 SMS API, including any differences that may exist between the API itself and the SDK. For a full reference on SMS API calls and responses, see the [SMS REST API Reference](/docs/sms/api-reference/). The code sample below is an example of how to use the Node.js SDK to send an SMS message. We've also provided an example that accomplishes the same task using the REST API. SDK send-message.js // eslint-disable-next-line no-unused-vars import { Sms, SmsService } from '@sinch/sdk-core'; /** @param {SmsService} smsService */ export const execute = async (smsService) => { const from = 'YOUR_sinch_phone_number'; const recipient = 'YOUR_recipient_phone_number'; const body = 'This is a test SMS message using the Sinch Node.js SDK.'; /** @type {Sms.SendSMSRequestData} */ const requestData= { sendSMSRequestBody: { type: 'mt_text', from, to: [recipient], body, }, }; const response = await smsService.batches.send(requestData); console.log(`Response:\n${JSON.stringify(response, null, 2)}`); }; REST API ```javascript const SERVICE_PLAN_ID = 'YOUR_servicePlanId'; const API_TOKEN = 'YOUR_API_token'; const SINCH_NUMBER = 'YOUR_Sinch_virtual_number'; const TO_NUMBER = 'RECIPIENT_number'; const REGION ='YOUR_region' const SINCH_URL= 'https://'+REGION+'.sms.api.sinch.com/xms/v1/' + SERVICE_PLAN_ID + '/batches' const axios = require('axios') const headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ' + API_TOKEN} const payload = JSON.stringify({ from: SINCH_NUMBER, to: [TO_NUMBER], body: 'Programmers are tools for converting caffeine into code. We just got a new shipment of mugs! Check them out: https://tinyurl.com/4a6fxce7!' }) axios.post(SINCH_URL, payload, { headers }) .then(response => console.log(response.data) ).catch(error => console.error('There was an error!', error.response) ); ``` This example highlights the following required to successfully make an SMS API call using the Sinch Node.js SDK: - [Client initialization](#client) - [SMS domain access](#sms-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" }); ``` ## sms 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.sms.[endpoint_category].[method()]`. In the Sinch Node.js SDK, SMS API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API: - `sms.batches` - `sms.deliveryReports` - `sms.groups` - `sms.inbounds` For example: ```javascript const response = await sinchClient.sms.batches.send({ sendSMSRequestBody: { to: [ "+13215013855" ], from: "+12074193397", body: "This is a test message from the Node.js SDK." } }); ``` The `sms.batches` category of the Node.js SDK corresponds to the [batches](/docs/sms/api-reference/sms/batches/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Send](/docs/sms/api-reference/sms/batches/sendsms) | `send()` | | [List batches](docs/sms/api-reference/sms/batches/listbatches) | `list()` | | [Dry run](/docs/sms/api-reference/sms/batches/dry_run) | `dryRun()` | | [Get a batch message](/docs/sms/api-reference/sms/batches/getbatchmessage) | `get()` | | [Update a batch message](/docs/sms/api-reference/sms/batches/updatebatchmessage) | `update()` | | [Replace a batch](/docs/sms/api-reference/sms/batches/replacebatch) | `replace()` | | [Cancel a batch message](/docs/sms/api-reference/sms/batches/cancelbatchmessage) | `cancel()` | | [Send delivery feedback for a message](/docs/sms/api-reference/sms/batches/deliveryfeedback) | `sendDeliveryFeedback()` | The `sms.deliveryReports` category of the Node.js SDK corresponds to the [delivery_report and delivery_reports](/docs/sms/api-reference/sms/delivery-reports/) endpoints. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Retrieve a delivery report](/docs/sms/api-reference/sms/delivery-reports/getdeliveryreportbybatchid) | `get()` | | [Retrieve a recipient delivery report](/docs/sms/api-reference/sms/delivery-reports/getdeliveryreportbyphonenumber) | `getByPhoneNumber()` | | [Retrieve a list of delivery reports](/docs/sms/api-reference/sms/delivery-reports/getdeliveryreports) | `list()` | The `sms.groups` category of the Node.js SDK corresponds to the [groups](/docs/sms/api-reference/sms/groups/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [List groups](/docs/sms/api-reference/sms/groups/listgroups) | `list()` | | [Create a group](/docs/sms/api-reference/sms/groups/creategroup) | `create()` | | [Retrieve a group](/docs/sms/api-reference/sms/groups/retrievegroup) | `get()` | | [Update a group](/docs/sms/api-reference/sms/groups/updategroup) | `update()` | | [Replace a group](/docs/sms/api-reference/sms/groups/replacegroup) | `replace()` | | [Delete a group](/docs/sms/api-reference/sms/groups/deletegroup) | `delete()` | | [List group member phone numbers](/docs/sms/api-reference/sms/groups/getmembers) | `listMembers()` | The `sms.inbounds` category of the Node.js SDK corresponds to the [inbounds](/docs/sms/api-reference/sms/inbounds/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [List incoming messages](/docs/sms/api-reference/sms/inbounds/listinboundmessages) | `list()` | | [Retrieve inbound message](/docs/sms/api-reference/sms/inbounds/retrieveinboundmessage) | `get()` | Requests and queries made using the Node.js SDK are similar to those made using the SMS API. 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. For example, consider this example in which the `get()` method of the `sms.batches` class is invoked: SDK ```javascript const smsResponse = sinchClient.sms.batches.get({ batch_id: "BATCH_ID" }); ``` REST API ```JSON url = "https://us.SMS.api.sinch.com/v1/" + service_plan_id + "/batches/" + batch_id ``` When using the SMS API, `service_plan_id` and `batch_id` would be included as path parameters in the JSON payload. With the Node.js SDK, the `batch_id` parameter is included as an argument in the `get()` method. Note: Note that the `service_plan_id` path parameter does not need to be included in any requests created by the Node.js SDK. 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.