RESTful Web Services

RESTFul APIs have been around for sometime now. At the time of this write-up it is practically impossible for you to be a software developer without having to create and use one or more APIs.

RESTFul APIs, on the other hand, are APIs that conform to the REST architectural style. REST refers to Representational State Transfer which “is an architectural style that defines a set of constraints and properties based on HTTP”.

REST stands for REpresentational State Transfer and is used to access and manipulate data using several stateless operations. These operations are integral to the HTTP protocol and represent an essential CRUD functionality (Create, Read, Update, Delete).

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards.

Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, which provides resource representation such as JSON and set of HTTP Methods.

Required applications

  • NodeJS
  • PostMan
  • IDE

NodeJS

Node.js development is a JavaScript runtime environment that runs server-side. Within that environment, we can use JavaScript to build our software, our REST APIs, and invoke external services through their APIs. This fact is especially convenient for developers who are crossing over from front-end development as they should already be familiar with JavaScript, making the transition more natural. It also has the bonus of unifying all of the codebase under a single programming language.

  • Node.js is an open source server environment
  • Node.js is free
  • Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
  • Node.js uses JavaScript on the server

Open your terminal or command prompt.

  • Run node -v This verifies the Nodejs version installed.
  • Run npm -v to verify Node Package Manager(npm) installed

Now it is time to give a name to our project and we will call it xtreemRESTapi. We need to find a good location in our filesystem to store our project files. Personally, since I get to work with different tools and programming languages, I chose to keep my node-based projects in a directory nodeprojects on my local drive. This is where I will create my new project directory xtreemrestapi with the following commands

// Create directory for your new project xtreemRestapi
mkdir xtreemrestapi

// Navigate into the directory
cd xtreemrestapi

Initialize NodeJs project with npm init follow the wizard to setup the project

Accept the default name and version but change the description as shown above. Do not forget to change the author’s name to your name and accept the default license to generate package.json. Do not worry about some of the inputs if you made a mistake, the file will be available in your project root directory for you to edit at will.

At this point, you should verify that you have a package.json file is available n your project root by listing the files with either ls -l or dir depending on your OS.

Time to Install Express and Setup Server

We have to run a web server with the end goal to make our API endpoint available to the program or a device like PostMan, we will utilize ExpressJS to accomplish this. On the off chance that you are not acquainted with ExpressJS make a beeline for the official site to take in more, generally we should continue onward. With npm we introduce Express in our undertaking with this direction

npm install express --save

It will take a while to complete the installation depending on your connection speed but in the end expressJs and its dependencies will be installed.

You can see one directory node_modules and one file package.json. Package.json store the nodeJs project configuration including dependencies. You can see the just installed expressjs -v4.16.3 under dependencies. Installed node packages are located in node_modules and we should not modify anything in that directory rather we should exclude with gitignore when we are pushing to a remote repository. In our package.json, we defined server.js as our app’s entry point. We need to create that file now and setup our web server.

Create a file server.js and add this code.

var express = require('express');
var app = express();
var fs = require("fs");

app.get('/listUsers', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       console.log( data );
       res.end( data );
   });
})

var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}

app.post('/addUser', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       data["user4"] = user["user4"];
       console.log( data );
       res.end( JSON.stringify(data));
   });
})

app.get('/:id', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
      var users = JSON.parse( data );
      var user = users["user" + req.params.id]
      console.log( user );
      res.end( JSON.stringify(user));
   });
})


var id = 2;

app.delete('/deleteUser', function (req, res) {

   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       delete data["user" + 2];
       
       console.log( data );
       res.end( JSON.stringify(data));
   });
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

})

Save the file and run node server on the terminal window.

Head to http://localhost:8081 on your browser.

We will implement the following endpoints

GET /listUsers list all users
URL: http://localhost:8081/listUsers

POST /addUser create new user
URL: http://localhost:8081/addUser

GET /{id} retrieve a single user
URL: http://localhost:8081/1

DELETE /deleteUser/{id} delete a single user
URL: http://localhost:8081/deleteUser/1

Conclusion

With the tools and methods covered in this tutorial, you should now be able to create simple and secure REST APIs on Node.js development. A lot of best practices that are not essential to the process were skipped so don’t forget to:

Implement proper validations (e.g. make sure that user email is unique)
Implement unit testing and error reporting
Prevent users from changing their own permission level
Prevent admins from removing themselves
Prevent disclosure of sensitive information (e.g., hashed passwords)

You can get the source code on GitHub.