Sinch Node.js SDK for Numbers
The Sinch Numbers Node.js SDK allows you to quickly interact with the Numbers 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 Numbers API are structured similarly to those that are sent and received using the Numbers API itself.
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 on the side of this page is an example of how to use the Node.js SDK to list the available numbers given a set of constraints. The code is also displayed below, along with a Numbers API call that accomplishes the same task, for reference:
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('<username>:<password>').toString('base64')
}
}
);
const data = await resp.text();
console.log(data);
}
run();
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(){
let numbers = await sinchClient.numbers.availableNumber.list({
regionCode: 'US',
type: 'LOCAL'
});
console.log(JSON.stringify(numbers));
}
run();
// import statements can only be used in javascript modules.
// This inclides frameworks like React or Angular or .mjs files
import { SinchClient } from '@sinch/sdk-core';
const sinchClient = new SinchClient({
projectId: "YOUR_project_id",
keyId: "YOUR_access_key",
keySecret: "YOUR_access_secret"
});
var numbers = await sinchClient.numbers.availableNumber.list({
regionCode: 'US',
type: 'LOCAL'
});
console.log(JSON.stringify(numbers));
This example highlights the following required to successfully make a Numbers 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
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
Note:
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"
});
Numbers 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.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:API operation | SDK method |
---|---|
Rent the first available number matching the provided criteria | rentAny() |
Rent a specified available phone number | rent() |
Search for available phone numbers | list() |
Checks the availability of a specific phone number | checkAvailability() |
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:API operation | SDK method |
---|---|
List active numbers for a project | list() |
Update active number | update() |
Retrieve active number | get() |
Release active number | release() |
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 operation | SDK method |
---|---|
List available regions | list() |
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:API operation | SDK method |
---|---|
Get callbacks configuration | get() |
Update callback configuration | update() |
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 theget()
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
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.
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 anApiPromiseList
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
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<ConversationMessage> = 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
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;
}
}
// 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;
}
}
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
}
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.