Build REST APIs with Hapi.js and MongoDB
I search google for “node framework for writing APIs”. So, Google gives me many options as Express, Koa, Hapi, Restify and so more. I choose Hapi and start to explore Hapi. Hapi.js is a good choice for a newbie.
About Hapi.js
Hapi.js is Node framework for writing reusable applications and services. Hapi.js developed at WalmartLabs and Lead by Eran Hammer.
Pre-requirements
- NodeJS
- MongoDB ( install MongoDB, if not installed on your device )
- Hapi.js
Verify NodeJS
first, verify node is installed on your local machine or not. I already installed node v7.7.3 and Node version must be > v4.0
C:\Users\Danish>node -v
v7.7.3
Setup Hapi.js
mkdir hapiprojectcd hapiprojectnpm initnpm install --save hapi
–save will save project dependencies in package.json. that’s all for hapi.js now. So, lets write basic code to run a hapi server on localhost with 3000 port. create a file name app.js in the hapiproject directory.
hapiproject/app.js
'use strict';const Hapi = require('hapi');const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });server.start((err) => { if (err) {
throw err;
}
console.log('Server Running at : ', server.info.uri);
});
Open your command line and run the command node app.js. this will return console message if all goes well.
Now your hapi server is running here http://localhost:3000/ but when you open in your browser it will return a JSON data. Because of no route assign to this server.
{
"statusCode": 404,
"error": "Not Found"
}
Setup Route to the Hapi Server
'use strict';const Hapi = require('hapi');const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});server.start((err) => { if (err) {
throw err;
}
console.log('Server Running at : ', server.info.uri);
});
In server.route({}) three parameters passing method, path, and handler. method: there any mostly used methods are GET, POST, DELETE, PUT. path: is defined as route mean which routes you want to assign ‘/’ = root node. handler: in handler section, you can define you function that you want to execute to that route.
npm app.js
http://localhost:3000/ will reply with “Hello World”.