Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Node.js: Retrieving JSON Data from Web Services

Node.js is one of the strongest frameworks of nowadays, and its functionalities go further than simply executing JavaScript on server side, but also allowing Web Services consumption. Here, well see how to consume a WS with JSON and Node API.

JavaScript is everywhere, from modern browsers to mobile phones. It is also very useful in building modern web applications from scratch.

In this article, we’ll use Node.js in the backend to collect information about different users . The application will be command line so you’ll also learn how to use Node.js from command line or terminal.

Installing Node.js on your machine

Head over to https://nodejs.org/download/ and download the required package for your Operating System and simply install the package similar to installing a software on your machine.

While installing Node.js make sure that ‘npm’ installation is checked. npm is node package manager and is used to install different packages to be used by Node.js applications.

Figure 1. Download page of Node.js

Figure 2. Make sure to install npm

After you’ve installed node.js, open up a terminal on your machine and type

=> node -v and press Enter.

You’ll see the current version of node.js installed on your machine.

=> npm -v and press Enter.

You’ll see the current version of npm installed on your machine.

If the above two steps are executed successfully, then you’ve installed node.js and npm on your machine. If not, then repeat all the steps again or post comments in the discussion to solve your problem.

Hello World with Node.js

Open up any text editor and create a file named “app.js” and write the following line of code!

console.log("Hello, World");

console.log in JavaScript is used to log or print a line of text on the command line or terminal. In this case we’re writing “Hello, World” in our console.

Open up the terminal and make sure you’re on the desktop (if your app.js file is in desktop) and type the following command:

Figure 3. Executing example via cmd

To run the application on Node.js platform we’ll use “node filename.js”.In this case we’re using node app.js because the name of our file is app.js. So, here you can see that we’ve got the output “Hello, World.”

We’ve created our simple application in Node.js which logs Hello world on the console. Now it’s time to write an application capable of retrieving information from the web.

Starting with our Node.js application

We’ll build a command line application that will get student’s badge count and points from team treehouse website.

If we use ‘.json’ at the end of the url then our browser will display a JSON (JavaScript Object Notation ) page. This page contains all the information that we’ve got using our Node.js application:

{  
   "name":"Josh Timonen",
   "profile_name":"joshtimonen",
   "profile_url":"https://teamtreehouse.com/joshtimonen",
   "gravatar_url":"https://uploads.teamtreehouse.com/production/profile-photos/1219982/thumb_1477348_10152811260403256_2086453396790167473_n.jpg",
   "gravatar_hash":"abd6c54523a6579429b88b82b58c595f",
   "badges":[  
      {  
         "id":49,
         "name":"Newbie",
         "url":"https://teamtreehouse.com/joshtimonen",
         "icon_url":"https://achievement-images.teamtreehouse.com/Generic_Newbie.png",
         "earned_date":"2014-07-04T17:15:53.000Z",
         "courses":[  

         ]
      },
      {  
         "id":1662,
         "name":"Intro to Sprite Kit",
         "url":"https://teamtreehouse.com/library/build-a-game-with-sprite-kit/intro-to-sprite-kit",
         "icon_url":"https://achievement-images.teamtreehouse.com/badges_iOS_SpriteKit_Stage1.png",
         "earned_date":"2014-08-14T00:20:38.000Z",
         "courses":[  
            {  
               "title":"Build a Game with Sprite Kit",
               "url":"https://teamtreehouse.com/library/build-a-game-with-sprite-kit",
               "badge_count":1
            },
            {  
               "title":"Intro to Sprite Kit",
               "url":"https://teamtreehouse.com/library/build-a-game-with-sprite-kit/intro-to-sprite-kit",
               "badge_count":1
            }
         ]
      },
      // ...
   "points":{  
      "total":551,
      "HTML":0,
      "CSS":0,
      "Design":1,
      "JavaScript":345,
      "Ruby":0,
      "PHP":0,
      "WordPress":0,
      "iOS":151,
      "Android":0,
      "Development Tools":0,
      "Business":18,
      "Python":0,
      "Java":0,
      "Digital Literacy":0
   }
}

The above two screenshots of the url : https://teamtreehouse.com/joshtimonen show the JSON data and here we can easily see that there is an array of badges which contains all the information of different badges earned by the user. In the second screenshot we can see that there is a JavaScript Object named as ‘points’ and inside this object we can see all different skills of the user with his/her respective point.

So, our problem is divided into these sub-parts =>

  1. Connect to the API url ( we’ve done this in the above step )
  2. Read the data.
  3. Parse the data.
  4. Print the data on the console

In the next section, we’ll start with reading the data with the help of Node.js modules.

Reading the data from the API

We’ll use one of Node.js built in module ‘http’ to go out and make a GET request.

First, we’ll start by building a function which will print out our final result on the console. We’ll print the total badge count and the total points in JavaScript. We can fetch any information from the JSON which we are using!

function printMessage(username, badgeCount, points){
	var message = username + " has " + badgeCount + " 	total badge(s) and " + points + " points in JavaScript ";
	console.log(message);
}

This printMessage function will take username, number of badges and points in JavaScript as arguments. In return, it’ll print a message saying “Username has badgeCount total badge(s) and points points in JavaScript.”. Username, badgeCount and points will be replaced by the name of the user, his/her badge count and total points in JavaScript!.

Now we’ll use ‘http’ module of Node.js to retrieve data from the web.

var http = require('http');


function get(username){
	var request = http.get("http://teamtreehouse.com/" + 	username + ".json", function(response){


	var body = "";


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

In the above screenshots of our file app.js we’ve first included the http module of Node.js using the statement => var http = require(‘http’);

So, this will include the http module in our file. In the next block of code we’ve created a function called ‘get’ which takes username as argument. This function will go to the web and will fetch all the information which was in the JSON file and will store it in a variable called ‘body’.

We’ve first initialized the variable ‘body’ as an empty string. We’ve created a variable called request which will call the ‘get’ method of the http module.

The first argument takes the URL of the webpage and the second argument is a callback function of JavaScript which takes response as an argument.

We are storing the information in the variable called body. When we transfer data from the web, the information is passed in the form of small chunks of data and we’ve used response.on, which will again and again receive the small chunk of data from the treehouse API. In the next line, we’ve used => body += chunk. This statement will append the received information in the variable body again and again until we’ve manually stopped the process.

So, in the next step we’ll use another response to stop the response when the data transmission is finished.

response.on("end", function(){
	if(response.statusCode === 200){
	try{
	var profile = JSON.parse(body);
	printMessage(username, profile.badges.length, 	profile.points.JavaScript);
}

Make sure to add this piece of code inside the get function that we’ve created earlier.

We’re again using response.on to check whether we’ve reached the end of the data transmission. As soon as whole data is transmitted, the status code will be 200 ( Status code for success is 200 ). Now we’ll use an if block to check whether the status code is 200 or not. If the status code is not 200, that means there is some error in our application and we’ll deal with this part later in this article.

First let’s assume that the status code is 200 in this case. response has a method called statusCode which stores the status code of the response. So we’ll check whether the status code is 200 with the help of an if block in JavaScript.

Inside the if block we’ll parse the data received to convert it into useful information. We’ll look into this in the next section.

Parsing the received data

We’ve the response as a string but we need to convert it into an object so that we can access the data more programmatically. The process of converting a string into a data structure is called parsing. You may not know this, but if you look in the documentation on how to parse JSON, it is not found as host object in the Node.js environment. It is actually a native object. A good reference for native object is MDN.

There is a method called JSON.parse() where you can pass in a string and it’ll return a parsed JSON Object.

Let’s write the code for this part of our application.

response.on("end", function(){
	if(response.statusCode === 200){
	try{
	var profile = JSON.parse(body);
	printMessage(username, profile.badges.length, 	profile.points.JavaScript);
}
	catch(error){
		printError(error);
	}
}
else{
	printError({message: "There was an error getting profile 	for " + username + "."})
}
	});
});

Here we are using exception handling to deal with the errors.

Inside the try block we’re creating a variable called ‘profile’ which will store the parsed string.

var profile = JSON.parse(body) will parse the information stored in the variable body and convert it into a JSON object and store it in the variable profile.

In the next step, we’re calling the function printMessage which we’ve created earlier to print the required information on the console. You can see the profile is now a JSON object and we are using profile.badges.length to calculate the length of the badges array (length of badges array will be equal to the total number of badges earned. You can see the JSON for more clarity). In the next argument we’re using profile.points.JavaScript to get the total points in JavaScript domain.

The first argument is ‘username’. We can either directly pass the name of the user or we can opt this method.

var username = ‘joshtimonen’;

The above statement will store the name of the user in the variable username and then we can pass the variable ‘username’ as argument.

Now it’s time for catching some errors!!

If there is an error parsing the string into JSON object, then try block will throw an error and catch block will accept that error and in return it will call a function printError, which is used to print the error on the console. The function printError is =>

function printError(error){
	console.error(error.message);
}

This printError function will accept the error as argument and then in return it’ll print the error on the console. The error object has a method called message which will print the information about the specific error automatically on the console.

Remember that we’ve assumed that the status code is 200 always. What if it’s not 200? Then, we’ll not enter the if block and in the else block we’ll call the printError function!.

Completing the application

module.exports.get = get;

At the end of our app.js file we’ll add this line of code so that we can use the methods of this file in different files.

We’ll create another file named profile.js and add these lines of code.

var profile = require("./app");
var users = process.argv.slice(2);
users.forEach(profile.get);

We’re including our app.js file in profile.js and then we are using process.argv to get the name of the users from command line, and then we’re iterating with the help of forEach loop to get information about different users.

So We’ve built our first Node.js application.

Sample Output =>

Source code available at => https://github.com/samarth4487/studentInformation, or at the top of this page as a zip file.

Conclusion

This is only a small piece of all the power Node.js can give us. Please refer to the official documentation of the framework and check the other samples it has available. With this, you'll have all the necessary inputs to create your own apps.



CODING is my Passion first, hobby second and job third! I am Full Stack Developer from last two years and I love building scalable web applications and modern websites with new technologies.I started with my web development with ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login