How to create a restful api using nodejs and hapi framework

How to create a restful api using nodejs and hapi framework

Hapi framework is popular Nodejs framework. In this tutorial we are going to explore how to create a restful API using nodejs and hapi framework. In a previous Nodejs loopback restful api with authentication tutorial, loopback framework is used.

Following tasks are performed in this tutorial.

1. What is hapi framework?

2. Install and run NodeJS

3. Install and run MongoDB

4. Create a database in mongoDB

5. Create a nodejs project

6. install required modules hapi, joe, mongoose and nodemon

7. Create a restful API using nodejs and hapi framework

nodejs hapi framework tutorial

 What is hapi framework?

According to https://hapijs.com/ it is a framework to create reusable application logic for developers. It has great resources for developers. Visit hapijs website to read more about the framework.

Install and run NodeJS

To create a restful API using nodejs and hapi framework, you need to install nodejs on your computer. Visit NodeJS website, download and install it. To verify the installation, open command prompt and type the command. This command shows the latest nodejs version installed.

node -v

Install and run MongoDB

Visit MongoDB Download Center, download and install mongodb. To read detailed instructions on running mongodb locally, visit MongoDb section of  nodejs user registration tutorial.

Create a MongoDB database

To create a database dbbooks in MongoDB.

use dbbooks;

To display all databases.

show dbs;

Display all tables

To view tables in a Mongdb database.

show tables;

Insert books in books table

To add records in database insert query is used.

db.books.insert({"title": "Introduction to Computer Science", price: 32, "author": "Author1", "category":"Computer science"});

Display books records

To display all the records in a database. Run the find command.

db.books.find().pretty();

 

nodejs hapi framework tutorial -mongodb book added

Create  a NodeJS project

Open a command line window. Create a new directory nodejs-hapi-framework-tutorial.

mkdir nodejs-hapi-framework-tutorial

Change directory by using cd command.

cd nodejs-hapi-framework-tutorial

Type on command line.

npm init -y

This command creates and initializes a package.json file with default values.

nodejs hapi framework tutorial - package.json

The entry point of this project is specified in as index.js.

Install required modules

We need to install hapi, joi and mongoose modules. Joi is a object schema description language, It is used to validate a JavaScript object. In this tutorial joi module is used to perform validation. Mongoose module is used to connect nodejs application to a mongodb database asynchronously.

npm install hapi --save;
npm install joi --save;
npm install mongoose --save;

Install nodemon module

Nodemon module is a tool that automatically restarts a nodejs app if a file is changed.

npm install nodemon --save-dev

Create index.js file

Open the project in your favorite text editor like sublime text or visual studio code. Create a file named index.js.

const hapi = require('hapi');
const joi = require('joi');
const mongoose = require('mongoose');

Hapi, joi and mongoose modules are included first.

Connect to mongodb database

Connect the app to mongodb. Database host is localhost and database name is dbbooks.

mongoose.connect("mongodb://localhost/dbbooks", { useNewUrlParser: true });

Create a books model

After database connection is successfully created, create a model for the books.

const BookModel = mongoose.model("book", {
    title: String,
    price: Number,
    author: String,
    category: String
});

In mongoose model, first parameter is the name of model and second parameter is an object. Object contains properties of a book model. Title, author and category are defined as string and price as number.

Fetch all books route

We are going to create a GET /book route to fetch books records from database using nodejs and hapi framework.

server.route({
    method:"GET",
    path:"/book",
    handler: async (request, resp) => {
        try{
           let books = await BookModel.find().exec();
           return resp.response(books);
        } catch(error) {
           return resp.response(error).code(500);
        }
    }
});

In server.route method, HTTP method is GET and path or route is /book. Next a handler is defined to handle the request.

To use handler as a promise, aysnc keyword is used. In the handler a try catch block is created to catch the errors. In try block BookModel‘s find method fetches all book records.

The await method before the books model, fetches the books records asynchronously from database. The next line of code will not execute until the result is returned. Books data is returned using response object’s response method. In case of error, status code of 500 is returned.

Fetch a single book record

To fetch a single book data, a book/{id} route is created. In this route, id is book id.

server.route({
    method:"GET",
    path:"/book/{id}",
    handler: async (request, resp) => {
        try{
           let book = await BookModel.findById(request.params.id).exec();
           return resp.response(book);
        } catch(error) {
           return resp.response(error).code(500);
        }
    }
});

The HTTP method in handler is GET and path is /book/{id}. findByid method is used with an id parameter. id parameter is passed via GET route using request.params.id. Data is returned on success or error code 500 is returned.

 Create a new book record

To create a new book record in database, add code to the index.js file.

server.route({
    method:"POST",
    path:"/book",
    options: {
        validate: {
            payload:{
              title: joi.string().required(),
              price: joi.number().required(),
              author: joi.string(),
              category: joi.string().required()
            }, 
            failAction: (request, resp, error) => {
                return error.isJoi ? resp.response(error.details[0]).takeover() : resp.response(error).takeover();
            }
        }
    },
    handler: async (request, resp) => {
        try{
           let book = new BookModel(request.payload);
           let result = await book.save();
           return resp.response(result);
        } catch(error) {
           return resp.response(error).code(500);
        }
    }
});

Route is /book using HTTP POST method. The options object has validate object. Set the payload object with properties title, price, author and category as required.

failActon method is defined with parameters request, response. If Error.isJoi is true then error is returned to the client. In handler’s async method, a book model is created.

Data is saved using book models ‘s save method. Result is returned on success or an error is returned in case of failure.

Edit a book record

To update a record, HTTP PUT method is used in nodejs hapi framework tutorial. In options parameter validate object with properties is defined. Route path is defined as book/{id}. FinByIDandUpdate method saves the updated data.

server.route({
    method:"PUT",
    options: {
        validate: {
            payload:{
              title: joi.string().optional(),
              price: joi.number().optional(),
              author: joi.optional(),
              category: joi.string().optional()
            }, 
            failAction: (request, resp, error) => {
                return error.isJoi ? resp.response(error.details[0]).takeover() : resp.response(error).takeover();
            }
        }
    },
    path:"/book/{id}",
    handler: async (request, resp) => {
        try{
          let result = await BookModel.findByIdAndUpdate(request.params.id, request.payload, {new : true});
          return resp.response(result);
        } catch(error) {
           return resp.response(error).code(500);
        }
    }
});

Delete a book record

To remove a book record, HTTP DELETE method is used. Route path is book/{id}. Id param is passed to FindByIdAndDelete method. Response is returned on success or failure.

server.route({
    method:"DELETE",
    path:"/book/{id}",
    handler: async (request, res) => {
        try{
            let result = await BookModel.findByIdAndDelete(request.params.id);
            return res.response(result);
        } catch(error) {
           return resp.response(error).code(500);
        }
    }
});

Start hapi nodejs Server

To start a server on port 3000 server.start method is used.

server.start(err => {
    if(err){
        throw err;
    }

    console.log('Server started')
});

Running nodejs and hapi framework app

For running the application.

nodemon

Testing application using postman

To test our application, we are going to use postman. Postman is a tool to test APIs. You can download Postman from this download page.

Testing fetch all books

Open postman, select GET from drop down and type URL in address bar.

http://localhost:3000/book

Click Send button. You can view list of books as a JSON response. On the bottom status code 200 is displayed.

nodejs and hapi framework tutorial - fetch all books

 

Find single book record

In order to find a single book record, you need to use the same route with GET HTTP verb but Add book id in end of URL. Click Send button and data is returned as JSON.

http://localhost:3000/book/5cd687f21e7eb15a343ada19

nodejs hapi framework tutorial - find a book

Add a new book

In the drop down select POST HTTP method. Add http://localhost:3000/book URL in address bar.  Select body and then raw, addempty object { }. Data validation is performed and error messages are returned to client.

nodejs hapi framework tutorial - add book title validation

 

 

Add new book record

Add title, price, author and category as an object and click Send button. In reply you can view the id generated by database.

{
  "title": "Introduction to Algorithms",
  "price":  29.0,
  "author": "author 4",
  "category": "Computer Science"
}

 

nodejs hapi framework tutorial - add book

 

Update a book

To update a book record, select PUT from HTTP methods drop down. Add id of book to the end of URL. Click body and click raw. Add updated data. Click Send button. Data is saved to the database and updated data is returned to the client.

nodejs hapi framework tutorial - update book

Delete a book

Select DELETE from drop down. Add id of the book at the end of the URL. Click Send button. Data is removed from database.

nodejs hapi framework tutorial - delete book

Summary

In this nodejs hapi framework tutorial you have created a restful API and performed fetch, add, edit and delete actions. You can clone or download the source code at this GitHub repository.

nodejs hapi framework tutorial source code github

Like our Facebook page, follow us on twitter or subscribe to our newsletter to stay updated on upcoming tutorials.

 

 

Related tutorials

 

Previous tutorial