How to make API Documentation in Hapi.js

Arsy Opraza
UNIKOM Codelabs
Published in
2 min readOct 31, 2021

--

In this post, I will share how to make API Documentation in Hapi.js

You can make API Documentation in Hapi.js using Swagger, Swagger is an open-source and pro tool that have helped millions of API developers,
teams and organizations deliver great APIs.

Install Swagger in Hapi Project

We will install the most popular library in Hapi framework that named hapi-swagger with the following command:

npm install hapi-swagger — save

If you want to view your API documentation with HTML format you need to install some plugins with the following command:

npm install @hapi/inert --save
npm install @hapi/vision --save

Configuration Swagger

The first thing you will do is import hapi-swagger, inert, vision plugins to the main Javascript file, in this example I imported in server.js file with the following code:

const HapiSwagger = require('hapi-swagger');
const Inert = require('@hapi/inert');
const Vision = require('@hapi/vision');

Then, make a configuration for swagger object like a version name and version number with the following code:

const swaggerOptions = {
info: {
title: 'Music API Documentation',
version: '0.0.1',
}
};

And we need to register all plugins and configurations to the server instance with the following code:

await server.register([
Inert,
Vision,
{
plugin: HapiSwagger,
options: swaggerOptions
},
]);

Configuration API Routes

We can add tags, descriptions, and notes to API Routes. Simply add the tags: ['api']property to the route object for any endpoint you want documenting to structure your API Documentation. And describe your endpoint by simply adding an description:. For example, you can see the following code below:

const routes = (handler) => [
{
method: 'POST',
path: '/songs',
options: {
description: 'Add song',
notes: 'Returns an array of books',
tags: ['api'],
handler: handler.postSongHandler,
}
},
];

For other routes, you can do the same method.

Testing API Documentation

You can test your documentation with add /documentation in your URL, so the full URL would be like this:

http://localhost:5000/documentation

Open your browser, and the result will be like this:

And you can test your endpoint too:

--

--