Managing phone numbers and routes is important to businesses both large and small. In the same way, the cloud has transformed how applications are written, tested, and deployed. The ability to scale your communications solutions via APIs provides unprecedented control over calling and messaging within your organization. The Flowroute v1 API allows users to manage phone numbers and purchase new phone numbers over a RESTful HTTP interface. This is useful for integration with existing backend and web-based systems, but sometimes administrators want direct access to get things done. Phone number management is just a command line argument away when you leverage the Node.js SDK for Flowroute and add a few lines of code.


Requirements


Download the SDK

The Flowroute SDK for Node.js (v1) is available as open source on GitHub.

Navigate to the root directory where you store your development projects and pull the repository by cloning it with the command:

git clone https://github.com/flowroute/flowroute-numbers-nodejs.git
                

You should see a result similar to Figure 1. A directory named flowroute-numbers-nodejs will be created.

Figure 1: Clone the SDK

Make note of the directory but don’t navigate to it yet. The next step is to create the project for command line access.

Configure the Project

From the command line, create a new directory named flowroute-cli and navigate to it. Initialize a Node.js project by issuing the command:

npm init
                

You will be prompted with several questions. Name the package and version, add an optional description, set the license, etc. The result will look something like Figure 2.

Figure 2: npm init

If you want to track source control, you can issue git init to initialize a new git repository. Navigate into the SDK folder you installed previously. The folder path should look like this:

flowroute-numbers-nodejs/flowroutenumberslib/lib
                

Copy the lib subfolder and all its contents into your project, so your project directory looks like this:

flowroute-cli/lib
                

For example, if SDK directory is the same level as your command line project, you can issue this command from the root of your flowroute-cli project:

cp -r ../flowroute-numbers-nodejs/flowroutenumberslib/lib 
                

In Visual Studio Code, your project structure should look like Figure 3. You will see additional files such as CustomAuthUtility.js and flowrouteUtils.js.

Now that the SDK is accessible from your project, you can add a few additional libraries to help with development.

Install Dependencies

There are three packages to install that are needed for the command line project to work. The first two are used by the Flowroute SDK and are needed to issue HTTP requests and decode the resulting data. These packages are named request and utf8. To install them and save them to your project, issue the following commands:

npm i --save request\n\nnpm i --save utf8
                

This will download the packages and update the package.json for your project with the dependencies.

The next package is a utility called commander. This utility makes it easy to parse command line arguments and take various actions based on the commands passed. It is useful to help construct a command line interface for the Flowroute phone number API.

npm i --save commander
                

Now that the prerequisites are installed, you can build the command line interface.

Authentication

The first step we’ll tackle is authentication to the API. From your IDE, create a new file and name it fr.js (as in Flowroute). The main program will be wrapped in an immediately invoked function expression (IIFE). This ensures the variables used are scoped to the function itself. As arguments, you’ll pass in the commander library and the Flowroute SDK. The shell looks like this:

(function (program, flowroute) {    console.log(program);
    console.log(flowroute);
 })(require('commander'), require('./lib'));

                

Save the file and run it from the command line to ensure everything is working correctly. Run the file using Node.js:

node fr.js
                

The first run will just show some structures from the helper packages. The two console.log statements just test that everything is working properly. You can go ahead and remove them.

There are two ways to authenticate with the Flowroute API. The first is to edit the configuration.js file under the lib folder. The username maps to your access key and the password maps to your secret key. Both are available at https://manage.flowroute.com/accounts/preferences/api/. If you store them here, you will not have to pass them every time you invoke the command line. However, you also risk exposing the credentials. Although it is beyond the scope of this article, if you want to securely store credentials you can install other third-party libraries that allow you to encrypt the credentials.

You can also choose to pass in the credentials as parameters each time you run the command. To do this, use a method declaration instead of the IIFE. It will use the commander package to check if a username and password exist, and pass them to the Flowroute SDK.

var configure = function() {    if(program.username && program.password) {
        console.log('Overrode username and password.');
        flowroute.configuration.username = program.username;
        flowroute.configuration.password = program.password;  
    }
}

                

Now you can pass the version of the command line interface and the parameters to the commander package. The notation provides short-hand (-u) and long-hand (–username) parameter name and notes that if the parameter is used, an additional argument is required due to the angle brackets.

program  .version('0.0.1')
  .option('-u, --username ', 'Username')
  .option('-p, --password ', 'Password');

                

The very last two lines of code inside the IIFE tell the commander package to parse the command-line arguments and call the configure function to set up the username and password if they exist:

 
program.parse(process.argv);
configure();

                

Run the command again, without passing any information. It should do nothing. Now run it and pass a username and password:

node fr.js -u my-access-key --password my-secret
                

You should receive the message “Overrode username and password."

As a side note, the commander package automatically builds help text based on the parameters and commands you configure. Pass the –help parameter to see this in action.

The First Command: Listing Area Codes

The first command will list area codes (NPAs) using the Flowroute API. The API supports limiting items and paging through long lists. To keep this example simple, it will always load the first page. As the first statement inside the IIFE, set a default number of items to bring back:

var itemsPerPage = 10;
                    

Inside the configure function, add support to override items with a parameter:

if (program.items)     itemsPerPage = program.items;
    console.log('Overrode items per page to', itemsPerPage);
}

                    

Add the parameter to the commander configuration after the password parameter:

.option('-i, --items ', 'Items per Page');
                    

Now the interface will default to ten items unless you override them with a parameter. To add the command to list NPAs, there are two steps. First, add the method that will retrieve the results and either show an error or list the codes:

var listNPAs = function (err, npaList)  {  if (err) {
    console.log(err);
  }
  else {
    for (var areaCode in npaList.npas) {
      console.log('Area Code: ' + areaCode);
    }
  }
};

                    

Second, configure the command line interface to accept the command and make the call to the API using the SDK.

program  .command('listNPAs')
  .action(function () {
    configure();
    flowroute.PurchasablePhoneNumbersController
      .listAvailableNPAs(itemsPerPage, listNPAs);
   });

                    

Because configure will be called from inside each command, remove the previous call you made after parsing the arguments. Notice that the SDK accepts a limit for items and a method to call when the results are ready. This enables the SDK to asynchronously fetch the information from the Flowroute server.

Now you can run the command to test it:

node fr.js listNPAs
                    

The result should be a list of available area codes. On my machine, it provides a list from 201 to 210.

List Exchanges

Next, you can build out the additional commands. Here is the code to list area codes and exchanges (the SDK documentation describes the structure of the result data):

var listAreaandExchange = function(err, exchangeList) {  if (err) {
    console.log(err);
  else {
    for (var number in exchangeList.npanxxs) {
      console.log('Available Exchange:', number.substring(0,3), '-',
                  number.substring(3), '- XXXX');
    }
  }
};

                    

The command is configured to accept an area code and filter the available exchanges. It is passed a hard-coded page number (one) and then the method for callback:

program  .command('listExchanges ')
  .action(function (areaCode) {
    configure();
    flowroute.PurchasablePhoneNumbersController.listAreaandExchange(
      itemsPerPage,
      areaCode,
      1,
      listAreaandExchange);
   });

                    

Running the command like this:

node fr.js listExchanges 813
                    

Will produce a list like this:

As you guessed, the next logical command will list the available numbers for an exchange.

Listing Numbers

For listing numbers, a simple helper method will format the numbers to display:

var formatNumber = function (raw) {  return `+${raw.substring(0,1)} (${raw.substring(1.4)})` +  `${raw.substring(4,7)}-${raw.substring(7,11)}`;
}

                    

This uses JavaScript’s template capabilities to evaluate inline expressions to format the result string. One method uses a “search” feature to search for available numbers given an area code and exchange. The other method simply lists the numbers that you have already configured in your Flowroute account.

var searchNumbers = function (err, numberList) {
  if (err) {
    console.log(err);
  }
  else {
    for (var num in numberList.tns) {
      var entry = numberList.tns[num];
      console.log(formatNumber(num), 
                  'for', 
                  '$' + entry.initial_cost,
                  'then',
                  '$' + entry.monthly_cost,
                  'per month.');
    }
  }
};

var listMyNumbers = function (err, numberList) {
  if (err) {
    console.log(err);
  }
  else {
    for (var num in numberList.tns) {
      console.log('Your number:', formatNumber(num));
    }
  }
};

                    

Add the commands:

program  .command('listNumbers  ')
  .action(function (areaCode, exchange) {
    configure();
    flowroute.PurchasablePhoneNumbersController.search(
      itemsPerPage,
      areaCode,
      exchange,
      1,
      null,
      null,
      null,
      searchNumbers);
  });

program
  .command('listMyNumbers')
  .action(function () {
    configure();
    flowroute.TelephoneNumbersController.listAccountTelephoneNumbers(
      itemsPerPage,
      1,
      null,
      listMyNumbers);
  });

                    

Then call the method. Figure 5 shows an example run to list numbers in area code 813 with exchange 321:

Figure 5: List Numbers

Use the listMyNumbers command to see what numbers are already in your account.

Conclusion

The Flowroute API is extremely flexible and the SDK makes it easy to build custom functionality to interact with your account. The Flowroute Command Line Interface demonstrates how a little code can produce helpful utilities to boost productivity. This example just scratches the surface of what is possible. Potential enhancements include building support for paging long lists and allowing you to purchase and route new numbers directly from the command line.