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 operation.
This article is designed so that a beginner and professional can easily understand it.
Before starting with creating API, let's understand the 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
- Node.js 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 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 be 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 opening project in Visual Studio Code, 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
- Express
Fast, unopinionated, minimalist web framework for node.
More details can be found at https://www.npmjs.com/package/express.
- body-parser
Node.js body parsing middleware.
Parse 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 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 click in explorer and select New File, then name your file as Server.js.
Until now, we 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 indicates that 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 used the Http Get
method, next we provided a path for API "/product
" after that, we wrote a callback function which has two parameters, 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 running 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 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 get 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 require.
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, first we are going to create Stored Procedure for insert records in the products
table.
Next, as we have written route in get
API, in the same way we are going to write POST
API route.
But something is new in this code snippet because we are using stored procedure 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 few 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
extracts 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');
app.use(bodyParser.urlencoded({ extended: true }));
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 if it is 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 to 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 productID
from Uri and on basis of it, it will delete product
records.
Deleting a Resource
In this part, we are going to Delete
product. For doing that, we are going to send id of product from Uri as you can see in the 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 liked my article to kickstart Node.js. In the next article, you will learn how to validate API Request.
History
- 12th April, 2018: Initial version