Getting Started With Swagger and Hapi

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:

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

Configuring Swagger options

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

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

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:

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:

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:

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
Swagger API doc in Hapi project

You can even test your api:

Open the route and test it in your Hapi project
Open the route and test it in your Hapi project

If you liked this, please help spread the word by hitting the recommend button below. Thanks!