Hapi Js
is a powerful and robust open-source node JS framework for developing Json Api. Hapi JS is one of the most preferred frameworks for node Js due to it's well-developed plugin system.
We'll be making a Hapi Js
server from scratch using Node Js.
In order to follow this tutorial you will need to following have Node
installed - ideally at the LTS (long term support) version.
Run the following command on your terminal to check if you have node installed:
node --version
In this tutorial, I will be using Visual Studio Code as the text editor and Postman for the HTTP requests
, but feel free to use whichever tools you want.
Let's start by making running the following commands:
mkdir hapi-tutorial
cd hapi-tutorial
npm init -y
- Creates a folder called
hapi-tutorial
. - Should contain a file titled
package.json
file with the default values.
Now we have our package.json
file, let's install Hapi Js
by running the following command in our terminal:
npm i @hapi/hapi
Your package.json
file should now look something like this:
{
"name": "hapi-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@hapi/hapi": "^20.2.2"
}
}
Now we're ready to start creating our project!
Next we'll be creating 3 files: an index.js
, a server.js
and a router.js
file.
Let's do that by running the following command in your terminal:
touch index.js router.js server.js
Traditionally, you'll start from the index.js
file but for this tutorial, we'll start with the router.js
file.
Add the following code to your router.js
file:
const router = [
{
method: "GET",
path: "/",
handler: (request, h) => {
return "Hello World!";
}
}
];
module.exports = router;
We've added a router array which will store all of our endpoints. Each endpoint must contain the following:
Method
: In our case it is (GET
).Path
: We're using/
as we're just using the default path for now.Handler
: This handles our functionality. The first parameter is therequest
, which you access arguments such asbody
orparams
. The second parameter,h
is the response toolkit, which is an object with several methods used to respond to the request.
Let's add the following to our server.js
file:
const Hapi = require("@hapi/hapi");
const router = require("./router");
const server = Hapi.server({
port: 8000,
host: "localhost"
});
router.forEach((path) => server.route(path));
module.exports = server;
Let's break this down what we've done:
- We've imported Hapi and initiated our server.
- We've set our
port
to8000
andhost
to"localhost"
. - We've then imported our
router
and created a route for eachpath
.
const server = require("./server");
(async () => {
await server.start();
console.log("🚀 Server listening %s/ 🚀", server.info.uri);
})();
Let's break this down what we've done:
- We're importing our server from
server.js
- We're creating a self calling
async
function. - When the server starts, it will log the server endpoint.
So let's run our app to make sure. Let's just run this command in our terminal:
node index.js
If everything has gone according to plan, we should see the following on our terminal:
🚀 Server listening http://127.0.0.1:8000/ 🚀
Now clicking on this link http://127.0.0.1:8000
should return "Hello World!"
Controllers are the way we prevent our router file from getting cluttered.
Lets start by creating our controllers
directory and our first controller:
mkdir controllers
touch controllers/events.controllers.js
We'll call our first controller events.controllers.js
, add the following code into our events.controllers.js
file:
const events_db = [];
const getEvents = (request, h) => {
return events_db;
};
const postEvent = (request, h) => {
events_db.push(request.payload);
return "Event Created!";
};
module.exports = {
getEvents,
postEvent
};
For now we're using an empty array named events_db
to store our data.
- The
GET
request will return anything currently stored in the array. - The
POST
request will push data into this array.
Now let's update our router.js
file:
const { postEvent, getEvents } = require("./controllers/events.controllers");
const router = [
{
method: "GET",
path: "/",
handler: (req, h) => {
return "Hello World!";
}
},
{
method: "POST",
path: "/post_event",
handler: postEvent
},
{
method: "GET",
path: "/events_list",
handler: getEvents
}
];
module.exports = router;
Let's try and make a POST
request to http://127.0.0.1:8000/post_event
with the following data:
{
"name": "test event",
"adultsOnly": false,
"attendees": 100,
"description": "test description"
}
A successful POST
request should return this response:
'Event Created!'
Finally a GET
request to http://127.0.0.1:8000/events_list
should return the response:
[
{
"name": "test event",
"adultsOnly": false,
"attendees": 100,
"description": "test description"
}
]
If you restart your server, this data should be gone as we are only temporarily storing it in an array.
And that's all she wrote! Thanks for reading!