Getting Started With Swagger and Hapi


hapi nodejs swagger Tutorials

If you want to create a documentation for API in your Hapi project, you can use the Swagger. Swagger is open-source tool to create documentation for REST API services.

I already told how to create a simple REST API with Hapi, so we will continue with an existing code.

Adding Swagger to Hapi project

The most popular library for Hapi framework its hapi-swagger. We can install it using the following:

npm i hapi-swagger -s

Because, the hapi-swagger will generate a documentation as HTML files for our API, we need install some important Hapi plugins:

npm i inert vision -s

Configuring Swagger options

First of all, you need to import the hapi-swagger, vision and inert modules to index.js:

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

and create a configuration object for Swagger. It will contain the name of our documentation and the version number, we want to specify:

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

After all these actions, we need to register (before server starts) all plugins and Swagger configuration. We can do this using the ‘register’ method of server instance:

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

Adding description, tags, notes to API routes

We are one step away from testing. Now we can add description, tags, notes to our routes. The tags _property is the simplest way to structure your API documentation in Swagger. Let’s take one route, for example GET /books _and add more information what is it doing for client:

server.route({
    method: 'GET',
    path: '/books',
    options: {
    	description: 'Get books list',
        notes: 'Returns an array of books',
        tags: ['api'],
        handler: async (request, h) => {
            const books = await readFile('./books.json', 'utf8');
            return h.response(JSON.parse(books));
        }
    }
});

Using the example above, do the same with other POST/PUT/DELETE routes.

Testing documentation

When you start your server in the terminal using the:

node index.js

the hapi-swagger plugin will generate a new page for documentation. By default - /documentation. In our case - localhost:3000/documentation

When you open the browser on this page, you will see the beautifully structured documentation. For me, the browser shows the following:

Swagger API doc in Hapi project

You can even test your api:

Open the route and test it in your Hapi project

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus