Julian Cates

Adventures in Node.js with the NimbleOS API

Blog Post created by Julian Cates Employee on Sep 27, 2016

I've done a lot of work with the NimbleOS API over the past year, primarily with PowerShell or Curl.  So when one of our systems engineers asked for guidance using the API with Node.js, I found myself in the frustrating position of knowing the API itself, but being entirely unfamiliar with the mechanics of making the API calls from JavaScript, a language I'm not overly familiar with.  The following script is the result of a few hours of Google, trial and error, and consulting with programmer types much smarter than myself.  I particularly want to thank Richard Carter for helping me understand control flow using callback functions, and also for his troubleshooting assistance.  So this isn't a master class on JavaScript API programming by any means, but I figured some folks might appreciate an example to work from if they were ever to try their hand at the Nimble API with Node.js.  The following example script will grab an authentication token from the array, and then use it to retrieve a list of volumes.  Enjoy!

 

P.S. I may have mentioned that I'm no JavaScript master.  Feel more than welcome to post an improved version if you'd like!

 

var https = require('https');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

 

function getToken(callback) {

 

  var token;

  var body = JSON.stringify({

       "data" : {

       "username" : "admin",

       "password" : "<YOUR PASSWORD HERE>"

  }

  });

  

  var options = {

       host : '<YOUR ARRAY HERE>',

       port : 5392,

       path : '/v1/tokens',

       method : 'POST',

       agent: false,

       headers : {

            'Content-Type' : 'application/json',

            'Content-Length' : Buffer.byteLength(body, 'utf8')

       }

  };

  

  var req = https.request(options, function (res) {

  res.on('data', function (d) {

  var parsed = JSON.parse(d);

  token = parsed.data.session_token;

  callback(token);

  });

  });

  

  req.write(body);

  req.end();

  req.on('error', function (e) {

  console.error(e);

  });

}

 

function getVolumes(token) {

 

  console.log("Using token: " + token.toString());

 

  var options = {

       host : '<YOUR ARRAY HERE>',

       port : 5392,

       path : '/v1/volumes',

        agent: false,

       headers : {

            'X-Auth-Token' : token

       }

  };

  

  callback = function(response) {

  var str = '';

 

  response.on('data', function (chunk) {

  str += chunk;

  });

 

  response.on('end', function () {

  console.log(JSON.parse(str));

  });

 

  }

 

 

  var req = https.request(options, callback);

 

  req.on('error', function (e) {

  console.error(e);

  });

 

  req.end();

}

 

 

getToken(getVolumes);

Outcomes