Open In App

Stock Market API Integration in Node.js

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to build a simple web application, in which we would learn how we can integrate a simple API with NodeJS and fetch data from the server using that API.

Here, we will learn about what API is, how to get data from the Server using that API and all the stuff related to that, and how you can integrate any API with your web application.

Things we will cover in this article:

  • We will learn a bit about what actually API is, why it is used, and the process that occurs when we use API.
  • We will gain some knowledge about JSON format(which is a notation to store, and transport data), and everything related to that.
  • We will search for the Stock Market API that we will use in our Application
  • We will learn how we can fetch data by calling an API.
  • Then, we will create a simple Nodejs application, and step by step(in which we will integrate the Stock Market API), we will make improvements to it and will reach our final application.

The application that we will make is going to be very simple. It will allow the user to get the data of any particular stock, and we will use our API to fetch the data from the Stock Market Server and display that to our user. The application is basic, but, once you learn how we can create an application by integration of the API, you can create complex applications and try different APIs of your choice.

Prerequisite: So before proceeding further, you should know some basics about the following terms.

API: Consider a simple example of a restaurant. When you visit a restaurant, you do not directly place the order to the cooks in the kitchen. Rather, we tell our requirements to the waiter who eventually communicates and delivers the message to the chef in the mess. The waiters serve as an interface between you and the Cooks in the kitchen. The work of API is similar to that of waiters in the restaurant.

API stands for application programming interface, which means it is an interface or a middleware that allows us to connect two different computers or services.  

Mobile applications/websites are widely used to book train and flight tickets nowadays. These applications basically use APIs in order to send and receive data from the database.

Consider an example of the Stock Market Database, containing the data related to Stock Performance of various companies(including the current price, the highest price of the day, etc.). Our Web application can not directly request and get data from the database, rather, we have to use some API to communicate with the database. So if we want to fetch the data related to any particular stock, the process that occurs can be divided into four steps:

  • Our application tells the API that we want data related to a particular Stock.
  • API accepts the request and sends it to Server/Database.
  • The data relating to the Stock is sent back to API from the Server/Database.
  • The API finally delivers us our required data.

This is how API acts as an intermediate between us(the mobile/web application user) and the Server/Database.

A very simple Representation of how API works

JSON (JavaScript Object Notation): JSON or JavaScript Object Notation is a format to represent, store and transport data. JSON data is very easy to understand and is human-readable. The data is stored in form of key-value pairs, similar to JavaScript Objects and these key-value pairs are separated by commas.

Example: A simple example of JSON Object.

{
    "name" : "YourName",
    "age"  : 22,
    "isMarried" : false,
    "education" : [
                    {"BTech" : "College1"},
                    {"MTech" : "College2"}
                  ]
}

This is a simple example of Data stored in JSON format. Here, “name”, “age”, “isMarried’’ and ‘’education” are the keys and data written after a semicolon (:) are the values corresponding to the keys.

Keys must be of type String, but the values can be of any type. (Number, Character, String, Array, Boolean or Another JavaScript Object)

A dot (.) is used to get the value associated with any key. For example, if we want to get the value associated with the “name” key, we would write “theObjectGivenAbove.name”.  

 var name = theObjectGivenAbove.name;

Similarly, if we want to get the value associated with the “age” key, then we would write “theObjectGivenAbove.age” in order to get the value associated with the “age” key.

Note: Here, the value corresponding to the “education” key is an Array of Objects. So “theObjectGivenAbove.education” will return an Array of Objects(which contain key-value pairs) and not a single value. Suppose we want to get the value corresponding to the ‘’BTech” key. Here we will have to follow these steps:

  • We will first obtain the Array associated with the key “education”.

    var educationArray = theObjectGivenAbove.education;
  • Now we have got the Array, we will obtain the first element of the Array obtained above.

    var firstElementOfEducationArray = educationArray[0];
  • The element that we have got is an object(“BTech”: “College1”), and in order to get the value corresponding to the “BTech” key, dot(.) will be used.

    var requiredValue = firstElementOfEducationArray.BTech;

The value associated with the BTech key is obtained by following the steps shown above. Combining all three, we get:

var educationArray = theObjectGivenAbove.education;
var firstElementOfEducationArray = educationArray[0];
var requiredValue = firstElementOfEducationArray.BTech;

 

Consider one more example:

{
    "nameOfPerson" : "Mike",
    "age"          : 29,
    "isEmployed"   : "Birla Innovation Group",
    "partner"      : {
                        "name" : "Jenny",
                        "age"  : 28,
                        "isEmployed" : "BlueRay Technologies"
                        }
}

In the above pre tag, a JSON object is shown with some key-value pairs. One thing to note here is that the value associated with the “partner” key is an object itself. Suppose we want to find the name of the partner of “Mike”(obtaining the value of the “name” key from the partner object), we can follow the below-listed steps:

  • Obtain the Object associated with the “partner” key

    var partnerObject = objectGivenAbove.partner;
  • Now we have got the object corresponding to the “partner” key, we will use dot(.) again to get the value corresponding to the “name” key from partnerObject.

    var nameOfPartner = partnerObject.name;

Similarly, we can obtain value corresponding to any key in the entire object.

The reason why we are focusing on JSON is that the data which is obtained using API, is in the JSON format, so it’s better to have some knowledge about reading and obtaining data in this format. Now we are familiar with these basic terms, let’s proceed further.

Building our Application: Now we know what an API does, but where is the API which we could use in our Application. Luckily, there is a lot of free APIs available on the Internet which allows us to communicate with the Server or Database of a large Organization or Company.

The API we are going to use here is from the website named RapidAPI.com, and the name of the API is ‘’Latest Stock Price”, which will allow us to fetch the data of the stocks which are listed on the National Stock Exchange(NSE).

You need to follow the steps given below in order to get access to API:

Step1: Navigate to the RapidAPI website or open RapidAPI.com, Log in and search for Latest Stock Price API in the search bar

Logging in the RapidAPI.com and finding the API we are going to use. 

Step2: You will come to the API playground page where the necessary details of API will be listed. (A page which is shown in the image below)

API Dashboard

Step3: For every developer who is using the API for integrating with the code, a unique API key is allocated. For example, if I want to integrate the latest stock price API in my web application, I will be provided with a unique API key, which will be required to communicate from the server/database using that API.

On the right bottom corner, there is a section as shown in the image below:

  1. This combined black box represent the entire details related to the API including the API key, about the API, and how we are going to communicate with the database.

  2. GET’ Represents that we are only going to fetch the data from the database and are not going to send or post any data to the Server/Database.

  3. Represents the URL of API, which is the address or link that allows us to access the API and its features and functionalities.

  4. Represents that we are going to fetch data related to NIFTY50 or 50 companies listed on National Stock Exchange.

  5. Represents our unique API key.

So now we have got our API and API key, we can use these details in our Web Application.

Setting up our NodeJS App: If you are not familiar with the basics of NodeJS, you can have a look at the following article https://www.geeksforgeeks.org/introduction-to-node-js/

Follow the steps given below to set up our App.

  1. Create a new folder named “StockMarketAPI”.

  2. Create a new file with the name “Server.js”.

  3. Open terminal/GitBash in the folder and run the command given below.

    npm init -y

    Project Structure: The above command is used to initialize npm in our Project Folder. As of now, the project structure should look like this:

    Project Structure

  4. Now, we have initialized npm. The next step is to install the node modules which we would need in our project. To use the API in our project, we would use a node package named “axios”. Run the following command to install the package.

    $npm i axios

    Project Structure: Now the project folder should look like this:

    Project Structure after you install the package “axios”

Now we have got the API details, initialized npm, and installed axios, we can now move forward to write code that allows us to fetch the details from the Stock Market Database, using our API.

 

Follow the steps given below:

  1. First, we would have to tell our NodeApp that we are going to require the node package “axios”. For that, we have to write the code given below in our Server.js file. By writing this simple one-line given below, we allowed Node to use the package named “axios” in our application.

    var axios = require(“axios”).default;
  2. 2. Now after this step, we have to copy and paste the options variable that was given in the API dashboard.

    Details related to the API in a variable named “options”

    You can either copy the code given below or copy it from the API dashboard. The code below is nothing but a simple variable named “object”, which contains the details of the API we are using. We have made a variable named “options”, which contains all the details related to the API we are using.

    Javascript




    var options = {
     method: 'GET',
     params: {Indices: 'NIFTY 50'},
     headers: {
       'x-rapidapi-host': 'latest-stock-price.p.rapidapi.com',
       'x-rapidapi-key': 'YOUR API KEY’
     }
    };

    
    

  3. Now we have to write code that will allow us to fetch the data from the database using the API. The code below is basically the part where we are getting the response from the Database after making a request through API.

    We are using the “axios” package to request from the server the data related to different stocks using our API.

    Javascript




    axios.request(options).then(function (response) {
     var dataFromResponse = response.data;
     console.log(dataFromResponse);
    }).catch(function (error) {
     console.error(error);
    });

    
    

In the code above, we are using the options variable for making a request to the server/database using the installed package named axios.  

.then’ represents that after we have made the request through axios, a call-back function is called which has the “response” as the parameter, which we have got from the server/database, and log whatever data we have got from the response.

.catch’ is to detect if there is an error in the request that we have made, or if there is some problem in the response from the server, and log whatever error has occurred.

Server.js: The entire code in the Server.js file would look like this.

Server.js




var axios = require("axios").default;
var options = {
 method: 'GET',
 params: {Indices: 'NIFTY 50'},
 headers: {
   'x-rapidapi-host': 'latest-stock-price.p.rapidapi.com',
   'x-rapidapi-key': 'YOUR API KEY'
 }
};
  
  
axios.request(options).then(function (response) {
  var dataFromResponse = response.data;
  console.log(dataFromResponse);
 }).catch(function (error) {
  console.error(error);
 });


Run Code: Now, start the server by executing the command given below:  

$node server.js

As soon as we hit Enter, we will see that very large data from the response received from the database is logged in the command line. This is because when we started the Server, all the code which was written in Server.js was executed, which included our communication with the database/server using the API, and we have also written the code to log all the response data that we have got from the Server, so the data we got from the API call is logged in the console.

You will see a response similar to this in your command line/terminal

The data would look like as shown in the image above.

There are two things to be noted:

  1. The data we have got from the server/database is a JSON Array, and now, from our previous knowledge, we can fetch values corresponding to any key in the entire Array.

  2. The Array obtained from the API response include the details related to the shares of companies listed in the National Stock Exchange.

Every object in the Array has a key named “symbol”, the value of which represents the symbol of the Stock to which the data is related.

So, for example, we want to fetch the details only related to ‘RELIANCE’ (ith element of Array in the object) for the present day, then we have to write dataFromResponse[i] in order to get the required details. Now, if we run the Server again using the command “node server.js” in the command line, this time, instead of a larger data, we will get only the data that is related to the ‘RELIANCE’.  

If we want to see the opening price of some other stock, say WIPRO(kth element in the Array), firstly we have to fetch the entire object using:

var wiproObject = dataFromResponse[k];

Then, using the dot(.), we can get the value corresponding to the key “open”, using:

var openingPrice = wiproObject.open;

We can log the opening price using:

console.log(openingPrice);

Similarly, we can find any data related to any stock listed in National Stock Exchange by obtaining the value associated with different keys in our data that we have got as a response from Server.

Providing a Simple User Interface:  For that, we have to make an HTML page with a simple form tag, which will have a drop-down where all the stocks will be listed. Once the user selects any stock and clicks the search button, a post request will be generated, and we will have to write code to handle that post request and provide appropriate data to the user.

Create a new folder named “StockMarketAPIIntegration”. Below is the detailed procedure you have to follow. The first step is related to setting our Node app(installing npm and required packages), and steps 2-8 include the completion of our web app.:

Step 1:

  1. Create a new folder named “StockMarketAPIIntegration”.

  2. Create a new file with the name “Server.js”.

  3. Open terminal/GitBash in the folder and run the command given below:

    npm init -y

The above command is used to initialize npm in our Project Folder.

Project Structure: As of now, the project structure should look like this.

Project Structure – after you create the Server.js file and run the command npm init -y

Step 2: Creating an HTML page with a simple form, containing one drop-down where stocks will be listed. In the code below, we have written the HTML code, where we have created a drop-down, from where the user can choose a stock and get the details related to it.

As the list of top 50 stocks in the NIFTY50 change on a frequent basis, we have only listed a few of those stocks(in the drop-down below) which have been consistently present in the NIFTY’s top 50 stocks list.(Eg. TCS, Infosys, ICICI Bank, etc.)

We are creating an HTML file, containing a form that has a drop-down with only a few stocks listed(so as to make things easy) from where the user can choose any stock and find data related to that, and when the user clicks on submit button, the form sends a post request to “/data” route.

index.html




<!DOCTYPE html>
<html lang="en" dir="ltr">
 <head>
   <meta charset="utf-8">
   <style media="screen">
     body{
       text-align: center!important;
     }
   </style>
 </head>
 <body>
   <h1>Fetch the Data Related to Any Stock</h1>
   <br>
     <h2>Select the Stock</h2>
     <form class="" action="/data" method="post">
         <select class="" name="stockSelected">
             <option value="RELIANCE">
               RELIANCE
             </option>
             <option value="INFY">
               INFOSYS
             </option>
             <option value="TCS">
               TCS
             </option>
             <option value="WIPRO">
               WIPRO
             </option>
             <option value="ICICIBANK">
               ICICI Bank
             </option>
             <option value="ITC">
               ITC
             </option>
         </select>
         <button type="submit" 
                 name="button">
           Fetch Data
         </button>
     </form>
 </body>
</html>


Step3:  Now we have created the drop-down in the form(which makes a post request to the /data route), we can now handle the response associated with the post request on the data route.

For handling get/post requests, we need to install the Express package, and for fetching data from the API(as shown in the article above), will require Axios package and we can install them by executing the command given below in the command line:

You can also use “npm i axios express” in place of “npm install express axios”

Step 4: Now we have installed the required packages, we can now write code in the Server.js file in order to handle requests. Now, we will write the following code in our Server.js file.

In the code written below, we are allowing our app to listen on port 3000. Also, we are handling a simple “get” request on our home route,  and a “post” request on our /data route.

We are writing code inside the Server.js file, where firstly, we are telling NodeJS to include the required packages(axios and express) in our app. Then we are handling a simple get request on the home route(“/”), and send a simple response back. Then we have written the code for the post request which we will use later in our web application.

Server.js




// Add express in our project
var express = require('express');
  
// Creating the express app
var app = express();
  
// The requirement of this package is 
// in the later part of the application
// where we will have to fetch data from server
var axios = require("axios").default;
  
  
// WE ARE MAKING A SIMPLE GET REQUEST ON HOME ROUTE 
// JUST TO MAKE SURE THAT EVERYTHING IS GOING FINE.
  
app.get("/", function(req, res) {
   res.send("We are getting a get request on home(/) route.")
})
  
  
  
// A SIMPLE POST REQUEST ON /DATA ROUTE.
// WE WILL USE THIS IN A WHILE.
app.post("/data"function(req, res) {
   res.send("We have got the post request on /data route");
})
  
// WE ARE ALLOWING OUR APP TO LISTEN ON PORT 3000
var port = 3000;
app.listen(port, function() {
   console.log("Server started successfully at port 3000!");
})


You can test whether everything is fine by restarting the Server. Press “Ctrl+C” or “Command+C” to stop the server, and again write the command “node server.js” to restart the Server.

Output: Now open your browser, and type “localhost:3000” in the address bar, and press Enter. If everything went fine, you will see a result as shown below:

Type “localhost:3000” in your browser and you should see the following response.

Step5: Now we are sure that everything is fine, our goal is to attach the Index.html that we have created in Step2, to the get request, or basically when a user comes to the home route, he/she should be able to see our Index.html file (containing a dropdown from where he/she could select any stock he/she is interested in) which we have made above. Now, we have to write the following code while handling the get request on the home route.

This code will send the “Index.html” file(that we have created in step2) as a response, so the user can select any stock from the drop-down.

Earlier we sent a simple text response back in the get request on the home route(“/’). Now we are sending our Index.html file(which we created in step2 including a drop-down in which stocks are listed) as a response to the user so that the user can select the Stock he wants to seek information about.

The rest of the code is the same as earlier, only the section where we are handling get request is different.

Server.js




app.get("/", function(req, res) {
  
 // This will send the index.html file
 // (containing a dropdown where all stocks are listed) 
 // on our home page as response  
  
       res.sendFile(__dirname + "/index.html");
})


Once again, restart the server, by pressing “Ctrl+C” or “Command+C” to stop, and again write “node server.js” to Start.

Output: Now, if you go to the home route, that is, “localhost:3000” in your browser, you will see our Index.html file(which we created in Step2, which includes a drop-down menu where all stocks are listed.

On the home page, we will see a drop-down menu from where we can select any stock.

Now, on our home route, we are getting our Index.html file, where there is a drop-down menu, where all the stocks are listed. So basically we are handling the “get” request properly. Now, if we click on the “Fetch Data” button, our form will make a post request on the “/data” route, and if you would notice, we have already written the code to handle the “post” request on “/data” route in Step 3, so now, if we click on “Fetch Data” button, our Index.html file will make a post request on the /data route, and the code inside the /data route will be executed, i.e., we will see a response as in the image below:

Step6: Now our App is running well, but the thing is, nothing happens when the user clicks on the “Fetch Data” button from the home route, except a post request is made which displays the sample message. Now, what we have to do is, we have to seek which stock the user has selected, and then we have to call our API and extract the data related to the stock(that user-selected) from the response that has been given back by the API.

For seeking what the user has selected from the form, we have to install the “body-parser” package and write the following code below in order for body-parser to work well.

To install the “body-parser” package, execute the command given below in the command line:

$npm install body-parser

Write the code at the top of the Server.js file, but below the code where we have written the “require” statement for the express package. Here in the code below, we are only telling node to include the body-parser package in our app, else everything is kept the same as earlier.

The code in Server.js is almost the same as in the previous step. We have added code to include and use body-parser in our application

Server.js




// SERVER.JS
  
  
// WE HAVE TO TELL NODE THAT WE REQUIRE 
// EXPRESS PACKAGE IN OUR PROJECT.
var express = require('express');
  
// CREATING OUR APP.
var app = express();
  
  
// TELLING NODE THAT WE REQUIRE BODY-PARSE
// R PACKAGE IN OUR PROJECT.
var bodyParser = require('body-parser');
  
  
// Allowing our app to use the body parser package.
app.use(bodyParser.urlencoded({extended:false}))
  
  
// TELLING NODE THAT WE REQUIRE AXIOS PACKAGE IN OUR PROJECT.
var axios = require("axios").default;
  
// Code below is same as that as shown in the prev step.


We have installed the body-parser package, we can now write code(In the section where we have handled the post request on /data route) to find which stock user has selected from the dropdown.

  • In the code given below, first of all, we are making a variable named options(we can copy and paste also from the API dashboard as we did earlier), containing all the details of the API. 
  • Then, we are using body-parser package to extract which stock-symbol the user has selected from the drop-down menu. 
  • And lastly, we are making an API call(using the package “axios”) and extracting the required data from the response(in the JSON format) given back by the API, and printing it in the console.

Server.js




// OPTIONS VARIABLE THAT CONTAINS THE INFO 
// RELATED TO THE API WE ARE GOING TO USE 
// TO FETCH DATA OF THE STOCK THAT USER HAS SELECTED.
var options = {
  method: 'GET',
  params: {Indices: 'NIFTY 50'},
  headers: {
    'x-rapidapi-host': 'latest-stock-price.p.rapidapi.com',
    'x-rapidapi-key': 'YOUR-UNIQUE-API-KEY'
  }
};
  
  
  
  
  
// EVERYTHING EXCEPT THE POST REQUEST 
// SECTION IS SAME AS EARLIER.
app.post("/data"function(req, res) {
  
// res.send("We have got the post request on /data route");
  
  
  
// req.body represents the data we have got from
// the post request that has been made
//.stockSelected is the “name” property of
// dropdown(in Index.html)
// which represents that we want the data that
// is selected from the dropdown.
  
  
  
var itemSelectedFromDropdown = req.body.stockSelected;
  
  
  
  
  
// WE LEARNT HOW WE CAN MAKE API CALL USING AXIOS
// BELOW WE ARE MAKING THE API CALL AGAIN TO FETCH
// THE DATA THAT IS REQUIRED BY THE USER
// BASED ON THE STOCK SELECTED.
axios.request(options).then(function (response) {
  
  
        var dataFromResponse = response.data;
        // dataFromResponse variable is a complete
        // array containing list of all stocks
        // listed in NIFTY50
  
        for(var i = 0; i<dataFromResponse.length; i++){
               // we iterate through the whole array to find
            // the index of the stock which is
            //selected by the user from the drop-down.
  
          if(dataFromResponse[i].symbol == itemSelectedFromDropdown){
            // We have got the index of stock which user has selected
            // logging the data in the console related to that stock
                      console.log(dataFromResponse[i]);
          }
        }
          
}).catch(function (error) {
console.error(error);
});
});


A detailed explanation of what we have written in the above code

  • First of all, we have added the options variable to our Server.js file, which contain all the details related to the API.
  • Then we have used app.post(“/data”, function(){}) to handle post request on the /data route.
  • Then, we have fetched the form data that has come with the post request(using req.body), and .stockSelected tells the value that the user has entered in the dropdown(or basically selected from the dropdown).
  • The value of that particular stock (in the HTML form which we created in step2) is named in accordance with its respective symbol(to make the work easier for you). For example, (in the Index.html file), the second option in the drop-down is of the stock “INFOSYS”, represented by “<option value=”INFY”>INFOSYS</option>”. Here, the value of INFOSYS is given as INFY which is the symbol of the respective stock. Similarly, the fifth option in drop-down is “ICICI Bank”, having the stock-symbol “ICICIBANK“, thus, we named the value corresponding to the stock as it’s symbol name(“<option value=”ICICIBANK”>ICICI Bank</option>“).

We have intentionally written all the values(in the drop-down option tag) in accordance with their symbols to make everything simple for you.

In short, when we write req.body.stockSelected, it basically represents the symbol of that corresponding stock and we can use that symbol to extract the required data from the API response.

  • Finally, we make an API request, fetch the data of stock that the user has selected(which is determined using the above step), and log that data in the console.

You can again restart the Server by performing the similar steps that we have performed earlier.

Now, on the homepage, if you select any stock and click on the “Fetch Data” button, you will see the data related to the stock you have selected in the console/terminal as shown in the image below:

We have selected reliance from the drop-down, and as we clicked on the fetch data button, this response got logged in the console.

Step7: Now we have to write code in such a way that the response given by the post request is in the form of HTML, containing all the data that we have fetched based on the stock user has selected.

For that, we have to modify our post request handling section a little bit (for the last time here). We are writing simple HTML code in Nodejs res.send() method.

Everything is the same in the Server.js file except the post request handling section, where we are writing HTML code attached with the required data of Stock in our res.send() method(which is used to give the response back to the user).

Server.js




// EVERYTHING EXCEPT THE POST REQUEST 
// SECTION IS SAME AS EARLIER.
// HANDLING THE POST REQUEST ON /DATA ROUTE.
app.post("/data"function(req, res) {
  
        var itemSelectedFromDropdown = req.body.stockSelected;
        axios.request(options).then(function (response) {
  
                var dataFromResponse = response.data;
                for(var i = 0; i<dataFromResponse.length; i++){
                  if(dataFromResponse[i].symbol == itemSelectedFromDropdown){
                          
                        var dataOfStock = dataFromResponse[i];
                        res.send("<html><body> <h1><strong> " + dataOfStock.symbol + "</strong></h1>"+
                        "<h1> Open: " + dataOfStock.open + "</h1>" +
                        "<h1> Day High: "+ dataOfStock.dayHigh + "</h1>" +
                        "<h1> Day Low: "+ dataOfStock.dayLow + "</h1>" +
                        "<h1> Last Price: "+ dataOfStock.lastPrice + "</h1>" +
                        "<h1> Previous Close: "+ dataOfStock.previousClose + "</h1>" +
                        "<h1> Year Low: "+ dataOfStock.yearHigh + "</h1>" +
                        "<h1> Year Low: "+ dataOfStock.yearLow + "</h1>" +
                        "<h1> Last Update Time: "+ dataOfStock.lastUpdateTime + "</h1>" +
  
                        "</body></html>")
                  }
                }
          
          }).catch(function (error) {
          console.error(error)
          });
});


Here’s the complete explanation of what we have done in the above code:

  • We have created the variable named dataOfStock which has the data of the stock user has selected. We can now fetch any attribute of the stock (Eg. Open, Day High, Day Low, etc.) using dot(.).  
  • Also, we are trying to present the data to the user in a systematic way, so we have written the attribute, along with its value (fetching from the dataOfStock variable created above using dots(.)).

One thing to note here is, that we can also send HTML code in res.send() method while handling a post request, by writing the HTML code in double-quotes. (Make sure you do not commit any error while writing HTML code). Now we have written the entire code, it’s time to run our App.

Now we have completed our app, which fetches data from the Stock Market Database and provides that to our End User.  

Complete Code:

Index.html




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <style media="screen">
      body{
        text-align: center!important;
      }
    </style>
  </head>
  
  <body>
    <h1>Fetch the Data Related to Any Stock</h1>
    <br>
      <h2>Select the Stock</h2>
      <form class="" action="/data" method="post">
          <select class="" name="stockSelected">
              <option value="RELIANCE">
                RELIANCE
              </option>
              <option value="INFY">
                INFOSYS
              </option>
              <option value="TCS">
                TCS
              </option>
              <option value="WIPRO">
                WIPRO</option>
              <option value="ICICIBANK">
                ICICI Bank
              </option>
              <option value="ITC">
                ITC
              </option>
          </select>
          <button type="submit" name="button">
            Fetch Data
          </button>
      </form>
  </body>
</html>


Server.js




var express = require('express');
var app = express();
  
var bodyParser = require('body-parser');
  
// Allowing our app to use the body parser package.
app.use(bodyParser.urlencoded({extended:false}))
  
var axios = require("axios").default;
  
var options = {
  method: 'GET',
  params: {Indices: 'NIFTY 50'},
  headers: {
    'x-rapidapi-host': 'latest-stock-price.p.rapidapi.com',
    'x-rapidapi-key': '9c4324e513mshdd7f131fa562556p1c3a3fjsnf8baf6f4993d'
  }
};
  
app.get("/", function(req, res) {
      res.sendFile(__dirname + "/index.html");
});
  
// HANDLING THE POST REQUEST ON /DATA ROUTE.
app.post("/data"function(req, res) {
  
        var itemSelectedFromDropdown = req.body.stockSelected;
  
        axios.request(options).then(function (response) {
  
                    var dataFromResponse = response.data;
                for(var i = 0; i<dataFromResponse.length; i++){
                  if(dataFromResponse[i].symbol == itemSelectedFromDropdown){
   
                        var dataOfStock = dataFromResponse[i];
  
                        res.send("<html><body> <h1><strong> " + dataOfStock.symbol + "</strong></h1>"+
                        "<h1> Open: " + dataOfStock.open + "</h1>" +
                        "<h1> Day High: "+ dataOfStock.dayHigh + "</h1>" +
                        "<h1> Day Low: "+ dataOfStock.dayLow + "</h1>" +
                        "<h1> Last Price: "+ dataOfStock.lastPrice + "</h1>" +
                        "<h1> Previous Close: "+ dataOfStock.previousClose + "</h1>" +
                        "<h1> Year Low: "+ dataOfStock.yearHigh + "</h1>" +
                        "<h1> Year Low: "+ dataOfStock.yearLow + "</h1>" +
                        "<h1> Last Update Time: "+ dataOfStock.lastUpdateTime + "</h1>" +
                        "</body></html>")
                  }
                }
          
          }).catch(function (error) {
          console.error(error)
          });
});
  
  
var port = 3000;
app.listen(port, function() {
    console.log("Server started successfully at port 3000!");
});


Now we are able to fetch the data using API, we can now create more complex apps(For example, we can use the data to provide complete analysis of any stock based on its performance in previous years), and we can also try different APIs as well.

As the article was a bit long, here’s a quick summary of all things we have done:

  • First, we learned what is API, and JSON or JavaScript Object Notation.
  • Then we searched for a free Stock Market API(latest-stock-price API), which could provide us the functionality to fetch details from the Stock Market Database, and also got our unique API key which we used in the options variable later in the article.
  • Then we learned how we can fetch data using the node package named “axios”. We installed that package, and used it to make a simple request via API, and logged the results in the console.
  • Then we created a new folder, installed npm and the required packages and started building our Web Application. For that, we first created a simple HTML form, and on the Server side, we installed Express to handle get and post requests, Axios for making API calls and body-parser for extracting the stock which user selected from the drop-down in Index.html.
  • Then we wrote the code for “get” and “post” requests, where, in the get request on the home route, we sent an HTML form we created, and in the post request on the data route, we used body-parser to know which stock user had selected, and sent the data related to that particular stock.

Output: Restart the server once again, and then run “localhost:3000” on your web browser. You will see our App running as shown below.

Our final application is ready. You can see the current prices of stock(fetched from the API) are practically equal as the actual prices.



Last Updated : 19 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads