ExpressJS RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.

Topics Covered

  • What is ExpressJS Restful API?
  • Why we need ExpressJS Restful APIs.
  • Advantages
  • Initialize npm and install the  modules
  • Creates  a  New User
  • Returns All the Users From the Database
  • Gets a Single User From the Database
  • Deletes a  User From the Database
  • Updates a Single User in  the Database

Why we need ExpressJS Restful APIs

The World Wide Web itself is based on HTTP and is based on RESTful API architecture. Mostly all the modern web browsers are RESTful API client. RESTful API applications use HTTP methods (GET, POST, PUT, and DELETE) to perform CRUD operations.

Advantages

1. Quick & easy development
2. High performance
3. Run on single thread to handle multiple concurrent requests
4. Easy to write APIs and interaction code
5. Streaming support
6. Monitoring possibilities
7. Authentication support
8. Lightweight, fast and scalable

Here is the restful API Design with Node

Initialize npm and install the following modules:

npm init
npm install express --save
npm install mongoose --save
npm install body-parser --save

Now, we will use ExpressJS for developing an application. It is a node.js framework. We will use Mongoose. Mongoose is an ORM (Object Relational Mapper). We use an ORM to simplify the transfer of data between our application and the database. The body-parser module is a middleware we are going to use, to parse our data sent through HTTP requests.

To start developing the application, create a  file and name it as  app.js. Write following code in your app.js file.

app.js

var express = require('express');
var app = express();
module.exports = app;

app.js will be used for configuring the app. All the logic will be placed in the directory.

We will use a module.exports module to make the application’s object visible to the program when we call it using require(). Now have to create Routes to listen to the application. For that, we will create another file, name it as  server.js, and we will write following code in our  server.js file.

server.js

var app = require('./app');
var port = 3000;
var server = app.listen(port, function() {
console.log('server listening on port ' + port);
});

Create a new file and name it as db.js,  This file’s Code will be used to store your database connection.

db.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://yourDatabaseURI');
 add a require() in the app.js, like this 

app.js

var express = require('express');
var app = express();
var db = require('./db');
module.exports = app;

Create a new folder name it user.js. This folder will contain the schema and model. We Will start by creating a user model. This model will be used as a schema(blueprint) showing what all users in our database will look like. Create a file named user.js and write code into your user.js file.

user.js

var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
});
mongoose.model('User', UserSchema);
module.exports = mongoose.model('User');

Create another file, and name it UserController.js. It will contain the actions which control the flow of data to and fro the database.

UserController.js

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({
    extended: true
}));
router.use(bodyParser.json());
var User = require('./User');
module.exports = router;

Create a New User

router.post('/', function (req, res) {
    User.create({
            name: req.body.name,
            email: req.body.email,
            password: req.body.password
        },
        function (err, user) {
            if (err) return res.status(500).send("Error in adding the information to the database.");
            res.status(200).send(user);
        });
});

Returns All the Users in the Database

router.get('/', function (req, res) {
    User.find({}, function (err, users) {
        if (err) return res.status(500).send("Error in finding the users.");
        res.status(200).send(users);
    });
});
module.exports = router;

Now, you need to let the application know that it has a UserController.js. Add this to your app.js.

Your previous app.js file

var express = require('express');
var app = express();
var db = require('./db');

Add These two  Lines to the app.js file

var UserController = require('./user/UserController');
app.use('/users', UserController);
module.exports = app;

Get a Single User From the Database

UserController.js

router.get('/:id', function (req, res) {
    User.findById(req.params.id, function (err, user) {
        if (err) return res.status(500).send("Error in finding the user.");
        if (!user) return res.status(404).send("No user found.");
        res.status(200).send(user);
    });
});

We have now added another GET request, the router.get method’s first parameter. It now has a value consist of a colon followed by some text. The value passed to ‘/: id’ will be accessible through the req.params object. Where the name of the query parameter will get mapped to a property with the same name on the req.params object.

Mongoose has a method called .findById which is will use  ID by which it will return a user information. The ID is the first parameter and the callback function is the second parameter. All the Mongoose methods want a value as a first parameter and a callback function as the last parameter. This callback will be called after the database has returned the query value. The same can be done with the DELETE request as well.

Delete a User From the Database

UserController.js

router.delete('/:id', function (req, res) {
    User.findByIdAndRemove(req.params.id, function (err, user) {
        if (err) return res.status(500).send("Error in deleting the user.");
        res.status(200).send("User " + user.name + " was deleted.");
    });
});

The router.delete() method is same as the router.get(). We will remove a user from the database by giving ID of the user we want to delete. The .findByIdAndRemove() method will find a user and delete it from the database.

The final step in Our application will be updating an existing user in the database. This is done with a PUT request.

Updates a Single User in the Database

UserController.js

router.put('/:id', function (req, res) {
    User.findByIdAndUpdate(req.params.id, req.body, function (err, user) {
        if (err) return res.status(500).send("Error in updating user");
        res.status(200).send(user);
    });
});

The router.put() request is very similar to the two requests above. It also takes one query parameter and ID. It is different in a way that it also takes body parameters, just like the POST request we wrote first. The only HTTP methods which have a body are POST and PUT.

Get More Knowledge: