How to Make RESTful API In node.js
 

Dear Readers, when you face node.js interview question, then you must know this question because interviewers want new employee already know about that.

What Is RESTful API

Restful API is an API that corresponds to the Representative State Transfer or the REST model. RESTful APIs are sometimes more comfortable for developers to use because they have a set of familiar syntax and protocols.

Now we start our topic of Advanced Node JS Interview Question and explore it deeply.

How to Make RESTful API in Node.js

In this example, we will create a RESTful API in response to data in JSON format.

In this blog, we’ll be answering how to build a Rest API in Node.js. This answer assumes an intermediate knowledge of working experience on javascript.

Phase 1. Define RESTful API

Before creating a RESTful API, the first thing you need to do is define the EndPoint of the RESTful API that you will create. The Restful API uses HTTP verbs. Generally used HTTP actions are GET, POST, PUT, and DELETE.

Phase 2. Create a database and table

To create a product table, it can be done by SQL Command:

CREATE TABLE product(
   product_id INT(11) PRIMARY KEY AUTO_INCREMENT,
   product_name VARCHAR(200),
   product_price INT(11)
)ENGINE=INNODB;

After that, enter some data in the product table:

INSERT INTO product(product_name,product_price) VALUES
('Product 1','2000'),
('Product 2','5000'),
('Product 3','4000'),
('Product 4','6000'),
('Product 5','7000');

The above SQL command will input 5 data into the product table.

Phase 3. Now Create Index.js file

And open index.js and type this code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const mysql = require('mysql');

// parse application/JSON

app.use(bodyParser.json());

//create database connection

const conn = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: '',
   database: 'restful_db'
});

 

//Connect to database

conn.connect((err) =>{
   if(err) throw err;
   console.log('Mysql Connected...');
});

 

//show all products

app.get('/api/products',(req, res) => {
   let sql = "SELECT * FROM product";
   let query = conn.query(sql, (err, results) => {
      if(err) throw err;
      res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
   });
});

 

//show a single product

app.get('/api/products/:id',(req, res) => {
   let sql = "SELECT * FROM product WHERE product_id="+req.params.id;
   let query = conn.query(sql, (err, results) => {
     if(err) throw err;
     res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
   });
});

 

//add new product

app.post('/api/products',(req, res) => {
let data = {product_name: req.body.product_name, product_price: req.body.product_price};
let sql = "INSERT INTO product SET ?";
let query = conn.query(sql, data,(err, results) => {
if(err) throw err;
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
});
});

 

//update product

app.put('/api/products/:id',(req, res) => {
    let sql = "UPDATE product SET product_name='"+req.body.product_name+"', product_price='"+req.body.product_price+"' WHERE product_id="+req.params.id; let query = conn.query(sql, (err, results) => {
     if(err) throw err;
     res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
    });
});

 

//Server listening

app.listen(3000,() =>{
   console.log('Server started on port 3000...');
});

I hope you found this informative and helped to add your knowledge through this node.js interview questions.

Conclusion:

We have successfully built the Node.js REST API. This node is the only basis for the rest of the API. There are still a lot of things in this situation, like adding certifications and authorizations, etc...