Sinch Node.js SDK for Voice API

The Sinch Voice API Node.js SDK allows you to quickly interact with the Voice API from inside your Node.js applications. The fastest way to get started with the SDK is to check out our getting started guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK.

Syntax

When using the Node.js SDK, the code representing requests and queries sent to and responses received from the Voice API are structured similarly to those that are sent and received using the Verification API itself.

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 on the side of this page is an example of how to use the Node.js SDK to make a Text to speech phone call. The code is also displayed below, along with a Voice REST API call that accomplishes the same task, for reference:

REST APISDK
Copy
Copied
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));
Copy
Copied
const {SinchClient} = require('@sinch/sdk-core');

const sinchClient = new SinchClient({
    applicationKey: 'YOUR_application_key',
    applicationSecret: 'YOUR_application_secret'
});

async function makeCall(){
    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.'
           }
        }
    });
       
    console.log(JSON.stringify(response));    
}

makeCall();

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

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

To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.

Copy
Copied
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

Copy
Copied
APPKEY="YOUR_application_key"
APPSECRET="YOUR_application_secret" 

app.js File

Copy
Copied
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:

Copy
Copied
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"
});

Voice domain

The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.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:

Copy
Copied
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:
API operationSDK method
Makes a Text-to-speech callouttts()
Makes a Conference calloutconference()
Makes a Custom calloutcustom()

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:
API operationSDK method
Get information about a conferenceget()
Manage a conference participantmanageParticipant()
Remove a participant from a conferencekickParticipant()
Remove all participants from a conferencekickAll()

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:
API operationSDK method
Return all the numbers assigned to an applicationlistNumbers()
Assign a number or list of numbers to an applicationassignNumbers()
Unassign a number from an applicationunassignNumber()
Return the callback URLs for an applicationgetCallbackUrls()
Update the callback URL for an applicationupdateCallbackUrls()
Returns information about a numberQueryNumber()

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.

Copy
Copied
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 name
Answered Call EventAceSvamletBuilder()
Incoming Call EventIceSvamletBuilder()
Prompt Input EventPieSvamletBuilder()

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:
SDKREST API
Copy
Copied
const response = await sinchClient.voice.calls.get({
        callId: 'YOUR_call_id'
    });
Copy
Copied
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.

We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.