Getting Started With Swagger and Hapi


hapi nodejs swagger Tutorials

If you want to create documentation for API in your Hapi project, you can use Swagger. Swagger is an 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 the Hapi framework is hapi-swagger. We can install it using the following:

npm i hapi-swagger -s

Because the hapi-swagger will generate documentation as HTML files for our API, we need to 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 the 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 descriptions, 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 on what is it doing for the 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 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