- Using npm. A good resource. npm will get installed with NodeJS itself.
- Basic knowledge of command line or terminal.
Essentially, we are going to use the requests library to make an API call to fetch data from an external source and use that data as we like. The final app has output like this:
The npm modules we are going to use are:
Project setup : To implement the above application demo, create a demo folder and create a .js file in it. You can use the below method to create a folder and the .js file
npm install the required modules : In your terminal, run the following command:
npm install cowsay request --save
The above command will install the modules necessary to implement the application.
- express module is a web framework
- cowsay module provides the cow with the cavity which we will fill with the data fetched from the API
Code and Explanation
The gfg.js looks like this:
Request module is designed to be the most simple way to make HTTP calls. Almost all the programming languages have a Request module which is used to fetch and post data from and to a server respectively.
Explanation of Code in gfg.js
- Step 1 : We ‘require’ request and cowsay module that we installed earlier using
npm install request cowsay --save
- Request module will help us in making HTTP calls to fetch data.
- Cowsay will provide the cow cavity which we will fill
- Step 2 : We call the request method and pass it the url to hit and method(GET)as the first parameter. This is called ‘making an API call’. This method returns the three objects talked about below.
- Step 3 : After the url is GET, the callback function is run with the arguments error, response, body.
All three of them are of type object. In this function, we will write the code to execute(filling the cow cavity with the data returned from the API call) and display it to the user in the terminal.
- Step 4 : We put an if-else conditional inside the callback function. The if checks and runs the code if there is no error( !error ) and the response returned is OK ( response.statusCode = 200 ).
Else it will execute the else code.
- Step 5 : We use the console.log() method to print the cow in the terminal. Inside the console.log() method, we use cowsay.say() method.
We put the text:body inside the cowsay.say() method. This puts the data fetched(body of resonse returned) into the cow cavity.
- Step 6 : We have written the entire code. Now, go to the terminal and write the following command and voila! Your app is working.Command:
The entire code of this article is available here
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.