Part 2-Node.js Restful API Sample App

In this phase, we will start by creating Routes in MVC manners. Without adding everything in app.js
As we are creating REST API
Step 1: Create a directory ‘routes’ and create file api.js
This file name is not supposed to have any impact on the Routes but its just to make it easy to understand what exactly the routes are about.
Step 2: Open the file api.js in editor to add following codes to it.
const express = require(‘express’);
const router = express.Router();
Step 3: We are adding the routes for the API to get  lists of products, post the values of product to add new product, put request to update a product provided with product id.
  • Get Request for list of products:
router.get(‘/products’, (req, res) => {
      res.send(“This is get request for the list of products”);
});
  • Post request to add new products:
router.post(‘/product’, (req, res) => {
      res.send(“Post the information”);
});
  • Put request to Update information:
router.put(‘/product/:id’, (req, res) => {
      res.send(“Update product id added in Query String”);
});
Please note above we have used ‘router’ not ‘app’ as we used it in app.js
Step 4: Export router to use it in other parts of the application as we will use it in app.js
module.exports = router;
Step 5: Now, go to app.js and import routers/api.js file to use it using following code:
const routes = require(‘./routes/api’);
Please note, we are not to use ‘.js’ with the file to be imported.
Now, app will use it to provide the functionality of routes.
app.use(routes);

Testing Routs:

As at the moment, we have no UI built on it, how can we test the routes ?

Get request is easy to be tested using browser. However for rest of the request forms and detailed testing, we may use a testing platform called ‘Postman‘. It can be installed as Chrome Extension.

I would share testing with Postman in later stage. Its pretty much intuitive and you can explore it yourself.

 

One thought on “Part 2-Node.js Restful API Sample App”

Leave a Reply

Your email address will not be published. Required fields are marked *