Get data from external API

Posted on



var employees = require('../models/employees');, function(body) {


var request = require('request');

var employees = {

    read: function(id, callback) {
            .get('' + id, function(error, response, body) {
                body = JSON.parse(body);
                return callback(body);

module.exports = employees;

This works (returns the employee name correctly), but I’m not sure if this is the correct (async) way of getting data from an API and displaying it.


You didn’t implement any error handling. Before doing something with the api response body, you should check if an error occured. Also the callback function of your read method should use the error first pattern. Here is a very short explanation:

Further, JSON.parse can throw an error if your api doesn’t respond with a valid json string. So you might want to handle this error, too. Just add a try-catch block.

Leave a Reply

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