DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > Creating a REST Application in Node.js With Hapi

Creating a REST Application in Node.js With Hapi

Using the hapi framework to create a REST application in Node.js, comparing the ease of use with Express.

Dursun Koç user avatar by
Dursun Koç
CORE ·
Jul. 11, 16 · Web Dev Zone · Tutorial
Like (7)
Save
Tweet
14.80K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous article, I demonstrated how to create a REST application using the Express framework, now we will be using the hapi framework. 

The prerequisites for this tutorial is a basic knowledge on Node.js and a basic understanding of REST architecture. You don't need any hapi knowledge.

We begin with creating the Node application folder first, our application name would be share, so the folder name does too. 

$ mkdir share
$ cd share

Now we can create our Node application using the npm init command.

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (share) 
version: (1.0.0) 
description: 
entry point: (index.js) app.js
test command: 
git repository: 
keywords: 
author: dursun
license: (ISC) 
About to write to /Users/dursun/workspace/share/package.json:

{
  "name": "share",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "dursun",
  "license": "ISC"
}


Is this ok? (yes) 

The next step is to add the hapi framework. Unlike Express, we do not need any additional middleware.

$ npm install --save hapi
share@1.0.0 /Users/dursun/workspace/share
└─┬ hapi@13.5.0 
  ├── accept@2.1.1 
  ├── ammo@2.0.1 
  ├── boom@3.2.0 
  ├── call@3.0.2 
  ├── catbox@7.1.1 
  ├── catbox-memory@2.0.2 
  ├── cryptiles@3.0.1 
  ├── heavy@4.0.1 
  ├── hoek@4.0.0 
  ├── iron@4.0.1 
  ├── items@2.1.0 
  ├─┬ joi@8.1.0 
  │ ├── isemail@2.1.2 
  │ └── moment@2.13.0 
  ├── kilt@2.0.1 
  ├─┬ mimos@3.0.1 
  │ └── mime-db@1.23.0 
  ├── peekaboo@2.0.1 
  ├── shot@3.1.0 
  ├── statehood@4.0.1 
  ├─┬ subtext@4.0.3 
  │ ├── content@3.0.1 
  │ ├─┬ pez@2.1.1 
  │ │ ├── b64@3.0.1 
  │ │ └─┬ nigel@2.0.1 
  │ │   └── vise@2.0.1 
  │ └── wreck@7.2.1 
  └── topo@2.0.1 

npm WARN share@1.0.0 No description
npm WARN share@1.0.0 No repository field.

Before we start coding lets have a look at our package.json file, it should appear as follows:

{
  "name": "share",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "dursun",
  "license": "ISC",
  "dependencies": {
    "hapi": "^13.5.0"
  }
}

Now it is time to create our entry application file app.js:

const Hapi = require('hapi');

var server = new Hapi.Server();

server.connection({
    port: 8000
});

Our hapi server is created and made avaliable connections on port 8000:

var sampleHandler = function(request, reply) {
    reply('Hello World');
    return;
};

var sampleHandlerWithPathVariable = function(request, reply) {
    reply('Hello '+request.params.name);
    return;
};

var sampleHandlerWithQueryParameter = function(request, reply) {
    reply('Hello '+request.query.name);
    return;
};

var sampleHandlerWithPostPayload = function(request, reply){
reply('Hello '+request.payload.name);
    return;
}


var routes = [
{
    path: '/api/share',
    method: 'GET',
    handler: sampleHandler
},
{
    path: '/api/share/{name}',
    method: 'GET',
    handler: sampleHandlerWithPathVariable
},
{
    path: '/api/share/query',
    method: 'GET',
    handler: sampleHandlerWithQueryParameter
},
{
    path: '/api/share',
    method: 'POST',
    handler: sampleHandlerWithPostPayload
}
];

server.route(routes);

We've created our handler functions and registered them to our server:

server.start(function() {
    console.log("Started server at " + JSON.stringify(server.info));
});

And finally, we started the server.

Now lets test it and see the results.

GET without any parameter and query:

$ curl -X GET http://localhost:8000/api/share 
Hello World

GET with path parameter:

$ curl -X GET http://localhost:8000/api/share/dursun
Hello dursun

GET with query parameter:

$ curl -X GET http://localhost:8000/api/share/query?name=dursun
Hello dursun

POST with body parameter:

$ curl -X POST http://localhost:8000/api/share -d "{\"name\":\"dursun\"}" --header "Content-Type: application/json"
Hello dursun

Conclusion

After seeing both Express and hapi frameworks in action, I can say that using the hapi framework for building a REST API is simpler and more concise!

REST Web Protocols application Node.js

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Utilize Python Machine Learning Models
  • What Is HttpSession in Servlets?
  • Instancio: Random Test Data Generator for Java (Part 1)
  • Servlets Listeners Introduction and Examples

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo