Nov 16, 2016

Adding Logging and Swagger to a Hapi Node Server

I am starting to like the Hapi node server. It is a real alternative to express. In this post we are going to add logging and swagger to the Hapi server we started working on earlier. If you want to see that post, check out Hapi Server Part 1. It is not necessary if you already have a Hapi server up and running. You can still follow along, or start with the logging branch from the git hub repository: https://github.com/veggie2u/hapijoi

git checkout logging

The first thing we need to do is get the required libraries.

npm install --save good
npm install --save good-console
npm install --save good-squeeze

This will install the node modules for the good logging plugin. Good-console will do just what you think. There are others for logging to files and over http. Good-squeeze is used in the process of matching logging tags. Think log “error” vs log “debug”.

Now we need to register our plugins with the server. Edit the index.js file. Modify the part where we create the server:

Now start the server, our start up log message has changed:

161007/204210.683, [log,Server running at: http://stickers.local:9000] data: (none)

How about the response logs? Hit the server with a couple of urls.

http://localhost:9000/validate/?name=John&age=60
http://localhost:9000/validate/?name=John

You should see this in the console:

161007/204228.345, [response] http://localhost:9000: get /validate {"name":"John","age":"60"} 400 (27ms)
161007/204308.731, [response] http://localhost:9000: get /validate {"name":"John"} 200 (9ms)

There you go, basic logging to the console. Check the good project for more options [https://github.com/hapijs/good]

Now for swagger. What is swagger, why would I want it? If you are creating an API for others to use, whether it is internal or external to the company, you will need some sort of documentation. What url’s or routes are exposed, what parameters can I send? Swagger allows you to put a web interface around our routes. The really cool thing is that it uses the Joi code we put in last time to report the available parameters.

Switch to the swagger branch, or start coding.

The first thing we will do is install the modules necessary to view the swagger documentation.

npm install hapi-swagger --save
npm install inert --save
npm install vision --save

Other than the base swagger plugin, there were a couple of other things needed to make swagger useful. Inert is a useful plugin in it’s own right, as it allows you to serve static resources like html files. Vision is a plugin to support templating within Hapi. It supports engines such as Handlebars and Mustache. We are not going to worry about these now. Just know that they are used by the hapi-swagger plugin to create the api page we will see in a minute.

Now we have to adjust our config to use these new plugins.

The server.register method can also take an array. This is the new method, taking that approach. We are passing an array of registration objects to the register method. This way we can register the logging and swagger plugins together with their own options.

The very end of the server.register method there is one new item. Just like when we start the server, this method allows us to be notified if an error occurred when registering our plugins.

Lets take a look. Head to the documentation url.

http://localhost:9000/documentation
Empty Swagger API

Empty Swagger API

Tada! Well, maybe we need a bit more to be useful. I am sure you noticed that none of our api endpoints are documented. We need to let the hapi-swagger plugin know which endpoints we want documented by adding a tag of ‘api’ to our routes.

Lets modify our simple hello world default route. It doesn’t have a config block, so we will add one like this:

The config block has 3 lines. The tag line is the only required one. The documentation and notes are optional. You will have to restart the node server for it to pick up on the changes to the endpoint. Now go take a look.

It you haven’t seen swagger before, click around. You can even submit the request right from the documentation.

Now, if you remember, I said that the swagger plugin would use the joi config. Lets do that now. Lets update the ‘/validate’ method (hello query parameter with validation). The config block should look like this:

After restarting the server and heading back to the /documentation endpoint, you will see both of our example endpoints. The /validate one will show that the endpoint takes two arguments, a string, and an integer, and the name is required.

Swagger Screen Shot

Swagger Screen Shot

Pretty cool. Swagger is showing some information, but not all of the validations. One way to include these is manually adding a documentation attribute to each parameter. Not ideal, but this is how it would look:

Well, that’s enough to get you going with creating api’s in Hapi for now.

About the Author

Chris Ward profile.

Chris Ward

Sr. Consultant

Chris has been programming computers since the Commodore 64 as a kid. He has spent much of his career on the JVM with Java, Groovy, and Grails creating backend services for several companies in the the twin cities. Based on interest and a desire to learn new things, he has branched out into the Javascript realm. The last few years, Chris has been using Angular to create more functional and dynamic front end applications for his clients, as well as creating Node based services on the backend. Recently, just for fun, Chris has been getting into robotics and Iot.

One thought on “Adding Logging and Swagger to a Hapi Node Server

  1. yson says:

    Good article, Thanks !

Leave a Reply

Your email address will not be published.

Related Blog Posts
Building Better Data Visualization Experiences: Part 1 of 2
Through direct experience with data scientists, business analysts, lab technicians, as well as other UX professionals, I have found that we need a better understanding of the people who will be using our data visualization products in order to build them. Creating a product utilizing data with the goal of providing insight is fundamentally different from a typical user-centric web experience, although traditional UX process methods can help.
Kafka Schema Evolution With Java Spring Boot and Protobuf
In this blog I will be demonstrating Kafka schema evolution with Java, Spring Boot and Protobuf.  This app is for tutorial purposes, so there will be instances where a refactor could happen. I tried to […]
Redis Bitmaps: Storing state in small places
Redis is a popular open source in-memory data store that supports all kinds of abstract data structures. In this post and in an accompanying example Java project, I am going to explore two great use […]
Let’s build a WordPress & Kernel updated AMI with Packer
First, let’s start with What is an AMI? An Amazon Machine Image (AMI) is a master image for the creation of virtual servers in an AWS environment. The machine images are like templates that are configured with […]