rfc1484 rfc1484 - 6 months ago 53
reST (reStructuredText) Question

REST client in node.js

I'm fairly new to node.js and I'm trying to make a simple node.js REST client to act as an SDK between an API and a larger application.

This is the current code in the client SDK part corresponding to


var unirest = require('unirest');
var config = require('config');

var host = config.get('api.host');

unirest.get(host + '/api/products?_format=json')
.headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
.end(function (response) {
module.exports.getProducts = function() {
return response.body;

If I execute in the terminal:
node index.js
command returns the expected result from the API call

However if I install the package in the main project (as a local dependency) it does not seem to work.

Here is the code from the
in the main project:

var SDK = require('api-sdk-js');

var result = SDK.getProducts;

In this case when I execute
node index.js
command returns
for the
variable, I suspect this is due to the
call in the SDK being asynchronous so it returns the value before there is a response.

I'm not sure how to fix this, any suggestions?

Alternatively it would also work for me a good example of a REST API client in node.js as an SDK (i.e., as a package able to be installed from another project).


Your unirest call should really be inside your module.exports.getProducts method.

Due to the call being asynchronous, you can't just return from it. You need some sort of callback.

module.exports.getProducts = function(callback) {
    unirest.get(host + '/api/products?_format=json')
        .headers({'Accept': 'application/json', 'Content-Type': 'application/json'})
        .end(function (response) {

You'd then use it like so:

var SDK = require('./api-sdk-js');
SDK.getProducts(function(products) {
     console.log(products); // Should contain data from the callback

Read How do I return the response from an asynchronous call? for other alternatives to asynchronous JavaScript.