Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Node.js to connect to a REST API

Is it sensible to use Node.js to write a stand alone app that will connect two REST API's?

One end will be a POS - Point of sale - system

The other will be a hosted eCommerce platform

There will be a minimal interface for configuration of the service. nothing more.

like image 497
AndrewMcLagan Avatar asked Apr 22 '13 13:04

AndrewMcLagan


1 Answers

Yes, Node.js is perfectly suited to making calls to external APIs. Just like everything in Node, however, the functions for making these calls are based around events, which means doing things like buffering response data as opposed to receiving a single completed response.

For example:

// get walking directions from central park to the empire state building
var http = require("http");
    url = "http://maps.googleapis.com/maps/api/directions/json?origin=Central Park&destination=Empire State Building&sensor=false&mode=walking";

// get is a simple wrapper for request()
// which sets the http method to GET
var request = http.get(url, function (response) {
    // data is streamed in chunks from the server
    // so we have to handle the "data" event    
    var buffer = "", 
        data,
        route;

    response.on("data", function (chunk) {
        buffer += chunk;
    }); 

    response.on("end", function (err) {
        // finished transferring data
        // dump the raw data
        console.log(buffer);
        console.log("\n");
        data = JSON.parse(buffer);
        route = data.routes[0];

        // extract the distance and time
        console.log("Walking Distance: " + route.legs[0].distance.text);
        console.log("Time: " + route.legs[0].duration.text);
    }); 
}); 

It may make sense to find a simple wrapper library (or write your own) if you are going to be making a lot of these calls.

like image 119
Robert Mitchell Avatar answered Sep 28 '22 07:09

Robert Mitchell