Click here to Skip to main content
13,703,857 members
Click here to Skip to main content
Add your own
alternative version

Stats

18.4K views
743 downloads
21 bookmarked
Posted 12 Apr 2018
Licenced CPOL

Creating Simple API in Node.js

, 12 Apr 2018
Rate this:
Please Sign up or sign in to vote.
In this article, we are going to learn how to create a simple API in Node.js and using MS SQL as a data source on which we are going to perform CRUD operation.

This article is designed so that a beginner and 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
  • Builds twice as fast with fewer people
  • 33% fewer lines of code
  • 40 % fewer files
  • 2x request/sec
  • 35% faster response

Large ecosystem of the open source library

JavaScript everywhere (front + back)

You can write an entire application using JavaScript, no need to learn a new language.

Prerequisites

  1. Node.js installed [Download Node.js https://nodejs.org/en/ ]
  2. Next, we are going to use Visual Studio Code IDE for Development [https://code.visualstudio.com/download]
  3. SQL Server Database

Let's Start with Database First

I have created a sample database "TESTDB" with a Products table.

Products Table

Creating Node.js Application

After creating a Database and tables next we are going to create a Node.js application.

Creating Simple Directory

After creating Directory next, we are going to test Node for testing if our installed node is working properly. We are going to enter the command "node." After entering the command, it should enter into language shell mode as shown below.

After creating a directory and how to use the "node" command, now let's create package.json.

What is a package. Json?

The file that contains the name of the application, the version and Lists the packages that your project depends on. Allows you to specify the versions of a package that your project can use, using semantic versioning rules. 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 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 for is application name. Here I am going to enter "demoproductapi," next it will ask for version. It will by default 1.0.0 after that it will ask description I going to enter "product API", next it is going to ask entry point here I am going to enter server.js "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 the package.json file.

And finally, it will ask you if you want to generate the package.json file with the setting you have set. If you say yes, then it is going to create the file.

Next, it has generated your package.json file.

Opening the 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 the opening project in Visual Studio Code, next we are going to install various packages which we require for creating API.

All packages will be downloaded from npm (Node Package Manager).

Installing modules

  1. Express

    Fast, unopinionated, minimalist web framework for node.

    More Details: https://www.npmjs.com/package/express

  2. body-parser

    Node.js body parsing middleware.

    Parse incoming request bodies in a middleware before your handlers, available under

    the req.body property.

  3. Mssql

    Microsoft SQL Server client for Node.js

  4. 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 the 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 requests.

For adding a file just right in explorer and select New File, then name your file as Server.js.

Until now we have installed all modules 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 the 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 indicate 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 Simple Service to understand

For creating 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 get a request we have used the Http Get method, next we have provided a path for API "/product" after that, we have written a callback function which has two parameter request and response. 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 an API, next, to test 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 that, I am setting Request Method to Get type. Further, I have entered localhost URL along with port no and API path http://localhost:1337/product after setting request URL the final step is 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 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 a 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 name "connection" and in this folder, we are going to add a connect.js file.

After creating 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 product in one router.

For example, all "/product" routes can be defined in one router. In the future, if we have to add any new route to the product we can easily define in "/product" route, we are going to getting all product-related route at one place.

Now we have added the 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.

var express = require('express');
var router = express.Router();
var sql = require("mssql");
var conn = require("../connection/connect")();

Express: express which is a web framework for creating API.

Router: router to create a route.

SQL: Microsoft SQL Server client for Node.js

Conn: we are importing SQL connection from connect.js Class.

After importing module, we have defined Anonymous functions and stored in "routes" variable.

Next we have defined route router.route('/').

After defining route next, we have declared HTTP Method "Get" and wrote 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, we are going to use Connect function for creating a new connection pool.

conn.connect().then(function ()
            {

After creating connection next, 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 a 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();
                })

The response which you will get from MS SQL driver will be in JSON format, and the Get API will return JSON of all products.

Finally, we have written a catch method for catching expectation.

.catch(function (err) {
                        conn.close();
                        res.status(400).send("Error while inserting data");
                    });

After completing with creating a route just save ProductController.js

Setting up middleware for handling route request in server.js

After creating ProductController.js, next we are going to import ProductController.js file in server.js.

var express = require('express');
var app = express();
var port = process.env.port || 1337;
 
var productController = require('./Controller/ProductController')();

Now we have imported ProductController.js file next we are going to use app.use method for invoking our API.

Note: app.use([path,] callback [, callback...])

Referenced from: http://expressjs.com/en/api.html#app.use

The middleware function is executed when the base of the requested path matches path.

The app.use method takes two parameters. The first parameter is path and second parameter is function or middleware function.

If the path we request "/api/products" is matched, then it will call Productcontroller function and return a response in JSON format.

Products Table

Save entire application and run.

Now to access API open Postman or any other Rest Client and enter URL: http://localhost:1337/api/products and set HTTP method request to Get and click on Send request.

The response of Get API

After completing understanding get request next we are going create POST request API.

Creating POST API

In post API we are first we are going to create Stored Procedure for insert records in the products table.

Next, as we have written route in get API same way we are going to write POST API route.

But something is new in this code snippet because we are using store produce along with transaction and in this request, we are going to get values from post request body, which we are going to insert in the product table.

Code snippet of POST API

router.route('/')
        .post(function (req, res) {
            conn.connect().then(function () {
                var transaction = new sql.Transaction(conn);
                transaction.begin().then(function () {
                    var request = new sql.Request(transaction);
                    request.input("ProductName", sql.VarChar(50), req.body.ProductName)
                    request.input("ProductPrice", sql.Decimal(18, 0), req.body.ProductPrice)
                    request.execute("Usp_InsertProduct").then(function () {
                        transaction.commit().then(function (recordSet) {
                            conn.close();
                            res.status(200).send(req.body);
                        }).catch(function (err) {
                            conn.close();
                            res.status(400).send("Error while inserting data");
                        });
                    }).catch(function (err) {
                        conn.close();
                        res.status(400).send("Error while inserting data");
                    });
                }).catch(function (err) {
                    conn.close();
                    res.status(400).send("Error while inserting data");
                });
            }).catch(function (err) {
                conn.close();
                res.status(400).send("Error while inserting data");
            });
        });

Now we have completed with creating a post request. Next we are going make little changes in the server.js file.

We are going to use body-parser package for parsing the incoming request, we have already installed body-parser package.

Note:

What is body-parser?

Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

Referenced from: https://www.npmjs.com/package/body-parser

Simplified definition

body-parser extract the entire body portion of an incoming request stream and exposes it on req. body.

Loading body-parser module.

Code snippet for loading body-parser module

var bodyParser = require('body-parser');
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: true }));
// create application/json parser
app.use(bodyParser.json());

Save entire application and run.

Now to access POST API open Postman or any other Rest Client and enter.

URL: http://localhost:1337/api/products and set HTTP method request to POST and in request body add below Request JSON and the next step is to add header "Content-Type" to "application/json" and finally click on Send request.

Request Json

{
  "ProductName": "WebCam",
  "ProductPrice": "5000"
}

Note: Do not forget to set add header "Content-Type" to "application/json".

The response of POST API



After successfully posting data let's see is it present in the products table.

Products table view after inserting data

Wow, we have successfully inserted product in the products table.

Note:

req.query: directly access the parsed query string parameters

req.params: directly access the parsed route parameters from the path

Referenced from: http://stackabuse.com/get-query-strings-and-parameters-in-express-js/

Creating PUT API

In PUT API we are first going to create Stored Procedure for updating records of products table.

Updating a Resource.

For updating product, we are going to send id of product from Uri and the request body that contains data which we want to update.

After setting Uri and request body, next we are going add HTTP Put method in Product controller file, and the route for this method will be different because we are going to accept "id" as a parameter and also request body.

For reading route parameters value we use request.params.

Code snippet of PUT API

router.route('/:id')
.put(function (req, res)
 {
    var _productID = req.params.id;
    conn.connect().then(function () {
        var transaction = new sql.Transaction(conn);
        transaction.begin().then(function () {
            var request = new sql.Request(transaction);
            request.input("ProductID", sql.Int, _productID)
            request.input("ProductPrice", sql.Decimal(18, 0), req.body.ProductPrice)
            request.execute("Usp_UpdateProduct").then(function () {
                transaction.commit().then(function (recordSet) {
                    conn.close();
                    res.status(200).send(req.body);
                }).catch(function (err) {
                    conn.close();
                    res.status(400).send("Error while updating data");});
            }).catch(function (err) {
                conn.close();
                res.status(400).send("Error while updating data");});
        }).catch(function (err) {
            conn.close();
            res.status(400).send("Error while updating data");});
    }).catch(function (err) {
            conn.close();
            res.status(400).send("Error while updating data");});
});

After completing with adding put method next save the entire application and run.

Now to access PUT API open Postman or any other Rest Client and enter.

URL: http://localhost:1337/api/products/7 and set HTTP method request to PUT and in the request, body add below Request Json and the next step is to add header "Content-Type" to "application/json" and finally click on Send request.

Request JSON

{
  "ProductPrice": "5000"
}

Note: Do not forget to set add header "Content-Type" to "application/json".

If an Updated request succeeds, it can return status 200 (OK) along with it we are going get request body in response.

Now we have completed with creating PUT request next we are going add Delete HTTP method to delete a product.

Creating Delete API

In Delete API we are first going to create a Stored Procedure for Deleting record of product from products table. The Delete HTTP method route is similar to PUT API route which takes product ID from Uri and on bases of it, it will delete product records.

Deleting a Resource.

In this part, we are going Delete product for doing that we are going to send id of product from Uri as you can see in below snapshot.

For reading route parameters value we use request.params.

Code snippet of Delete API

router.route('/:id')
        .delete(function (req, res) {
            var _productID = req.params.id;
            conn.connect().then(function () {
                var transaction = new sql.Transaction(conn);
                transaction.begin().then(function () {
                    var request = new sql.Request(transaction);
                    request.input("ProductID", sql.Int, _productID)
                    request.execute("Usp_DeleteProduct").then(function () {
                        transaction.commit().then(function (recordSet) {
                            conn.close();
                            res.status(200).json("ProductID:" + _productID);
                        }).catch(function (err) {
                            conn.close();
                            res.status(400).send("Error while Deleting data");
                        });
                    }).catch(function (err) {
                        conn.close();
                        res.status(400).send("Error while Deleting data");
                    });
                }).catch(function (err) {
                    conn.close();
                    res.status(400).send("Error while Deleting data");
                });
            })
        });

After completing with adding Delete method next save the entire application and run.

Now to access Delete API open Postman or any other Rest Client and enter.

URL: http://localhost:1337/api/products/7 and set HTTP method request to Delete and add header "Content-Type" to "application/json" and finally click on Send request.

Note: Do not forget to set add header "Content-Type" to "application/json".

Products table view after deleting Product

Complete Project Structure

Conclusion

Until now we have learned how to create Node.js API in a simple step, we have started with creating Node.js application, after that we have to create a simple GET API in server.js file. Next we have created a product controller in that we have created route and move entire logic of API in to this controller, and also in SQL Server we have created stored procedure for Inserting, updating and deleting data. Finally, we have used POSTMAN for testing our API which we have created.

I hope you have liked my article to kick start Node.js. In the next article, you will learn how to validate API Request.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

saineshwar bageri
Software Developer (Senior)
India India
I am Microsoft MVP | C# Corner MVP working on.Net Web Technology
(Asp.net, C# , Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.

You may also be interested in...

Pro

Comments and Discussions

 
Questionhow to connect windows authentication msqsl database Pin
Member 1293466917-Sep-18 21:22
memberMember 1293466917-Sep-18 21:22 
PraiseExcellent explanation Pin
Hvishal889-Sep-18 20:16
memberHvishal889-Sep-18 20:16 
QuestionI receive error when I run server.js Pin
Member 1391390117-Jul-18 3:38
memberMember 1391390117-Jul-18 3:38 
QuestionHow to connect (LocalDB)\MSSQLLocalDB Pin
Mostafa Asaduzzaman27-Jun-18 12:20
memberMostafa Asaduzzaman27-Jun-18 12:20 
AnswerRe: How to connect (LocalDB)\MSSQLLocalDB Pin
Member 1208703019-Sep-18 23:06
memberMember 1208703019-Sep-18 23:06 
QuestionExcellent article Pin
Member 1092658726-Apr-18 2:45
memberMember 1092658726-Apr-18 2:45 
AnswerRe: Excellent article Pin
saineshwar bageri3-May-18 2:45
membersaineshwar bageri3-May-18 2:45 
Questionproblem connecting to database Pin
Member 289463623-Apr-18 23:13
memberMember 289463623-Apr-18 23:13 
AnswerRe: problem connecting to database Pin
saineshwar bageri3-May-18 2:48
membersaineshwar bageri3-May-18 2:48 
QuestionHelpful Pin
Member 1155185318-Apr-18 2:00
memberMember 1155185318-Apr-18 2:00 
AnswerRe: Helpful Pin
saineshwar bageri3-May-18 2:46
membersaineshwar bageri3-May-18 2:46 
QuestionImage with wrong code. Pin
Member 1377875118-Apr-18 1:31
memberMember 1377875118-Apr-18 1:31 
AnswerRe: Image with wrong code. Pin
saineshwar bageri19-Apr-18 20:57
membersaineshwar bageri19-Apr-18 20:57 
GeneralMy vote of 5 Pin
Mou_kol12-Apr-18 21:50
memberMou_kol12-Apr-18 21:50 
GeneralRe: My vote of 5 Pin
saineshwar bageri3-May-18 2:46
membersaineshwar bageri3-May-18 2:46 
QuestionVS code IDE has same functionality of VS IDE Pin
Mou_kol12-Apr-18 21:47
memberMou_kol12-Apr-18 21:47 
Question3rd Party Platform ? Pin
Member 1158571812-Apr-18 17:11
memberMember 1158571812-Apr-18 17:11 
AnswerRe: 3rd Party Platform ? Pin
saineshwar bageri16-Apr-18 17:54
membersaineshwar bageri16-Apr-18 17:54 
QuestionWhy Node.js if we already have other frameworks? Pin
Dewey12-Apr-18 15:50
memberDewey12-Apr-18 15:50 
AnswerRe: Why Node.js if we already have other frameworks? Pin
Igor Ladnik13-Apr-18 13:59
professionalIgor Ladnik13-Apr-18 13:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180920.1 | Last Updated 12 Apr 2018
Article Copyright 2018 by saineshwar bageri
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid