TaCode Tuesday: How to Use Zang SMS and Call APIs in Node.JS

Posted by Pedram Mohammadi on March 15, 2017

A couple years ago, the web was a stateless environment. Interactive features were treated as isolated units within a website, encapsulated within Flash or Java Applets. In 2009, NodeJS was released by Ryan Dahl aiming to create more interactive websites by establishing two-way connections. NodeJS enables asynchronous, event-driven input/output (I/O) making lightweight and efficient connections even in data-intensive applications.
TaCode Tuesday: How to Use Zang SMS and Call APIs in Node.JS | http://blog.zang.io

The figure above shows the internal structure of Node.JS. Here, you see that only a single thread (i.e. file I/O, DNS, etc.) connects Node to the rest of an application. This single thread handles all incoming requests concurrently and can interface with one another. The architecture also allows the thread pool to interact with Node.JS’ low-level libraries to perform operations such as database transaction, file system access, etc. The asynchronous processing is done by libuv which enables Node to move without having to wait for the outcome of a current event.

Why Use Node.JS?

Node is an asynchronous event driven JavaScript runtime. Because of this, it can handle up to one million concurrent connections while usual web servers require a new thread for every request. Node can also be easily scaled and requires less memory and CPU overhead, because it utilizes heap elements instead of using threads which typically take about 2MB of memory.

Due to its asynchronous nature, a website built in Node can continuously execute a process without having to wait for a response. For every successful request, Node sends a callback and an application notification is made, allowing the waiting event to resume. This is possible through the use of Google’s V8 engine and the C++ libuv library. V8 is a Just in Time (JIT) compiler written in C++ that compiles JavaScript directly into the assembly code while at the same time optimizing the program by removing dead objects. The libuv library, on the other hand, is responsible for the I/O operations. It is in libuv that time-consuming operations are delegated so that websites can focus on more responsive processes. 

Node also utilizes native JSON. Because of this, it is fit to use in websites that are primarily built on Java. It also uses RESTful services to establish secure and efficient client-server connections. In utilizing JSON's JavaScript API, Node can also be used in both front-end and back-end components, enabling faster development time. It also minimizes the defects brought by having different programming languages talk with one another.

Using Node.JS for Zang

In this week’s TaCode Tuesday, we will teach you how to use Zang in Node.JS utilizing its SMS and call APIs. Node.JS can be used for any website, and mobile and desktop applications in which asynchronous (async) processing is vital.

Before we start, you must have basic knowledge of:

  • Node.JS Framework
  • REST API
  • Asynchronous programming
  • JavaScript
  • JSON Data Format
  • Terminal window commands
  • Zang subscription – its free, you can get one here. 

Let’s start coding!

We will create a NodeJS client by connecting to Zang APIs. The following are the features of the standard NodeJS REST client:

  • Direct or thorough proxy connection to remote API sites
  • Remote API operations can be registered as client’s own method enabling a simple code reuse
  • Automatic parsing of XML and JSON response documents as JS objects
  • Dynamic path and query parameters and request headers
  • Improved error handling mechanism (client or specific request)
  • Added support for compressed responses like gzip and deflate
  • Transparent HTTP/HTTPS connection to remote API sites
  • Allows simple HTTP basic authentication
  • Allows most common HTTP operations: GET, POST, PUT, DELETE, PATCH

 

1.0 How to install your NodeJS client

Start by opening your terminal window and key in the following command:

 

$npm install node-rest-client

 

There are two ways to call a web service in Node.JS: registered and direct. Use the registered method to implement custom calls making code reuse easy. On the other hand, use direct method if you just want to utilize the standard methods available in Node.

 

  1. Registered method works by invoking a predefined JavaScript method, such as:

 

client.registerMethod("zangMethod", "{https://api.zang.io/v2/Accounts/{AccountSID}/Calls.json}", "GET");

client.methods.jsonMethod(function (data, response) {

// parsed response body as js object

console.log(data);

// raw response

console.log(response);

});

 

  1. Direct method works by using the native Node.JS method

 

client.get("{https://api.zang.io/v2/Accounts/{AccountSID}/Calls.json}", function (data, response) {

// parsed response body as js object

console.log(data);

// raw response

console.log(response);

});

 

2.0 How to invoke Zang Call API though Node.JS

 

There are two ways to invoke Zang’s Call API. These are through a URL: https://api.zang.io/v2/Accounts/{AccountSID}/Calls.json; or through CURL:

 

curl -X POST 'https://api.zang.io/v2/Accounts/{AccountSid}/Calls.json' -u '{AccountSid}:{AuthToken}' -d 'From=XXX-XXX-XXXX&To=XXX-XXX-XXXX&

Url=http://zang.io/ivr/welcome/call'

 

Once successful, you will receive the following response in JSON format:

 

{

 "date_updated": "Wed, 13 Jul 2016 15:25:01 -0000",

 "parent_call_sid": "",

 "duration": 0,

 "from": "+15555555555",

 "to": "+19999999999",

 "caller_id_blocked": "false",

 "answered_by": "nobody",

 "sid": "{CallSid}",

 "recordings_count": "",

 "price": "0.00",

 "api_version": "v2",

 "status": "queued",

 "direction": "outbound-api",

 "start_time": null,

 "date_created": "Wed, 13 Jul 2016 15:25:01 -0000",

 "subresource_uris": {

   "notifications": "/v2/Accounts/{AccountSid}/Calls/{CallSid}/Notifications",

   "recordings": "/v2/Accounts/{AccountSid}/Calls/{CallSid}/Recordings"

 },

 "forwarded_from": "",

 "uri": "/v2/Accounts/{AccountSid}/Calls/{CallSid}",

 "account_sid": "{AccountSid}",

 "duration_billed": 0,

 "end_time": null,

 "phone_number_sid": ""

}

 

2.1 How to invoke Zang Call API through "Direct" approach

 

var Client = require('node-rest-client').Client;

var client = new Client();

 

//setup the zang call variables

var args = {

   data: { From: "{XXX-XXX-XXXX}",

   To: "{XXX-XXX-XXXX}",

   Url: "{http://zang.io/ivr/welcome/call}"} // data passed to REST method (only useful in POST, PUT or PATCH methods)

parameters: { arg1: "{AccountSid}", arg2: "{AuthToken}" }, // query parameter substitution vars

   headers: { "Content-Type": "application/json" }// request headers

};

//invoke the zang call api

client.get("https://api.zang.io/v2/Accounts/{AccountSID}/{Calls.json}", args,

   function (data, response)

   {

       // parsed response body as js object

       console.log(data);

       // raw response

       console.log(response);

   });

 

3.0 How to invoke Zang SMS API through Node.JS

There are two ways to invoke Zang’s SMS API. The first one is through a URL: https://api.zang.io/v2/Accounts/{AccountSid}/SMS/Messages.json; the second is through CURL:

 

curl -X POST 'https://api.zang.io/v2/Accounts/{AccountSid}/SMS/Messages.json' -u '{AccountSid}:{AuthToken}'

-d 'To=XXX-XXX-XXXX&From=XXX-XXX-XXXX&Body=This is an SMS sent from Zang'

 

Once successful, you will receive the following response in JSON format:

 

{

"api_version": "v2",

"sid": "{SmsSid}",

"account_sid": "{AccountSid}",

"date_created": "Tue, 24 Jul 2012 14:08:23 +0000",

"date_updated": "Tue, 24 Jul 2012 14:08:24 +0000",

"date_sent": "Tue, 24 Jul 2012 14:08:24 +0000",

"to": "+17325551234",

"from": "+14245551234",

"body": "Test message sent from TelAPI!",

"status": "sent",

"direction": "outbound-api",

"price": "0.070000",

"uri": "/v2/Accounts/AC5521767e53d04deeb0a06f660cee50f9/SMS/Messages/{SmsSid}.json"

}

 

3.1 Invoke the Zang Call API via NodeJS using registered approach

 

var Client = require('node-rest-client').Client;

// configure basic http auth for every request

var options_auth = { AccountSid: "{AccountSid}", AuthToken: "{AuthToken}" };

var client = new Client(options_auth);

// registering remote methods

client.registerMethod("jsonMethod", "{https://api.zang.io/v2/Accounts/{AccountSid}/SMS/Messages.json}", "POST");

client.methods.jsonMethod(args, function (data, response) {

// parsed response body as js object

console.log(data);

// raw response

console.log(response);

});

// posted data can be js object

//setup the zang sms variables

var args = {

data: { From: "{XXX-XXX-XXXX}",

To: "{XXX-XXX-XXXX}",

Body: "{This is an SMS sent from Zang}"} // data passed to REST method (only useful in POST, PUT or PATCH methods)

parameters: { arg1: "{AccountSid}", arg2: "{AuthToken}" }, // query parameter substitution vars

headers: { "Content-Type": "application/json" }// request headers

};

client.methods.jsonMethod(args_js, function (data, response) {

// parsed response body as js object

console.log(data);

// raw response

console.log(response);

}).on('error', function (err) {

   console.log('something went wrong on the request', err.request.options);

});

 

// handling client error events

client.on('error', function (err) {

console.error('Something went wrong on the client', err);

});

Easy, right? Use Node to build prototypes and rapidly evolving applications like media sites and chat apps. Just keep in mind that like any platform, there are a couple of things to watch out for. For instance, since Node's architecture is deeply rooted in the V8 runtime engine, any modifications to it may impact your code. The single threaded nature of Node could also be a single point of failure. If too many concurrent requests are made, it may slow down the server or crash Node's main thread.  

Despite this, Node is still an elegant solution for modern developers, most especially at the rate of agility required to compete in the market.

If you want to try Zang for free, you can sign up here.

Start building on Zang

Topics: TaCode Tuesday, cPaaS, SMS