Node Rest Client

Making REST calls
Each API call takes a set of data in JSON format and returns data also in JSON format. The exception to this is a GET request, which instead takes its data as a query string. I didn’t want to have to deal with this detail, so I cobbled together a wrapper function that would produce data in the correct format and issue the request.

var querystring = require('querystring');
var https = require('https');

var host = 'www.thegamecrafter.com';
var username = 'JonBob';
var password = '*****';
var apiKey = '*****';
var sessionId = null;
var deckId = '68DC5A20-EE4F-11E2-A00C-0858C0D5C2ED';

function performRequest(endpoint, method, data, success) {
  var dataString = JSON.stringify(data);
  var headers = {};
  
  if (method == 'GET') {
    endpoint += '?' + querystring.stringify(data);
  }
  else {
    headers = {
      'Content-Type': 'application/json',
      'Content-Length': dataString.length
    };
  }
  var options = {
    host: host,
    path: endpoint,
    method: method,
    headers: headers
  };

  var req = https.request(options, function(res) {
    res.setEncoding('utf-8');

    var responseString = '';

    res.on('data', function(data) {
      responseString += data;
    });

    res.on('end', function() {
      console.log(responseString);
      var responseObject = JSON.parse(responseString);
      success(responseObject);
    });
  });

  req.write(dataString);
  req.end();
}

https://rapiddg.com/blog/calling-rest-api-nodejs-script

https://www.npmjs.com/package/node-rest-client

Share

Leave a Reply

Your email address will not be published. Required fields are marked *