Skip to content

Instantly share code, notes, and snippets.

@dexterlabora
Last active July 18, 2019 00:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dexterlabora/fef1f7de9ab4d95d68efa89763ed5cfd to your computer and use it in GitHub Desktop.
Save dexterlabora/fef1f7de9ab4d95d68efa89763ed5cfd to your computer and use it in GitHub Desktop.
A Meraki Dashboard API request wrapper to follow 301/302/307/308 redirects properly.
// Handles Meraki API requests. Has additional logic to follow the HTTP redirects properly and handle OrgID being converted to INTs
var request = require("request");
var JSONbig = require("json-bigint")({ storeAsString: true });
// Recursive function to follow Meraki API redirects
var requestMeraki = function(options, callback) {
request(options, function(error, res, data) {
//console.log('RESPONSE [ ' + res.statusCode + ' ]');
if (error) {
return callback(error);
} else {
if (
[301, 302, 307, 308].indexOf(res.statusCode) !== -1 &&
res.headers.location
) {
console.log("REDIRECT: (recursive function)");
options.url = res.headers.location;
return requestMeraki(options, function(err, res, data) {
return callback(err, res, data);
});
} else {
// parse the large integers properly if data exists
try {
var parsedData = JSONbig.parse(data);
return callback(error, res, parsedData);
} catch (e) {
console.log("error: no data returned ", error);
}
//console.log("FINISHED")
return callback(error, res, data);
}
}
});
};
module.exports = requestMeraki;
@dexterlabora
Copy link
Author

dexterlabora commented Dec 10, 2017

Example of using the request-meraki module:

var requestMeraki = require('./request-meraki');

var apiKey = 'YourAPIkey';
var orgId = 'YourOrgID';

var jsonAdminData = {
    "name":"test meraki request",
    "email":"test@internetoflego.com",
    "orgAccess":"none",
    "tags":[
      {
        "tag":"west",
        "access":"read-only"     
      }
    ]
  }

// Set Options
var addAdminOptions = {
    qs: '', 
    url: 'http://api.meraki.com/api/v0/organizations/'+orgId+'/admins',
    method: 'POST',
    body: JSON.stringify(jsonAdminData),
    headers: {
        'X-Cisco-Meraki-API-Key': apiKey,
        'Content-Type': 'application/json'
    } 
}

requestMeraki(addAdminOptions, function(err, res, data){
    if(err){
        console.log('FINAL err ',err);
        return;
      }
      console.log('FINAL res.statusCode ',res.statusCode);
      console.log('FINAL res.body ',res.body);
      console.log('FINAL data ',data);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment