How to Validate and Look Up Phone Numbers from a CSV file

In a nutshell, MessageMedia Lookups API validates the phone numbers you’re sending to by checking their validity, type and carrier records. In this example, we’ll use Node.js and the MessageMedia Lookups API to validate phone numbers from a CSV file.

 

Prerequisites

In order to work through this tutorial, you need:

 

Create a CSV file

Let’s create the csv file which we will contain the numbers we would like to lookup.
To do this, go to your Desktop and create a folder called lookups. Inside this folder, create a csv file called numbers. Open this csv file and in the first row of the first column, type in Number and add the phone numbers under this column. These numbers should be valid or else the lookup will fail.

 

 

Initialise project

Before we can start writing any code, we need to initialise our project. It’s quite simple to do. Open up command line from the root directory of your project (lookups) and run “npm init”. You can leave the options blank and press Enter when prompted with “Is this ok? (yes)”

 

Install modules

To keep our script concise, we’ll use a few essential third-party modules – csv-parser, request and fs. request is a handy module to make HTTP calls. csv-parser takes in csv and gets the rows out as object. fs is the Node.js file system module that allows you to work with the file system. This is already built in to Node so you won’t have to separately install it. To install the other modules, run the following commands separately on your command line:

npm install request
npm install csv-parser

 

Read data from csv

We’ll write our code in a file called index.js. Save this file in the Lookups folder. Let’s take a look at how we can read data from the csv file.

var csv = require('csv-parser');
fs.createReadStream('numbers.csv')
  .pipe(csv())
  .on('data', function (data) {
      console.log(data.Number);
});

 

And this what they output would look like:

 

Authentication and lookup number

To actually lookup a number you need to make a call to the Lookups API and to do that you’ll need authentication. We can use the API Key and secret that were sent to you when you signed up.

var request = require('request');

// Replace key and secret with your actual ones
var key = "xx";
var secret = "yy";
var auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");

function lookup(number){
    var url = "https://api.messagemedia.com/v1/lookups/phone/"+number+"?options=carrier%2Ctype";
    request({
            url : url,
            headers : { "Authorization" : auth }
        },
        function (error, response, body) {
            var phone_number = JSON.parse(body)["phone_number"]
            var type = JSON.parse(body)["type"];
            var carrier = JSON.parse(body)["carrier"]["name"];
            var country_code = JSON.parse(body)["country_code"];
            console.log(phone_number + " " + type + " " + carrier + " " + country_code);
        }
    );
}

Write to file

function writeToFile(phone_number, type, carrier, country_code) {
  var dataToWrite = phone_number+","+type+","+carrier+","+country_code+"\n";
  fs.appendFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('Lookups information added successfully.');
    }
  });
}

 

Add headers before writing to file

Our output csv file does not contain any headers. Let’s add some in. We will call this function before we start looking up numbers so that the output file is already created with the headers.

function createFile(){
  var dataToWrite = "Phone Number,Type,Carrier,Country Code\n";
  fs.writeFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('File created and headings added.');
    }
  });
}

 

Putting it all together

We’ve cleaned up our code and made it look pretty and modular.

var csv = require('csv-parser');
var fs = require('fs');
var request = require('request');

var key = "xx";
var secret = "yy";
var auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");

// Entry point
start();

function start(){
  // Create file and insert headers
  createFile();
  // Read numbers from file and perfom lookup on each function
  fs.createReadStream('numbers.csv')
    .pipe(csv())
    .on('data', function (data) {
        lookup(data.Number);
    });
}

// Make call to Lookups API and return data to writeToFile function
function lookup(number){
  var url = "https://api.messagemedia.com/v1/lookups/phone/"+number+"?options=carrier%2Ctype";
  request({
          url : url,
          headers : { "Authorization" : auth }
      },
      function (error, response, body) {
          var phone_number = JSON.parse(body)["phone_number"]
          var type = JSON.parse(body)["type"];
          var carrier = JSON.parse(body)["carrier"]["name"];
          var country_code = JSON.parse(body)["country_code"];
          writeToFile(phone_number, type, carrier, country_code);
      }
  );
}

// Fill in the lookup details of the number in the csv file
function writeToFile(phone_number, type, carrier, country_code) {
  var dataToWrite = phone_number+","+type+","+carrier+","+country_code+"\n";
  fs.appendFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('Lookups information added successfully.');
    }
  });
}

// Create and add headers to the file
function createFile(){
  var dataToWrite = "Phone Number,Type,Carrier,Country Code\n";
  fs.writeFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('File created and headings added.');
    }
  });
}

 

Run the tutorial

Run node index from the root directory. In our case we’ve only have one number in the numbers.csv file.

 

 

Conclusion

Well done – you have learnt how to lookup numbers from a csv file and output the details into a separate file.

Get the code

All the code for this tutorial is available in the Lookups CSV Tutorial Github repo

Resources