1. Overview

In this article, we will learn how to develop JSON web services in node js along with JSON data. we will see the specific example for insert, update and delete records.

1.1 REST Standards and Http CRUD operations

REST(REpresentational State Transfer) is not a protocol it just a set of rules.

Suppose we have one JSON object for Employees. Now we want to design RESTFUll WEB SERVICES(web service along with rest standard) for CRUD (CREATE, READ, UPDATE, DELETE) operation on employees object.

Let’s understand REST standard by below example. It shows the routes pattern and method type for different operations where employee indicates the object or table. In our case which is  JSON object. Here, Route is specific URL and Method is HTTP request type.

  • To GETall the employees
    • Route: /employee          Method: GET
  • To GET a particular employee
    • Route: /employee/:ID    Method: GET
  • To ADD a new employee
    • Route: /employee          Method: POST
  • To UPDATE employee
    • Route: /employee/:ID    Method: PUT
  • To DELETE particular employee
    • Route: /employee/:ID    Method: DELETE
  • To DELETE all employees
    • Route: /employee          Method: DELETE

1.2. Express.js

It basically helps us to manage everything from routes to request handling and views handling. It will create server we just need specify the port number.

// server.js
var express  = require('express') //importing express

var app  = express() // create one instance

var server = app.listen(8081, () => { 
    console.log('Server is started on 127.0.0.1:8081')
})

2. Examples of JSON Web Service

2.1 Project Structure

Your project structure should be like. So that your app will be more modular and easy to understand.

NodeJS JSON Web Service Example

NodeJS JSON Web Service Example

2.2 Install express module

2.2.1 package.json

First of all, add express.js in your node application by using this command. This command will install express module globally as well as locally.

npm install express --save

Your package.jsonwill look like this.

{
  "name": "javadeveloperzone.com",
  "version": "1.0.0",
  "description": "NodeJS JSON Web Service Example",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "javadeveloperzone.com",
  "license": "ISC",
  "keywords": [
    "NodeJS",
    "JSON",
    "Web",
    "Service",
    "Example"
  ],
  "dependencies": {
    "express": "^4.16.3"
  }
}

2.3 Example of employee web service

Now Let’s build simple application first we need to build server. As shown in above code build the server. Now our server is ready. Let’s Run and test it.

Input:

cmd>node server.js

Output:

Server is started on 127.0.0.1:8081

2.3.1 router.js

Let’s add some routes in separate file name it routes.js and JSON object for employee data.

let data = {
    "1": {
      "id": 1,
      "name": "emp1",
      "post": "QA"
    },
    "2": {
      "id": 2,
      "name": "emp2",
      "post": "DEVELOPER"
    },
    "3": {
      "id": 3,
      "name": "emp3",
      "post": "QA"
    }
  }

module.exports = (app) => { 
    app.get('/employee/:id', (req, res) => { //get employee by id 
        console.log('Employee With Id '+req.params.id + ' Is Requested')
        res.send(data[req.params.id])
    })
    
    app.get('/employee', (req, res) => { //get all employee 
        console.log('All Employees Requested')
        res.send(data)
    })
    
    app.delete('/employee/:id', (req, res) => { //delete employee by id 
        console.log('Employee With Id '+req.params.id + ' Is Deleted')
        console.log(data.remove(req.params.id))
        res.send("Employee is Deleted")
    })
    
    app.delete('/employee', (req, res) => { //delete all employee 
        console.log('All Employees deleted')
        res.send("All Employees Deleted")
    })
    
    app.post('/employee', (req, res) => { //add new employee
        console.log(req.body)
        res.send("New Employee Added")
    })

    app.post('/employee/:id', (req, res) => { //update particular employee 
        console.log(req.body) 
        res.send("Employee Updated") 
    })
}

2.3.2 server.js

Import this file in server.js and your server file will look like this.

var express  = require('express')

var app  = express()
require('./routes')(app) //import routes

var server = app.listen(8081, () => {
    console.log('Server is started on 127.0.0.1:8081')
})

2.4 Output:

Now check the all routes by using postman for example.

http://localhost:8081/employee

Output:

{
 1: {
     id: 1,
     name: "emp1",
     post: "QA"
 },
 2: {
     id: 2,
     name: "emp2",
     post: "DEVELOPER"
 },
 3: {
     id: 3,
     name: "emp3",
     post: "QA"
 }
}

Same as above test all the routes. For testing PUT , POST routes need to send data in body and body type to JSON(application.json)

3. Conclusion

In this article we learned how to develop JSON with rest standards using nodeJS, different types of modules like express.js, body-parser, types of HTTP request etc. you can also use some other request type like PATCH for partial update. 

4. References

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags:

Leave a Reply

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