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.
Join the DZone community and get the full member experience.
Join For FreeIn 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!
Opinions expressed by DZone contributors are their own.
Comments