In this article, we are going to learn how to create a simple API in node js and use MS SQL as a data source on which we are going to perform CRUD operations.

This article will be written so that both a beginner and a professional can easily understand it.
Before starting with creating API let’s understand basics.
What is Node js?
- An Open source, Cross-platform, and runtime environment for executing javascript code outside the browser.
What can we build using it?
- We can build Web apps and APIS using node js.
Why node.js if we already have other frameworks?
- It is super-fast and highly scalable e.g. PayPal, Uber, Netflix
- Build twice as fast with fewer people
- 33% fewer lines of code
- 40% fewer files
- 2x request/sec
- 35% faster response
The open source library has a large ecosystem.
Javascript is everywhere (front + back).
You can write an entire application using javascript, no need to learn a new language.
Prerequisites
- Node js is installed [Download node js https://nodejs.org/en/ ]
- Next, we are going to use Visual Studio Code IDE for Development [ https://code.visualstudio.com/download ]
- SQL Server Database
Let’s start with Database first
I have created a sample database “TESTDB” with Products table.

Products Table

Creating Node js Application
After creating Database and tables next we are going to create Node js application.
Creating simple Directory

After creating Directory, next, we are going to test Node. For testing that our installed node is working properly we are going to enter the command “node” after entering the command and it should enter into language shell mode as shown below.

After creating a directory and how to use “node” command now let’s create package.json.
What is a package. Json?
It is the file that contains the name of the application, the version and lists the packages that your project depends on. It allows you to specify the versions of a package that your project can use using semantic versioning rules. It makes your build reproducible, and therefore much easier to share with other developers.
Reference Link: - https://goo.gl/pXwGB2
Creating a package.json
For creating a package.json file we are going to first execute the command “npm init”.

After executing the command, it will begin to ask a question for generating the package. json file.
The first question it will ask is for application name; here I am going to enter “demoproductapi”, next it will ask for version. It will be by default 1.0.0; after that it will ask for a description. I am going to enter “product API”, next it is going to ask entry point and here I am going to enter “server.js” as entry point to our application. Next we are not going to set test command, git repository, and keywords, and at last we are going to set author and license.
After that, it will show you what it will write to package.json file.
And finally, it will ask you if you want to generate the package.json file with the setting you have set and if you say yes then it is going to create the file.

Next, it has generated your package.json file.
Opening project in Visual Studio code from the command prompt
Now to open this file in Visual Studio code we are going to write “code .”
As you enter the command it will open Visual Studio code as you can see below.
Note
Color Theme Visual studio code IDE might be different but you can set your custom Color theme as you want.

After opening the project in Visual Studio code, next we are going to install various packages which we require for creating the API.
All packages will be downloaded from npm (Node Package Manager).
Installing modules
- Express
Fast, unopinionated, minimalist web framework for node.
More Details :- https://www.npmjs.com/package/express
- body-parser
Node.js is body parsing middleware.
Parses incoming request bodies in a middleware before your handlers, available under the req.body property.
- Mssql
Microsoft SQL Server client for Node.js
- joi
Object schema description language and validator for JavaScript objects.
For installing package from Visual Studio code you can open a terminal in Visual Studio code using shortcut keys [ Ctrl + ‘~’]

Note The ‘--save ' option instructed NPM to include the modules inside of the dependencies section of your package.json automatically.
Command: - npm install --save express body-parser mssql joi

After entering the command just click on the enter button to install modules.
After installing you will see all modules in the package.json file with versions in it.

Next, we are going to add a js file with name server.js
Adding Server.js file
In this part, we are going to add server.js file and in this file, we are going to create a simple server using an express framework, which will handle HTTP request.
For adding files just right click in explorer and select New File, then name your file as Server.js.
So far we have installed all modules now to use that module in a Node.js application we need to use the 'require' keyword.

Now to run this application we are going to use shortcut [ Ctrl + ‘~’] to open Terminal.
Next, we are going to enter command node and file name.
- Command: - “node server.js”.

After you enter the command you can see the log which we have written; this indicates the application is running.
Note: - What is Callback?
A callback is a function called at the completion of a given task; this prevents any blocking and allows other code to be run in the meantime.
Reference:- https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks/
Create a simple service to understand
For creating a simple API, we are going to use an express framework which we have already downloaded.
The first API we are going to create is the get product API which will return a simple welcome message as a response in Json format.
For handling a get request we have used Http Get method, next we have provided a path for API “/product” after that, we have written a callback function which has 2 parameter requests and responses. We are going to use response parameter to send a response in Json format.

Code Snippet for the first API
- var express = require('express');
- var app = express();
- var port = process.env.port || 1337;
- app.get("/product",function(request,response)
- {
- response.json({"Message":"Welcome to Node js"});
- });
- app.listen(port, function () {
- var datetime = new Date();
- var message = "Server runnning on Port:- " + port + "Started at :- " + datetime;
- console.log(message);
- });
After completing creating the API next, for testing how it works, we are going to use REST client “POSTMAN”.
Using POSTMAN Rest Client to Test API
There are various REST clients available and you can use any of them to test API, for this demo I am going to use POSTMAN.
We are going to send Get Request, for doing that I am setting Request Method to Get type, further, I have entered localhost URL along with port number and API path http://localhost:1337/product. After setting request URL the final step is to set Content-Type to application/json and click on send button to send the request.

After sending request we get a response which we have set in the API response.
Wow, we have created a simple API in node js.
Now we have learned how to create a simple API but we have written our entire code inside the server.js file which will get messy if we are going to create Add More APIs in it. To stop that we are going to create a separate database connection file and controllers file and in that file we are going to write code and export it such that we can access it anywhere.
Creating GET API

Connect.js for Creating Database Connection for Using SQL Server
We have created a new folder with the name “connection” and in this folder, we are going to add a connect.js file.
After creating the file next, we are going to import “mssql” module for creating SQL connection, and finally, we are going to export this connection such that it can be used in other modules.

Code Snippet
- var sql = require("mssql");
- var connect = function()
- {
- var conn = new sql.ConnectionPool({
- user: 'sa',
- password: 'Pass@123',
- server: 'SAI-PC',
- database: 'TESTDB'
- });
- return conn;
- };
- module.exports = connect;
After adding connect.js for creating SQL connection file next we are going to add Controller folder and inside that folder, we are going to add Product Controller js file.
ProductController.js for creating Route
We are going to use Route to define all routes of a product in one router.
For example, all “/product” routes can be defined in one router, in future, if we have to add any new route to the product we can easily define in “/product” route, we are going to get all product-related routes at one place.

Now we have added ProductController.js file next we are going to import module and create a route.
Loading required Modules

Code Explanation
First we are going to load external module which we are required to do.
- var express = require('express');
- var router = express.Router();
- var sql = require("mssql");
- var conn = require("../connection/connect")();
- Express: - A web framework for creating API.
- Router: - Used to create a route.
- SQL: - Microsoft SQL Server client for Node.js
- Conn: - We are importing SQL connection from connect.js Class.
After importing the module, we have defined Anonymous functions and stored it in the “routes” variable.
Next we have defined route router.route('/').
After defining route, next, we have declared HTTP Method “Get” and written a callback.
.get(function (req, res)
Note - connect
Create a new connection pool. The initial probe connection is created to find out whether the configuration is valid.
After that we are going to use Connect function for creating new connection pool.
- conn.connect().then(function ()
- {
Next, after creating a connection, I have written a query to get all products from the database.
- var sqlQuery = "SELECT * FROM Products";
After we have written the query we are going to create a new SQL request and pass your connection (conn) to it.
Then request (req) has a method query which takes command string as input. We are going to pass our sqlQuery to it, and the same query has a callback which will return a response.
- var req = new sql.Request(conn);
- req.query(sqlQuery).then(function (recordset)
- {
- res.json(recordset.recordset);
- conn.close();
- })




















Debapriya SahooPosted Jun 12, 2021, 1:42 PM
ConnectionError: Failed to connect to XXX:1433 - self signed certificateGot this issue when i was try with same code
Jana VithuPosted Oct 3, 2018, 1:43 AM
It wouldgreate if you can help me, i followed your instruction, but i am getting null value when try to inserting the data. Could you help me out ?
Steven ThefainePosted Sep 12, 2018, 2:11 PM
Great article. Is it possible to show how you would get the inserted id return back from a post executing a stored procedure. Thank You
Ananya SreepathiPosted Aug 17, 2018, 1:06 PM
I have not seen such a best explanation of code so far, too good. I am basically learning and digging deeper into node.js. Thank you so much Sainesh. This helps lot of people
Tridip BhattacharjeePosted Apr 24, 2018, 3:45 AM
How to download Node.js tools from Extension....please share a screen shot if possible.
Olinzer TamayoPosted Apr 24, 2018, 3:07 AM
This is a very nice explanation to develop an API on Node. It might be a little off-topic, but as a suggestion, you can add the method-override package, because HTMl doesn't support other methods than GET and POST, and method-override helps with PUT and DELETE methods. Very nice article.
Tridip BhattacharjeePosted Apr 23, 2018, 3:40 AM
How to code the same in VS2013 IDE or 2017 IDE?
bhavana desaiPosted Apr 22, 2018, 7:23 AM
Good explanation on Node.js API.