Learning Node.JS And Express - Part 3 (Creating API)

This is the last part of the series “Learning Node.js and Express”. Please refer the earlier two articles here:

In order to get complete inside out of the series.

For this particular article, we would be using the trial version of WebStorm IDE , the database used will be SQL Server 2008 R2 and we will be using Postman for testing our webservice response

As mentioned in the previous article, the db structure previously included:

sample table

And we were able to get response as the following:

Postman UI looks

We can avoid using Postman and do all the API testing from browser itself but I would still be using Postman as it have many features that a browser does not provide. You can get all the information regarding Postman from the following links : Postman Introduction and Postman Features

Now, let’s get to some code configuration.

By this time all of you would be well aware with the app.js file in the project. This is rather a very important file and is the first one to be executed when the project starts. The code in this file decides the route of the request.

For this article, I will be doing the code in this file only, although we can segregate the code in different files but that is not the purpose of this article, hence skip that.

Let’s define a variable of the type “Router”, this is a property in the express package that we have previously installed in the application.

  1. var router = express.Router(); // get an instance of the express Router  
Now, we can explicitely mention the port no. On which we would like to get the response on. I would be using the port 8090 and mention it using the following code:
  1. var port = process.env.PORT || 8080;  
As per the general practice, we usually make our API in a way that the request had to have the word “API” in it.

We mentioned the same using the following code:
  1. app.use('/api', router);  
It specifies, that the word “API” needs to be there before the router word/expression.

Let’s make a welcome method for our API which will only have a greeting message for the users:
  1. router.get('/', function(req, res) {  
  2.    res.json({ message: 'hooray! welcome to our api!' });  
  3. });  
This method will be called when the user tries to hit the url: http://localhost:8090/api/.

This is more of a default method to be called when we just need to check if the API is working or not.

Let’s open Postman now, it comes as an extension to chrome and is pretty self explanatory in usage. The basic Postman UI looks something like the following:


Let’s try and hit the url http://localhost:8090/api/ in Postman and test the result, but before that we have to start the API as well. In order to do that, right click the app.js file and click on the option “Run ‘app.js’”. The shortcut for the same is Ctrl+Shift+F10.

The response comes out to be as in the following:


This now proves that our code is working fine.

Let’s now make one more function in app.js which will bring data from DB and not hard coded.

We shall call the router name as “GiveData”.

The code for the same would not be much different from what we wrote in the previous article and the basic code for API is general to the complete application.

Here's the code for GetData:
  1. router.get('/GiveData', function(req, res) {  
  3.     var sql = require('mssql');  
  4.     var dbConfig = {  
  6.         server: "localhost\\MSSQLSERVER",  
  7.         database: "LearningNode",  
  8.         user: "sa",  
  9.         password: "123456",  
  10.         port: 1433  
  11.     };  
  13.     var conn = new sql.Connection(dbConfig);  
  15.     //get Request  
  16.     var req = new sql.Request(conn);  
  17.     var sqlquery = "SELECT * FROM SampleTable";  
  18.     var VData = null  
  19.     conn.connect(function(err) {  
  20.         if (err) {  
  21.             VData = "Error : " + err;  
  22.         } else {  
  23.             console.log("Connected to DB");  
  24.             req.query(sqlquery, function(err, recordset) {  
  25.                 if (err) {  
  26.                     VData = "Error : " + err;  
  27.                 } else {  
  28.                     VData = JSON.stringify(recordset);  
  29.                 }  
  30.                 res.send(VData);  
  31.                 conn.close();  
  32.             });  
  33.         }  
  34.     });  
  35. });  
The response of the same could be seen using the following url in Postman: http://localhost:8090/api/GiveData.

The output response is as follows:


This response shows the output in the JSON format. The output can be seen as XML,HTML and text format.

I am ending this series here.

Hope this article gave you a good idea regarding API creation in node.js.