Skip to content
Last updated

Click to view on Community.

The Sinch Node.js SDK allows you to quickly interact with the suite of APIs 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 suite of APIs are structured similarly to those that are sent and received using the suite of APIs.

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 <b>Access Keys</b> page of the Sinch Build Dashboard. You can also create new access key IDs and Secrets, if required.

Note

If you have trouble accessing the above link, ensure that you have gained access to the Conversation API 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.

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

PROJECTID="YOUR_project_id"
ACCESSKEY="YOUR_access_key"
ACCESSSECRET="YOUR_access_secret" 

app.js File

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:

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.

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

APPKEY="YOUR_application_key"
APPSECRET="YOUR_application_secret" 

app.js File

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:

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 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.

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.

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)}`);
};

This example highlights the following required to successfully make a Numbers API call using the Sinch Node.js SDK:

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()].

Endpoint categories

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:

var numbers = await sinchClient.numbers.availableNumber.list({
    regionCode: 'US',
    type: 'LOCAL'
});

numbers.availableNumber endpoint category

The numbers.availableNumber category of the Node.js SDK corresponds to the availableNumbers endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

numbers.activeNumber endpoint category

The numbers.activeNumber category of the Node.js SDK corresponds to the activeNumbers endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

numbers.availableRegions endpoint category

The numbers.availableRegions category of the Node.js SDK corresponds to the availableRegions endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
List available regionslist()

numbers.callbackConfiguration endpoint category

The numbers.callbackConfiguration category of the Node.js SDK corresponds to the callbackConfiguration endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

Request and query parameters

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:


var numResponse = sinchClient.numbers.activeNumber.get({
  phoneNumber: "PHONE_NUMBER"
  });

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.

Responses

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.

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.

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)}`);
};

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()].

Endpoint categories

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:

const response = await sinchClient.sms.batches.send({
    sendSMSRequestBody: {
        to: [
            "+13215013855"
        ],
        from: "+12074193397",
        body: "This is a test message from the Node.js SDK."
    }
});

sms.batches endpoint category

The sms.batches category of the Node.js SDK corresponds to the batches endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
Sendsend()
List batcheslist()
Dry rundryRun()
Get a batch messageget()
Update a batch messageupdate()
Replace a batchreplace()
Cancel a batch messagecancel()
Send delivery feedback for a messagesendDeliveryFeedback()

sms.deliveryReports endpoint category

The sms.deliveryReports category of the Node.js SDK corresponds to the delivery_report and delivery_reports endpoints. The mapping between the API operations and corresponding Node.js methods are described below:

sms.groups endpoint category

The sms.groups category of the Node.js SDK corresponds to the groups endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
List groupslist()
Create a groupcreate()
Retrieve a groupget()
Update a groupupdate()
Replace a groupreplace()
Delete a groupdelete()
List group member phone numberslistMembers()

sms.inbounds endpoint category

The sms.inbounds category of the Node.js SDK corresponds to the inbounds endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
List incoming messageslist()
Retrieve inbound messageget()

Request and query parameters

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:

const smsResponse = sinchClient.sms.batches.get({
  batch_id: "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.

Responses

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.

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).

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();

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()].

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:

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 endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Send a messagesend, or you could use any of the following message-specific methods:
sendCardMessage
sendCarouselMessage
sendChoiceMessage
sendContactInfoMessage
sendListMessage
sendLocationMessage
sendMediaMessage
sendTemplateMessage
sendTextMessage
Get a messageget
Delete a messagedelete
List messageslist
Update a message's metadataupdate

app endpoint category

The app category of the Node.js SDK corresponds to the apps endpoint. The mapping between the API operations and corresponding methods are described below:

contact endpoint category

The contact category of the Node.js SDK corresponds to the contacts endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
List contactslist
Create a contactcreate
Get a contactget
Delete a contactdelete
Update a contactupdate
Merge two contactsmergeContact
Get channel profilegetChannelProfile

conversation endpoint category

The conversation category of the Node.js SDK corresponds to the conversations endpoint. The mapping between the API operations and corresponding methods are described below:

events endpoint category

The events category of the Node.js SDK corresponds to the events endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Send an eventsend, or you could use any of the following message-specific methods: sendComposingEvent, sendComposingEndEvent, sendCommentReplyEvent, sendAgentJoinedEvent, sendAgentLeftEvent, or sendGenericEvent
Get an eventget
Delete an eventdelete
List eventslist

transcoding endpoint category

The transcoding category of the Node.js SDK corresponds to the messages:transcode endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Transcode a messagetranscodeMessage

capability endpoint category

The capability category of the Node.js SDK corresponds to the capability endpoint. The mapping between the API operations and corresponding methods are described below:

API operationSDK method
Capability lookuplookup

webhooks endpoint category

The webhooks category of the Node.js SDK corresponds to the webhooks endpoint. The mapping between the API operations and corresponding methods are described below:

templatesV1 endpoint category

The templatesV1 category of the Node.js SDK corresponds to the Templates endpoint. The mapping between the API operations and corresponding methods are described below:

templatesV2 endpoint category

The templatesV2 category of the Node.js SDK corresponds to the Templates-V2 endpoint. The mapping between the API operations and corresponding methods are described below:

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.

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:


const response = await sinchClient.conversation.messages.get({
                    message_id:"YOUR_message_id"
                    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.

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.

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)}`);
};

This example highlights the following required to successfully make a Voice API call using the Sinch Node.js SDK:

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()].

Endpoint categories

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:

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.'
           }
        }
       });

voice.callouts endpoint category

The voice.callouts category of the Node.js SDK corresponds corresponds to the callouts endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

voice.calls endpoint category

The voice.calls category of the Node.js SDK corresponds corresponds to the calls endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

API operationSDK method
Get information about a callget()
Manage call with callLegmanageWithCallLeg()
Updates a call in progressupdate()

voice.conferences endpoint category

The voice.conferences category of the Node.js SDK corresponds corresponds to the conferences endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

voice.applications endpoint category

The voice.applications category of the Node.js SDK corresponds corresponds to the configuration endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

Call events and SVAML

The Voice API uses call events and SVAML responses 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.

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 eventBuilder method nameMethods
Answered Call EventAceSvamletBuilder()setAction() or addInstruction()
Incoming Call EventIceSvamletBuilder()setAction() or addInstruction()
Prompt Input EventPieSvamletBuilder()setAction() or addInstruction()

Using these builder methods you can then build your SVAML responses using the following methods:

Actions:

Helper method nameAction
Voice.aceActionHelper.connectConfconnectConf
Voice.aceActionHelper.continuecontinue
Voice.aceActionHelper.hanguphangup
Voice.aceActionHelper.runMenurunMenu
Voice.iceActionHelper.connectConfconnectConf
Voice.iceActionHelper.connectMxpconnectMxp
Voice.iceActionHelper.connectPstnconnectPstn
Voice.iceActionHelper.connectSipconnectSip
Voice.iceActionHelper.hanguphangup
Voice.iceActionHelper.parkpark
Voice.iceActionHelper.runMenurunMenu
Voice.pieActionHelper.connectConfconnectConf
Voice.pieActionHelper.connectSipconnectSip
Voice.pieActionHelper.continuecontinue
Voice.pieActionHelper.hanguphangup
Voice.pieActionHelper.runMenurunMenu

Instructions:

Helper method nameAction
Voice.aceActionHelper.playFilesplayFiles
Voice.aceActionHelper.saysay
Voice.aceActionHelper.setCookiesetCookie
Voice.aceActionHelper.startRecordingstartRecording
Voice.iceActionHelper.answeranswer
Voice.iceActionHelper.playFilesplayFiles
Voice.iceActionHelper.saysay
Voice.iceActionHelper.sendDtmfsendDtmf
Voice.iceActionHelper.setCookiesetCookie
Voice.iceActionHelper.startRecordingstartRecording
Voice.pieActionHelper.playFilesplayFiles
Voice.pieActionHelper.saysay
Voice.pieActionHelper.sendDtmfsendDtmf
Voice.pieActionHelper.setCookiesetCookie
Voice.pieActionHelper.startRecordingstartRecording
Voice.pieActionHelper.stopRecordingstopRecording

Request and query parameters

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:

const response = await sinchClient.voice.calls.get({
        callId: 'YOUR_call_id'
    });

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.

Responses

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.

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.

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<void>}
   */
  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<string>} 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<string>} 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<string>} 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<void>}
   */
  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;
    }
  }
}

This example highlights the following required to successfully make a Verification API call using the Sinch Node.js SDK:

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()].

Endpoint categories

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:

const startRequestData = verificationsHelper.buildStartSmsVerificationRequest(
                                                      "YOUR_phone_number");
const smsVerification = await sinchClient.verification.verifications.startSms(
                                                      startRequestData);

verification.verifications endpoint category

The verification.verifications category of the Node.js SDK corresponds to the verifications start endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

verification.verificationStatus endpoint category

The verification.verificationStatus category of the Node.js SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Node.js methods are described below:

Helper methods

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.

const requestData = verificationHelper.buildStartSmsVerificationRequest(
                                          "YOUR_phone_number");
Request bodyHelper method nameParameters
Start SMS VerificationbuildStartSmsVerificationRequest()
  • phoneNumber
    *required
  • reference
Start FlashCall VerificationbuildStartFlashCallVerificationRequest()
  • phoneNumber
    *required
  • reference
  • dialTimeout
Start Callout VerificationbuildStartCalloutVerificationRequest()
  • phoneNumber
    *required
  • reference
Start Data VerificationbuildStartSeamlessVerificationRequest()
  • phoneNumber
    *required
  • reference
Report SMS Verification by IDbuildReportSmsVerificationByIdRequest()
  • id
    *required
  • code
    *required
  • cli
Report FlashCall Verification by IDbuildReportFlashCallVerificationByIdRequest()
  • id
    *required
  • cli
    *required
Report Phone Call Verification by IDbuildReportCalloutVerificationByIdRequest()
  • id
    *required
  • code
    *required
Report SMS Verification by IdentitybuildReportSmsVerificationByIdentityRequest()
  • identity
    *required
  • code
    *required
  • cli
Report FlashCall Verification by IdentitybuildReportFlashCallVerificationByIdentityRequest()
  • identity
    *required
  • cli
    *required
Report Phone Call Verification by IdentitybuildReportCalloutVerificationByIdentityRequest()
  • identity
    *required
  • code
    *required

Request and query parameters

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:

const response = await sinchClient.verification.verificationStatus.getByIdentity({
    endpoint: 'PHONE_NUMBER',
    method: 'sms'
});

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.

Responses

Response fields match the API responses. They are delivered as JavaScript objects.

SDK features

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

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:

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<ActiveNumber> = 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

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.

// 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;
    }
  }

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:

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
  }

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.