# Node.js SDK 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 . Important Node.js SDK links: The following links are available for your reference: - [Sinch Node.js SDK repository](https://github.com/sinch/sinch-sdk-node) - [Sinch Node.js SDK releases](https://github.com/sinch/sinch-sdk-node/releases) - [Sinch Node.js quickstart repository](https://github.com/sinch/sinch-sdk-node-quickstart) - [Sinch Node.js SDK snippets repository](https://github.com/sinch/sinch-sdk-node-snippets) ## 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 Initialization of the Node.js SDK client can be done in two ways, depending on which product you are using. #### Unified Project Authentication 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" }); ``` #### Application Authentication 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({ applicationKey: "YOUR_application_key", applicationSecret: "YOUR_application_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 APPKEY="YOUR_application_key" APPSECRET="YOUR_application_secret" ``` **`app.js` File** ```javascript const {SinchClient} = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ applicationKey: process.env.APPKEY, applicationSecret: process.env.APPSECRET }); ``` 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" }); ``` ## Domains The Node.js SDK currently supports the following products: Numbers SMS Conversation Voice Verification ### Numbers Domain Note: This guide describes the syntactical structure of the Node.js SDK for the Numbers API, including any differences that may exist between the API itself and the SDK. For a full reference on Numbers API calls and responses, see the [Numbers API Reference](/docs/numbers/api-reference/numbers). The code sample below is an example of how to use the Node.js SDK to list the available numbers given a set of constraints. We've also provided an example that accomplishes the same task using the REST API. SDK snippet.js // eslint-disable-next-line no-unused-vars import { Numbers, NumbersService } from '@sinch/sdk-core'; /** @param {NumbersService} numbersService */ export const execute = async (numbersService) => { /** @type {Numbers.ListAvailableNumbersRequestData} */ const requestData = { regionCode: 'US', type: 'LOCAL', capabilities: ['SMS', 'VOICE'], }; const response = await numbersService.availableNumber.list(requestData); console.log(`Available numbers to rent:\n${JSON.stringify(response, null, 2)}`); }; REST API ```javascript import fetch from 'node-fetch'; async function run() { const query = new URLSearchParams({ regionCode: 'US', type: 'LOCAL' }).toString(); const projectId = 'YOUR_projectId_PARAMETER'; const resp = await fetch( `https://numbers.api.sinch.com/v1/projects/${projectId}/availableNumbers?${query}`, { method: 'GET', headers: { Authorization: 'Basic ' + Buffer.from(':').toString('base64') } } ); const data = await resp.text(); console.log(data); } run(); ``` This example highlights the following required to successfully make a Numbers API call using the Sinch Node.js SDK: - [Client initialization](#client) - [Numbers domain access](#numbers-domain) - [Endpoint usage](#endpoint-categories) - [Field population](#request-and-query-parameters) 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.numbers.[endpoint_category].[method()]`. In the Sinch Node.js SDK, Numbers API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API: - `numbers.availableNumber` - `numbers.activeNumber` - `numbers.availableRegions` - `numbers.callbackConfiguration` For example: ```javascript var numbers = await sinchClient.numbers.availableNumber.list({ regionCode: 'US', type: 'LOCAL' }); ``` The `numbers.availableNumber` category of the Node.js SDK corresponds to the [availableNumbers](/docs/numbers/api-reference/numbers/available-number/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Rent the first available number matching the provided criteria](/docs/numbers/api-reference/numbers/available-number/numberservice_rentanynumber) | `rentAny()` | | [Rent a specified available phone number](/docs/numbers/api-reference/numbers/available-number/numberservice_rentnumber) | `rent()` | | [Search for available phone numbers](/docs/numbers/api-reference/numbers/available-number/numberservice_listavailablenumbers) | `list()` | | [Checks the availability of a specific phone number](/docs/numbers/api-reference/numbers/available-number/numberservice_getavailablenumber) | `checkAvailability()` | The `numbers.activeNumber` category of the Node.js SDK corresponds to the [activeNumbers](/docs/numbers/api-reference/numbers/active-number/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [List active numbers for a project](/docs/numbers/api-reference/numbers/active-number/numberservice_listactivenumbers) | `list()` | | [Update active number](/docs/numbers/api-reference/numbers/active-number/numberservice_updateactivenumber) | `update()` | | [Retrieve active number](/docs/numbers/api-reference/numbers/active-number/numberservice_getactivenumber) | `get()` | | [Release active number](/docs/numbers/api-reference/numbers/active-number/numberservice_releasenumber) | `release()` | The `numbers.availableRegions` category of the Node.js SDK corresponds to the [availableRegions](/docs/numbers/api-reference/numbers/available-regions/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [List available regions](/docs/numbers/api-reference/numbers/available-regions/) | `list()` | The `numbers.callbackConfiguration` category of the Node.js SDK corresponds to the [callbackConfiguration](/docs/numbers/api-reference/numbers/numbers-callbacks/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Get callbacks configuration](/docs/numbers/api-reference/numbers/numbers-callbacks/getcallbackconfiguration) | `get()` | | [Update callback configuration](/docs/numbers/api-reference/numbers/numbers-callbacks/updatecallbackconfiguration) | `update()` | Requests and queries made using the Node.js SDK are similar to those made using the Numbers API. 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 `numbers.activeNumber` class is invoked: ```javascript var numResponse = sinchClient.numbers.activeNumber.get({ phoneNumber: "PHONE_NUMBER" }); ``` ```JSON url = "https://numbers.api.sinch.com/v1/projects/" + projectId + "/activeNumbers/" + phoneNumber ``` When using the Numbers API, `projectId` and `phoneNumber` would be included as path parameters in the request. With the Node.js SDK, the `phoneNumber` parameter is included as an argument in the `get()` method. Response fields match the API responses. They are delivered as JavaScript objects. ### SMS Domain 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) ); ``` 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. ### SMS Domain 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(); ``` 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. ### Voice Domain Note: This guide describes the syntactical structure of the Node.js SDK for the Voice API, including any differences that may exist between the API itself and the SDK. For a full reference on Voice API calls and responses, see the [Voice API Reference](/docs/voice/api-reference/voice). The code sample below is an example of how to use the Node.js SDK to make a Text to speech phone call. We've also provided an example that accomplishes the same task using the REST API. SDK index.js // eslint-disable-next-line no-unused-vars import { Voice, VoiceService } from '@sinch/sdk-core'; /** @param {VoiceService} voiceService */ export const execute = async (voiceService) => { const recipientPhoneNumber = 'the_phone_number_to_call'; const callingNumber = 'the_calling_number'; /** @type {Voice.TtsCalloutRequestData} */ const requestData = { ttsCalloutRequestBody: { method: 'ttsCallout', ttsCallout: { destination: { type: 'number', endpoint: recipientPhoneNumber, }, cli: callingNumber, locale: 'en-US/male', text: 'Hello, this is a call from Sinch.', }, }, }; const response = await voiceService.callouts.tts(requestData); console.log(`Callout response: \n${JSON.stringify(response, null, 2)}`); }; REST API ```javascript const APPLICATION_KEY = ""; const APPLICATION_SECRET = ""; const SINCH_NUMBER = ""; const LOCALE = ""; const TO_NUMBER = ""; const basicAuthentication = APPLICATION_KEY + ":" + APPLICATION_SECRET; const fetch = require('cross-fetch'); const ttsBody = { method: 'ttsCallout', ttsCallout: { cli: SINCH_NUMBER, destination: { type: 'number', endpoint: TO_NUMBER }, locale: LOCALE, text: 'This is a call from sinch', } }; fetch("https://calling.api.sinch.com/calling/v1/callouts", { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Basic ' + Buffer.from(basicAuthentication).toString('base64') }, body: JSON.stringify(ttsBody) }).then(res => res.json()).then(json => console.log(json)); ``` This example highlights the following required to successfully make a Voice API call using the Sinch Node.js SDK: - [Client initialization](#client) - [Voice domain access](#voice-domain) - [Endpoint usage](#endpoint-categories) - [Field population](#request-and-query-parameters) 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.voice.[endpoint_category].[method()]`. In the Sinch Node.js SDK, Voice API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API: - `voice.callouts` - `voice.calls` - `voice.conferences` - `voice.applications` For example: ```javascript const response = await sinchClient.voice.callouts.tts({ ttsCalloutRequestBody: { method: 'ttsCallout', ttsCallout: { cli: 'YOUR_Sinch_number', destination: { type: 'number', endpoint: 'YOUR_phone_number' }, text: 'This is a test call from Sinch using the Node.js SDK.' } } }); ``` The `voice.callouts` category of the Node.js SDK corresponds corresponds to the [callouts](/docs/voice/api-reference/voice/callouts/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Makes a Text-to-speech callout](/docs/voice/api-reference/voice/callouts/callouts#callouts/callouts/request) | `tts()` | | [Makes a Conference callout](/docs/voice/api-reference/voice/callouts/callouts#callouts/callouts/request) | `conference()` | | [Makes a Custom callout](/docs/voice/api-reference/voice/callouts/callouts#callouts/callouts/request) | `custom()` | The `voice.calls` category of the Node.js SDK corresponds corresponds to the [calls](/docs/voice/api-reference/voice/calls/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Get information about a call](/docs/voice/api-reference/voice/calls/calling_getcallresult) | `get()` | | [Manage call with `callLeg`](/docs/voice/api-reference/voice/calls/calling_managecallwithcallleg) | `manageWithCallLeg()` | | [Updates a call in progress](/docs/voice/api-reference/voice/calls/calling_updatecall) | `update()` | The `voice.conferences` category of the Node.js SDK corresponds corresponds to the [conferences](/docs/voice/api-reference/voice/conferences/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Get information about a conference](/docs/voice/api-reference/voice/conferences/calling_getconferenceinfo) | `get()` | | [Manage a conference participant](/docs/voice/api-reference/voice/conferences/calling_manageconferenceparticipant) | `manageParticipant()` | | [Remove a participant from a conference](/docs/voice/api-reference/voice/conferences/calling_kickconferenceparticipant) | `kickParticipant()` | | [Remove all participants from a conference](/docs/voice/api-reference/voice/conferences/calling_kickconferenceall) | `kickAll()` | The `voice.applications` category of the Node.js SDK corresponds corresponds to the [configuration](/docs/voice/api-reference/voice/applications/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Return all the numbers assigned to an application](/docs/voice/api-reference/voice/applications/configuration_getnumbers) | `listNumbers()` | | [Assign a number or list of numbers to an application](/docs/voice/api-reference/voice/applications/configuration_updatenumbers) | `assignNumbers()` | | [Unassign a number from an application](/docs/voice/api-reference/voice/applications/configuration_unassignnumber) | `unassignNumber()` | | [Return the callback URLs for an application](/docs/voice/api-reference/voice/applications/configuration_getcallbackurls) | `getCallbackUrls()` | | [Update the callback URL for an application](/docs/voice/api-reference/voice/applications/configuration_updatecallbackurls) | `updateCallbackUrls()` | | [Returns information about a number](/docs/voice/api-reference/voice/applications/calling_querynumber) | `QueryNumber()` | The Voice API uses [call events](/docs/voice/api-reference/voice/callbacks) and [SVAML responses](/docs/voice/api-reference/svaml/) to dynamically control calls throughout their life cycle. The Node.js SDK has a number of builder and helper methods designed to aid in quickly constructing the correct SVAML responses for the various call events. The builder and helper methods available and their parameters are described in the example and tables below. ```javascript const iceResponse = new Voice.IceSvamletBuilder() .setAction(Voice.iceActionHelper.hangup()) .addInstruction(Voice.iceInstructionHelper.say('Thank you for calling Sinch! This call will now end.', 'en-US')) .build(); ``` | Call event | Builder method name | Methods | | --- | --- | --- | | [Answered Call Event](/docs/voice/api-reference/voice/callbacks/ace) | `AceSvamletBuilder()` | `setAction()` or `addInstruction()` | | [Incoming Call Event](/docs/voice/api-reference/voice/callbacks/ice) | `IceSvamletBuilder()` | `setAction()` or `addInstruction()` | | [Prompt Input Event](/docs/voice/api-reference/voice/callbacks/pie) | `PieSvamletBuilder()` | `setAction()` or `addInstruction()` | Using these builder methods you can then build your SVAML responses using the following methods: **Actions:** | Helper method name | Action | | --- | --- | | `Voice.aceActionHelper.connectConf` | [connectConf](/docs/voice/api-reference/svaml/actions#connectconf) | | `Voice.aceActionHelper.continue` | [continue](/docs/voice/api-reference/svaml/actions#continue) | | `Voice.aceActionHelper.hangup` | [hangup](/docs/voice/api-reference/svaml/actions#hangup) | | `Voice.aceActionHelper.runMenu` | [runMenu](/docs/voice/api-reference/svaml/actions#runmenu) | | `Voice.iceActionHelper.connectConf` | [connectConf](/docs/voice/api-reference/svaml/actions#connectconf) | | `Voice.iceActionHelper.connectMxp` | [connectMxp](/docs/voice/api-reference/svaml/actions#connectmxp) | | `Voice.iceActionHelper.connectPstn` | [connectPstn](/docs/voice/api-reference/svaml/actions#connectpstn) | | `Voice.iceActionHelper.connectSip` | [connectSip](/docs/voice/api-reference/svaml/actions#connectsip) | | `Voice.iceActionHelper.hangup` | [hangup](/docs/voice/api-reference/svaml/actions#hangup) | | `Voice.iceActionHelper.park` | [park](/docs/voice/api-reference/svaml/actions#park) | | `Voice.iceActionHelper.runMenu` | [runMenu](/docs/voice/api-reference/svaml/actions#runmenu) | | `Voice.pieActionHelper.connectConf` | [connectConf](/docs/voice/api-reference/svaml/actions#connectconf) | | `Voice.pieActionHelper.connectSip` | [connectSip](/docs/voice/api-reference/svaml/actions#connectsip) | | `Voice.pieActionHelper.continue` | [continue](/docs/voice/api-reference/svaml/actions#continue) | | `Voice.pieActionHelper.hangup` | [hangup](/docs/voice/api-reference/svaml/actions#hangup) | | `Voice.pieActionHelper.runMenu` | [runMenu](/docs/voice/api-reference/svaml/actions#runmenu) | **Instructions:** | Helper method name | Action | | --- | --- | | `Voice.aceActionHelper.playFiles` | [playFiles](/docs/voice/api-reference/svaml/instructions#playfiles) | | `Voice.aceActionHelper.say` | [say](/docs/voice/api-reference/svaml/instructions#say) | | `Voice.aceActionHelper.setCookie` | [setCookie](/docs/voice/api-reference/svaml/instructions#setCookie) | | `Voice.aceActionHelper.startRecording` | [startRecording](/docs/voice/api-reference/svaml/instructions#startrecording) | | `Voice.iceActionHelper.answer` | [answer](/docs/voice/api-reference/svaml/instructions#answer) | | `Voice.iceActionHelper.playFiles` | [playFiles](/docs/voice/api-reference/svaml/instructions#playfiles) | | `Voice.iceActionHelper.say` | [say](/docs/voice/api-reference/svaml/instructions#say) | | `Voice.iceActionHelper.sendDtmf` | [sendDtmf](/docs/voice/api-reference/svaml/instructions#sendDtmf) | | `Voice.iceActionHelper.setCookie` | [setCookie](/docs/voice/api-reference/svaml/instructions#setcookie) | | `Voice.iceActionHelper.startRecording` | [startRecording](/docs/voice/api-reference/svaml/instructions#startrecording) | | `Voice.pieActionHelper.playFiles` | [playFiles](/docs/voice/api-reference/svaml/instructions#playfiles) | | `Voice.pieActionHelper.say` | [say](/docs/voice/api-reference/svaml/instructions#say) | | `Voice.pieActionHelper.sendDtmf` | [sendDtmf](/docs/voice/api-reference/svaml/instructions#senddtmf) | | `Voice.pieActionHelper.setCookie` | [setCookie](/docs/voice/api-reference/svaml/instructions#setcookie) | | `Voice.pieActionHelper.startRecording` | [startRecording](/docs/voice/api-reference/svaml/instructions#startrecording) | | `Voice.pieActionHelper.stopRecording` | [stopRecording](/docs/voice/api-reference/svaml/instructions#stoprecording) | Requests and queries made using the Node.js SDK are similar to those made using the Voice API. 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 `voice.calls` class is invoked: ```javascript const response = await sinchClient.voice.calls.get({ callId: 'YOUR_call_id' }); ``` ```JSON url = "https://calling.api.sinch.com/calling/v1/calls/id/" + callId ``` When using the Voice API, `callId` would be included as a path parameter in the request. With the Node.js SDK, the `callId` parameter is used in an object passed as an argument in the `get()` method. Response fields match the API responses. They are delivered as Javascript objects. ### Verification Domain Note: This guide describes the syntactical structure of the Node.js SDK for the Verification API, including any differences that may exist between the API itself and the SDK. For a full reference on Verification API calls and responses, see the [Verification API Reference](/docs/verification/api-reference/verification). The code sample below is an example of how to use the Node.js SDK to initiate an Verification SMS PIN request. We've also provided an example that accomplishes the same task using the REST API. SDK verificationSample.js // eslint-disable-next-line no-unused-vars import { Verification, VerificationService, VerificationsApi } from '@sinch/sdk-core'; import inquirer from 'inquirer'; /** * Class to handle a phone number verification using SMS. */ export class VerificationSample { /** * @param { VerificationService } verificationService - the VerificationService instance from the Sinch SDK containing the API methods. */ constructor(verificationService) { this.verificationService = verificationService; } /** * Starts the verification process by prompting the user for a phone number, * sending a verification request, asking for the verification code, and reporting it. * @return {Promise} */ async start() { // Step 1: Ask the phone number to verify const e164Number = await this.promptPhoneNumber(); try { // Step 2: Start the phone number verification const verificationId = await this.startSmsVerification(this.verificationService.verifications, e164Number); // Step 3: Ask the user for the received verification code const code = await this.promptSmsCode(); // Step 4: Report the verification code and complete the process await this.reportSmsVerification(this.verificationService.verifications, code, verificationId); console.log('Verification successfully completed.'); } catch (error) { console.error('An error occurred during the verification process:', error); } } /** * Prompts the user to enter their phone number. * @return {Promise} The phone number entered by the user. */ async promptPhoneNumber() { const userInput = await inquirer.prompt([ { type: 'input', name: 'phoneNumber', message: 'Enter the phone number you want to verify (E.164 format):', validate: (input) => input ? true : 'Phone number cannot be empty.', }, ]); return userInput.phoneNumber; } /** * Sends a request to start SMS verification for a phone number. * @param {VerificationsApi} verificationStarter - The VerificationsApi instance. * @param {string} phoneNumber - The phone number to verify. * @return {Promise} The verification ID if the request is successful. */ async startSmsVerification(verificationStarter, phoneNumber) { console.log(`Sending a verification request to ${phoneNumber}`); const requestData = Verification.startVerificationHelper.buildSmsRequest(phoneNumber); try { const response = await verificationStarter.startSms(requestData); if (!response.id) { throw new Error('Verification ID is undefined.'); } console.log(`Verification started successfully. Verification ID: ${response.id}`); return response.id; } catch (error) { console.error('Failed to start SMS verification:', error); throw error; } } /** * Prompts the user to enter the verification code they received. * @return {Promise} The verification code entered by the user. */ async promptSmsCode() { const answers = await inquirer.prompt([ { type: 'input', name: 'code', message: 'Enter the verification code you received:', validate: (input) => input ? true : 'Verification code cannot be empty.', }, ]); return answers.code; } /** * Sends a request to report the verification code for a specific verification ID. * @param { VerificationsApi } verificationReporter - The VerificationsApi instance. * @param {string} code - The verification code to report. * @param {string} id - The verification ID corresponding to the process. * @return {Promise} */ async reportSmsVerification(verificationReporter, code, id) { const requestData = Verification.reportVerificationByIdHelper.buildSmsRequest(id, code); try { const response = await verificationReporter.reportSmsById(requestData); console.log(`Verification reported successfully. Response status: ${response.status}`); } catch (error) { console.error('Failed to report SMS verification:', error); throw error; } } } REST API ```javascript const axios = require('axios'); const APPLICATION_KEY = ""; const APPLICATION_SECRET = ""; const TO_NUMBER = ""; const SINCH_URL = "https://verification.api.sinch.com/verification/v1/verifications"; const basicAuthentication = APPLICATION_KEY + ":" + APPLICATION_SECRET; const payload = { identity: { type: 'number', endpoint: TO_NUMBER }, method: 'sms' }; const headers = { 'Authorization': 'Basic ' + Buffer.from(basicAuthentication).toString('base64'), 'Content-Type': 'application/json; charset=utf-8' }; axios.post(SINCH_URL, payload, { headers }) .then(response => console.log(response.data) ).catch(error => console.error('There was an error!', error) ); ``` This example highlights the following required to successfully make a Verification API call using the Sinch Node.js SDK: - [Client initialization](#client) - [Verification domain access](#verification-domain) - [Endpoint usage](#endpoint-categories) - [Field population](#request-and-query-parameters) 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.verification.[endpoint_category].[method()]`. In the Sinch Node.js SDK, Verification API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API: - `verification.verifications` - `verification.verificationStatus` For example: ```javascript const startRequestData = verificationsHelper.buildStartSmsVerificationRequest( "YOUR_phone_number"); const smsVerification = await sinchClient.verification.verifications.startSms( startRequestData); ``` The `verification.verifications` category of the Node.js SDK corresponds to the [verifications start](/docs/verification/api-reference/verification/verifications-start/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Start an SMS PIN verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startSms()` | | [Start a FlashCall verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startFlashCall()` | | [Start a Phone Call verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startCallout()` | | [Start a Data verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startSeamless()` | | [Report an SMS verification PIN code by the identity of the recipient](/docs/verification/api-reference/verification/verifications-report/reportverificationbyidentity) | `reportSmsByIdentity()` | | [Report a FlashCall verification code (CLI) by the identity of the recipient](/docs/verification/api-reference/verification/verifications-report/reportverificationbyidentity) | `reportFlashCallByIdentity()` | | [Report a Phone Call verification code by the identity of the recipient](/docs/verification/api-reference/verification/verifications-report/reportverificationbyidentity) | `reportByCalloutIdentity()` | | [Report an SMS verification PIN code by the ID of the verification request](/docs/verification/api-reference/verification/verifications-report/reportverificationbyid) | `reportSmsById()` | | [Report a FlashCall verification code (CLI) by the ID of the verification request](/docs/verification/api-reference/verification/verifications-report/reportverificationbyid) | `reportFlashCallById()` | | [Report a Phone Call verification code by the ID of the verification request](/docs/verification/api-reference/verification/verifications-report/reportverificationbyid) | `reportCalloutById()` | The `verification.verificationStatus` category of the Node.js SDK corresponds to the [verifications](/docs/verification/api-reference/verification/verification-status/) endpoint. The mapping between the API operations and corresponding Node.js methods are described below: | API operation | SDK method | | --- | --- | | [Get the status of a verification by the ID of the verification request](/docs/verification/api-reference/verification/verification-status/verificationstatusbyid) | `getById()` | | [Get the status of a verification by the identity of the recipient](/docs/verification/api-reference/verification/verification-status/verificationstatusbyidentity) | `getByIdentity()` | | [Get the status of a verification by a reference value](/docs/verification/api-reference/verification/verification-status/verificationstatusbyreference) | `getByReference()` | The Node.js SDK has a number of helper methods designed to aid in quickly constructing the correct request bodies for the various methods. The helper methods available and their parameters are described in the example and table below. ```javascript const requestData = verificationHelper.buildStartSmsVerificationRequest( "YOUR_phone_number"); ``` | Request body | Helper method name | Parameters | | --- | --- | --- | | Start SMS Verification | `buildStartSmsVerificationRequest()` | `phoneNumber`***required**`reference` | | Start FlashCall Verification | `buildStartFlashCallVerificationRequest()` | `phoneNumber`***required**`reference``dialTimeout` | | Start Callout Verification | `buildStartCalloutVerificationRequest()` | `phoneNumber`***required**`reference` | | Start Data Verification | `buildStartSeamlessVerificationRequest()` | `phoneNumber`***required**`reference` | | Report SMS Verification by ID | `buildReportSmsVerificationByIdRequest()` | `id`***required**`code`***required**`cli` | | Report FlashCall Verification by ID | `buildReportFlashCallVerificationByIdRequest()` | `id`***required**`cli`***required** | | Report Phone Call Verification by ID | `buildReportCalloutVerificationByIdRequest()` | `id`***required**`code`***required** | | Report SMS Verification by Identity | `buildReportSmsVerificationByIdentityRequest()` | `identity`***required**`code`***required**`cli` | | Report FlashCall Verification by Identity | `buildReportFlashCallVerificationByIdentityRequest()` | `identity`***required**`cli`***required** | | Report Phone Call Verification by Identity | `buildReportCalloutVerificationByIdentityRequest()` | `identity`***required**`code`***required** | Requests and queries made using the Node.js SDK are similar to those made using the Verification API. 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 `getByIdentity()` method of the `verification.verificationStatus` class is invoked: ```javascript const response = await sinchClient.verification.verificationStatus.getByIdentity({ endpoint: 'PHONE_NUMBER', method: 'sms' }); ``` ```JSON url = "https://verification.api.sinch.com/verification/v1/verifications/" + method + "/number/" + endpoint ``` When using the Verification API, `method` and `endpoint` would be included as path parameters in the request. With the Node.js SDK, the `method` and `endpoint` parameters are used in an object passed as an argument in the `getByIdentity()` method. Response fields match the API responses. They are delivered as JavaScript objects. ## SDK features ### 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.