Creating a RESTful API with HapiJS and NodeJS and MYSQL

In this post we have explained about how to create a RESTful API with HapiJS and NodeJS and MYSQL. Many web applications they provide API to access their data via RESTful.  This process is called as web services. We have implemented RESTFUL API using NodeJS with MYSQL Database using Hapi JS web services.

Prerequisites:

– You have to install NodeJs latest version.
– MYSQL Database.
– Install hapi.js package.
– Install JOI package.
– Install Encryption package.
– POSTMAN chrome extension.

Step 1:

Create a sample “users” table in your localhost

CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT,
`username` varchar(50),
`password` varchar(200),
`email` varchar(200),
PRIMARY KEY (`user_id`)
);

Step 2:  

Setup Node Restful Project

Go to Terminal or Command Line, create a project folder.

mkdir node_restapi

cd node_restapi

Step 3: 

Initialize your node project, this will create a package.json file.

node init

Step 4: 

Install hapi.js plugin for Restful APIs.

npm install hapi --save

Step 5: 

Create a Node Server

'use strict';
const Hapi = require('hapi');

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

// Add the route
server.route({
    method: 'GET',
    path:'/welcome',
    handler: function (request, reply) {
    return reply('hello world');
}
});

server.start((err) => {
   if (err) {
     throw err;
   }
  console.log('Server running at:', server.info.uri);
});

Step 6:

Run Project

npm start

Open your browser and launch the following URL, you will find “welcome” result.
http://localhost:8000/welcome

Step 7:

Install MYSQL Database Connection

npm install mysql --save

Step 8:

Update mysql connecton in server.js file.

'use strict';
const Hapi = require('hapi');
const MySQL = require('mysql');

// Create a server with a host and port
const server = new Hapi.Server();

const connection = MySQL.createConnection({
     host: 'localhost',
     user: 'Your username',
     password: 'Your password',
     database: 'Your database_name'
});

server.connection({
    host: 'localhost',
    port: 8000
});

connection.connect();

Step 9:

Get Users List

// Get users list
server.route({
    method: 'GET',
    path: '/users',
    handler: function (request, reply) {
       connection.query('SELECT user_id, username, email FROM users',
       function (error, results, fields) {
       if (error) throw error;

       reply(results);
    });
  }
});

OUTPUT:

users_api

Step 10:

Validate user inputs so install JOI

npm install joi --save

Step 11:

Get particular user information 

server.route({
    method: 'GET',
    path: '/user/{user_id}',
    handler: function (request, reply) {
    const user_id = request.params.user_id;

    connection.query('SELECT user_id, username, email FROM users WHERE user_id = "' + user_id + '"',
    function (error, results, fields) {
       if (error) throw error;

       reply(results);
    });
    },
   config: {
       validate: {
        params: {
        user_id: Joi.number().integer()
       }
  }
}
});

OUTPUT:

user_record_rest_api

Step 11:

We need to encrypt the user password, bcryptjs package will provide you the salt encryption code.

npm install bcrypt --save

Step 12:

User POST form

server.route({
    method: 'POST',
    path: '/signup',
    handler: function (request, reply) {
    const username = request.payload.username;
    const email = request.payload.email;
    const password = request.payload.password;

    //Encryption
    var salt = Bcrypt.genSaltSync();
    var encryptedPassword = Bcrypt.hashSync(password, salt);

    //Decrypt
    var orgPassword = Bcrypt.compareSync(password, encryptedPassword);

    connection.query('INSERT INTO users (username,email,password) VALUES ("' + username + '","' + email + '","' + encryptedPassword + '")',
    function (error, results, fields) {
        if (error) throw error;

        reply(results);
    });
},
config: {
      validate: {
       payload: {
          username: Joi.string().alphanum().min(3).max(30).required(),
          email: Joi.string().email(),
          password: Joi.string().regex(/^[a-zA-Z0-9]{8,30}$/)
       }
    }
}
});

OUTPUT:

signup_rest_api

Step 13:

Delete a user

server.route({
    method: 'DELETE',
    path: '/user/{user_id}',
    handler: function (request, reply) {
    const user_id = request.params.user_id;
    connection.query('DELETE FROM users WHERE user_id = "' + user_id + '"',
    function (error, result, fields) {
       if (error) throw error;

       if (result.affectedRows) {
           reply(true);
       } else {
           reply(false);
       }
});
},
config: {
     validate: {
     params: {
       user_id: Joi.number().integer()
      }
     }
}
});

Thanks for reading this post. If You have any queries and please post your comments below box.

Comments

comments

phpexpertise

I’m Blogger and Programming Blog, Tutorials, PHP, MySQL, jQuery, Laravel, Wordpress and Codeigniter