In this post I am not going to explain, what is REST? I assume you are already aware of REST concepts hence on this post to create REST API on Node.js which will perform CRUD operations. I am going to use Visual Studio to create Node Application and before you move ahead in this post, recommend you to read
Getting started with Node.js development in Visual Studio
After reading above article when you are done with setting up Visual Studio for Node.js go ahead and create a Node Application by selecting Blank Express Application template from JavaScript language section
Image may be NSFW.
Clik here to view.
Once project is created right click on the public\javascripts folder and add a new JavaScript file. You are free to give any file name, I am giving data.js .
Before you work with data.js I recommend you to read below post
First we are going to create data and CRUD operation on that. Keep in mind that we are going to expose CRUD operation as REST API on a JavaScript Array. In real projects you may want to perform these operations on database.
To start with I have created an array as below,
var product = [ { "id" :1 , "productName" : "Pen", "productPrice" : "200", 'productStock' : "false" }, { "id" :2 , "productName" : "Pencil", "productPrice" : "200", "productStock" : "false" }, ];
Fetch Records
Let us start with writing function to return products. If you notice function is taking two parameters req and res. We send data in HTTP response with res.send . In this case we are sending JSON object product as HTTP response.
exports.getProducts = function(req,res){ res.send(product); };
Add Record
To add record we need to read data coming in HTTP request. We can read that using req.body. Client will append JSON data to get added in product array in request body. After reading request body we are just pushing data in array using push method.
exports.addProduct = function(req,res) { var data = req.body; product.push(data); res.send(product); }
Delete Record
To delete record we need to read query parameter coming in URL as HTTP request. We can read that using req.params. Once we have id to delete a product, I am just putting some logic to delete it from products array. Keep in mind that in real project and API this logic should be better. Once product is deleted successfully we are sending updated product JSON object in HTTP response.
exports.deleteProduct = function(req,res) { var id = parseInt(req.params.id)-1; var itemdeleted = product.splice(id,1) if(itemdeleted===undefined) { res.send("Not Deleted"); } else { ; res.send(product); } }
Update Record
To update record we need to read query parameter coming in URL as HTTP request. We can read that using req.params. Once we have id to update a product, we will read data to be updated in req.body. After that I am just putting some logic to update item in products array. Keep in mind that in real project and API this logic should be better. Once product is updated successfully we are sending updated product JSON object in HTTP response.
exports.updateProduct = function(req,res) { var id = parseInt(req.params.id)-1; var productToUpdate = product[id]; var data = req.body; if(productToUpdate===undefined) { res.send("Not Updated"); } else { productToUpdate.productName = data.productName; productToUpdate.productPrice = data.productPrice; productToUpdate.productStock = data.productStock; res.send(product); } }
Just we created CRUD operation which we will expose as REST API. Putting all together data.js which contains logic for CRUD would be as below,
data.js
var product = [ { "id" :1 , "productName" : "Pen", "productPrice" : "200", 'productStock' : "false" }, { "id" :2 , "productName" : "Pencil", "productPrice" : "200", "productStock" : "false" }, ]; exports.getProducts = function(req,res){ res.send(product); }; exports.addProduct = function(req,res) { var data = req.body; product.push(data); res.send(product); } exports.deleteProduct = function(req,res) { var id = parseInt(req.params.id)-1; var itemdeleted = product.splice(id,1) if(itemdeleted===undefined) { res.send("Not Deleted"); } else { ; res.send(product); } } exports.updateProduct = function(req,res) { var id = parseInt(req.params.id)-1; var productToUpdate = product[id]; var data = req.body; if(productToUpdate===undefined) { res.send("Not Updated"); } else { productToUpdate.productName = data.productName; productToUpdate.productPrice = data.productPrice; productToUpdate.productStock = data.productStock; res.send(product); } }
So far we have created business logic to be exposed as REST API. Now we need to add various routes in app.js. These routes will call functions from data.js module. We are going to map ROUTES to business logic as below,
Image may be NSFW.
Clik here to view.
Open app.js and add this code to load data.js module. [write all below code in app.js]
var data = require('./public/javascripts/data.js');
Once module is loaded use bodyParse to parse request body.
app.use(express.bodyParser());
If you notice we created project using Express Template. So here Node.js Express Framework router is being used. In last step to create REST API we need to add routes to application.
app.get('/products',data.getProducts); app.post('/products',data.addProduct); app.delete('/products/:id',data.deleteProduct); app.put('/products/:id',data.updateProduct);
Each route is calling a function in data module. If you notice when we added a route for HTTP POST operation which is calling addProducts function. In this function we are creating a product.
Yes it is done. You have created REST API on Node.JS using Visual Studio. To test it you have various options. You can either use
- CURL
- Fiddler
- Create a client to work with service (in next post we will do this)
So let us test created REST API in Fiddler and browsers. We can test HTTP GET in browser by pressing F5 and navigate to baseURL/products
Image may be NSFW.
Clik here to view.
Next let us use fiddler to perform POST, PUT and DELETE. To perform POST or create a product select Composer, from drop down select POST operation. Set URL, set Content-Type and in Request-Body construct a JSON to add as product.
Image may be NSFW.
Clik here to view.
When you perform this operation as a response you will get updated products as response. You can verify this in browser as well.
Image may be NSFW.
Clik here to view.
As you performed POST in the same way in fiddler you can perform DELETE and PUT. So I hope you must have realised by now that creating REST API on Node.js using Visual Studio is very simple. In next post we will consume this created REST service in different kind of clients. I hope you find this post useful. Thanks for reading.
Filed under: Node Image may be NSFW.
Clik here to view.
Clik here to view.
Clik here to view.
Clik here to view.
Clik here to view.
Clik here to view.
Clik here to view.
