Build a RESTful API using hapijs and mongoose
Tags: api, hapijs, mongoose, database
Published: 2018-10-24 07:52:08

---
title: Build a RESTful API using hapijs and mongoose
published: true
description: This article is about building RESTful API using hapijs and mongoose.
tags: API, hapijs, mongoose, database
---

The API will handle CRUD for an object[[Wolf](https://en.wikipedia.org/wiki/Wolf_%28disambiguation%29)], Using the HTTP verbs — GET, PUT, POST and DELETE

Okay, Let’s start
> Make sure you’ve node installed in your machine and yarn as a global package

Create a project directory name “/hapijs-mongoose-restapi” and run the command and fill the required details.

    yarn init

> Specify the main file as app.js

yarn init is similar to npm init, this will generate the package.json file, Refer [yarn](https://yarnpkg.com/) for more.

then install the node_modules we need for this API

    yarn add hapi mongoose --dev

Building the hapi server, In the app.js

    const Hapi = require('hapi');
    const server = new Hapi.Server();

    server.connection({
        host: 'localhost',    
        port: 4000
    });
    
    server.route({
        method: 'GET',
        path: '/',
        handler(request, reply) {
    	reply('Hello, world!');
        }
    });
    
    server.route({
        method: 'GET',
        path: '/api',
        handler(request, reply) {
    	reply('Hello, API!');
        }
    });
    
    server.start(err => {
        if (err) {
    	throw err;
        }
        console.log(`Server running at: ${server.info.uri}`);
    });
    
    exports.server = server;

* server.connection — To connect to the server with the host and port

* server.route — Will contain the route object
> In the server.router, the handler will return using the return() API — [http://hapijs.com/api#replyerr-result](http://hapijs.com/api#replyerr-result), where the return is used to conclude the handler activity by setting a response and returning the response and status to the handler.

* server.start — To start the server

Starting the server and testing the index route

    nodemon app.js
[**Using nodemon for auto-reload of server after code change for node.js applications**
*Was a newbie to node.js, whenever I make a change in the code, In the terminal i used to keep on hitting Ctrl+C and…*medium.com](https://medium.com/jsessentials/using-nodemon-for-auto-reload-of-server-after-code-change-74c9901a1d98)

Let’s test the API using [Postman](https://www.getpostman.com/) — Chrome App/Mac App.

open Postman, select the **GET** HTTP verb and enter the url [http://localhost:4000](http://localhost:4000) and click Send, the response body should show **Hapi World!**.

Create a mongoDB connection to the API, create a file database.js in the root directory of the app

    var Mongoose = require('mongoose');

    //load database
    Mongoose.connect('mongodb://localhost/hapijs-mongoose-restapi/');
    var db = Mongoose.connection;

    db.on('error', console.error.bind(console, 'connection error'));
    db.once('open', function callback() {
        console.log('Connection with database succeeded.');
    });

    exports.db = db;

and include the database.js in app.js

    // app.js

    const db = require('./database').db;

This will connect to the mongoDB and then let’s create the mongoose schema model for our wolves, the models was placed in /models directory

### THE WOLF MODEL

the path to create the Wolf Model is — /hapijs-mongoose-restapi/models/Wolf.js

The Wolf model will be just having the **name** field where the SchemaType is String.

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;

    var WolfSchema = new Schema({
        name: String
    });

    module.exports = mongoose.model('Wolf', WolfSchema);

with the Wolf.js model created, require this in the app.js

    // app.js

    const Hapi = require('hapi');
    const server = new Hapi.Server();
    const db = require('./database').db;

    ...

The nodemon will be in action here, it will watch for you changes in any of the file in the app directory and restarts the server for you, no CTRL+C hazzle.

### ROUTES — Default API Route

URL — [http://localhost:4000/api](http://localhost:4000/api)

    // app.js

    ...

    server.route({
        method: 'GET',
        path: '/api',
        handler: function (request, reply) {
            reply({'message': 'Hello, API!'});
        }
    });

### ROUTES

Create a routes.js file and include that file in app.js

    // routes.js

    module.exports = [];

then include this routes.js into the app.js file

    // app.js

    …

    const routes = require(‘./routes’);
    server.route(routes);

### The GET Route — GETTING ALL WOLVES

Require the Wolf model onto the router.js

URL —[ http://localhost:4000/api/wolves](http://localhost:4000/api/wolves)

    // routes.js

    const Wolf = require('./models/Wolf');

    module.exports = [
      {
          method: 'GET',
          path: '/api/wolves',
          handler: function (request, reply) {
              Wolf.find(function(error, wolves) {
                  if (error) {
                      console.error(error);
                  }

                  reply(wolves);
              });
          }
      }
    ];

This is a simple route — which will render all the wolves in JSON format.

### The POST Route — SAVING A WOLF

In the routes.js, create a module for POST which is for saving the Wolf

URL —[ http://localhost:4000/api/wolves/GrayWolf](http://localhost:4000/api/wolves/GrayWolf)

    // routes.js

    const Wolf = require('./models/Wolf');

    module.exports = [
      {
          method: 'GET',
          path: '/api/wolves',
          handler: function (request, reply) {
              Wolf.find(function(error, wolves) {
                  ...
              });
          }
      },
      {
          method: ['PUT', 'POST'],
          path: '/api/wolves/{name}',
          handler: function (request, reply) {          
              const wolf = new Wolf({
                  name: request.params.name
              });
              wolf.save(function(error, wolf) {
                if (error) {
                    console.error(error);
                }

                reply(wolf.id);
              });
          }
      }
    ];

This will return the object id which is created in the mongoDB.

You can find the source code [here](https://github.com/chetanraj/hapijs-mongoose-restapi).

### Conclusion

We now have the ways to handle CRUD on Wolves using hapiJS.

Please go js-rest-api on that heart icon which is below this post and if you have any questions please comment below.

<iframe src="https://medium.com/media/22a2a9fb4a1ff3a1485ebea72af73070" frameborder=0></iframe>