# Sinch Node.js SDK for Voice API v2

The Sinch Node.js SDK allows you to quickly interact with the  from inside your Node.js applications. When using the Node.js SDK, the code representing requests and queries sent to and responses received from the  are structured similarly to those that are sent and received using the .

The fastest way to get started with the SDK is to check out our [getting-started](/docs/voice-2.0/getting-started) guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK.

## Syntax

Note:
This guide describes the syntactical structure of the Node.js SDK for the Voice API v2, including any differences that may exist between the API itself and the SDK. For a full reference on Voice API v2 calls and responses, see the [Voice API v2 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
start.js
```javascript start.js
/**
 * Sinch Node.js Snippet
 * See: https://github.com/sinch/sinch-sdk-node/examples/snippets
 */
import { SinchClient } from '@sinch/sdk-core';
import * as dotenv from 'dotenv';
dotenv.config();

async function main() {
  const projectId = process.env.SINCH_PROJECT_ID ?? 'MY_PROJECT_ID';
  const keyId = process.env.SINCH_KEY_ID ?? 'MY_KEY_ID';
  const keySecret = process.env.SINCH_KEY_SECRET ?? 'MY_KEY_SECRET';

  // The phone number to be used as the caller ID, in E.164 format (e.g., +12025550123)
  const sinchPhoneNumber = process.env.SINCH_PHONE_NUMBER || 'MY_SINCH_PHONE_NUMBER';
  // The phone number you want to call, in E.164 format (e.g., +12025550123)
  const recipientPhoneNumber = 'RECIPIENT_PHONE_NUMBER';

  const sinch = new SinchClient({ projectId, keyId, keySecret });

  try {
    const response = await sinch.voice.v2.calls.start({
      createCallRequestBody: {
        commands: [
          {
            command: 'dial',
            callName: 'Node_SDK_Snippet_Call',
            from: {
              type: 'PHONE',
              phone: {
                number: sinchPhoneNumber,
              },
            },
            to: {
              type: 'PHONE',
              phone: {
                number: recipientPhoneNumber,
              },
            },
            dialTimeoutDurationSeconds: 30,
            events: {
              onAnswer: [
                {
                  command: 'messages',
                  messages: [
                    {
                      type: 'SAY',
                      say: {
                        text: 'Hello, your call is now connected.',
                        voiceName: 'Emma',
                      },
                    },
                  ],
                },
              ],
              onHangup: [
                {
                  command: 'hangup',
                },
              ],
            },
          },
        ],
      },
    });
    console.log(`✅ Successfully started a Voice v2 call to ${recipientPhoneNumber}.`);
    console.log(`Response:\n${JSON.stringify(response, null, 2)}`);
  } catch (err) {
    console.error(`❌ Failed to start a Voice v2 call to ${recipientPhoneNumber}:`);
    console.error(err);
  }
}

main();
```

REST API
```javascript
const query = new URLSearchParams({
  serviceId: '6e124178-c29d-46a5-943c-5c2ae544aade'
}).toString();

const projectId = 'YOUR_projectId_PARAMETER';
const resp = await fetch(
  `https://voice.api.sinch.com/v2/projects/${projectId}/calls?${query}`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Idempotency-Key': 'stringstringstri',
      Authorization: 'Basic ' + btoa('<username>:<password>')
    },
    body: JSON.stringify({
      commands: [
        {
          command: 'dial',
          callName: 'origin',
          from: {
            type: 'PHONE',
            phone: {number: '+15551234567'}
          },
          to: {
            type: 'PHONE',
            phone: {number: '+15559876543'}
          },
          dialTimeoutDurationSeconds: 30,
          maxCallDurationSeconds: 3600,
          events: {
            onAnswer: [
              {
                command: 'messages',
                messages: [
                  {
                    type: 'SAY',
                    say: {
                      text: 'Hello, your call is now connected.',
                      voiceName: 'Emma'
                    }
                  }
                ]
              }
            ],
            onHangup: [{command: 'hangup'}]
          }
        }
      ]
    })
  }
);

const data = await resp.json();
console.log(data);
```

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-v2-domain)
- [Endpoint usage](#endpoint-categories)
- [Field population](#request-and-query-parameters)


## Client

When using the Sinch Node.js SDK, you initialize communication with the Sinch backend by initializing the Node.js SDK's main client class. This client allows you to access the functionality of the Sinch Node.js SDK.

### Initialization

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

## Voice v2 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.v2.[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.v2.batches`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-node/1.6.0/classes/VoiceV2BatchesApi.html)
- [`voice.v2.calls`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-node/1.6.0/classes/VoiceV2CallsApi.html)
- [`voice.v2.services`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-node/1.6.0/classes/VoiceV2ServicesApi.html)
- [`voice.v2.sessions`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-node/1.6.0/classes/VoiceV2SessionsApi.html)
- [`voice.v2.svaml`![external](/assets/external-blue.5a59beb5e5a442f78b530509ddf6b5d0fa705285ff8181e59adf96b5c2c73e25.33310b29.svg)](https://developers.sinch.com/sdk/sinch-sdk-node/1.6.0/classes/VoiceV2SvamlApi.html)


For example:

```javascript
const response = await sinch.voice.v2.calls.start({
      createCallRequestBody: {
        commands: [
          {
            command: 'dial',
            callName: 'Node_SDK_Snippet_Call',
            from: {
              type: 'PHONE',
              phone: {
                number: sinchPhoneNumber,
              },
            },
            to: {
              type: 'PHONE',
              phone: {
                number: recipientPhoneNumber,
              },
            },
            dialTimeoutDurationSeconds: 30,
            events: {
              onAnswer: [
                {
                  command: 'messages',
                  messages: [
                    {
                      type: 'SAY',
                      say: {
                        text: 'Hello, your call is now connected.',
                        voiceName: 'Emma',
                      },
                    },
                  ],
                },
              ],
              onHangup: [
                {
                  command: 'hangup',
                },
              ],
            },
          },
        ],
      },
    });
```

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.v2.calls` class is invoked:

```javascript
const response = await sinch.voice.v2.calls.get({
      callId,
    });
```

```JSON

url = "https://voice.api.sinch.com/v2/projects/${projectId}/calls/${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.