How to use swagger in node.js hapi framework
Swagger is the good and effective way to create documentation of your project.
Step 1: Install hapi-swagger:
$ npm install hapi-swagger —save
Step 2: Add option after the creation of server object :
swaggerOptions = {
basePath: 'http://localhost:8000',
apiVersion: pack.version
};
server.pack.register({
plugin: require('hapi-swagger'),
options: swaggerOptions
}, function (err) {
if (err) {
server.log(['error'], 'Plugin "hapi-swagger" load error: ' + err)
}else{
server.log(['start'], 'Swagger interface loaded')
}
});
Step 3: Add details in api :
server.route({
method : 'GET',
path: '/fav' ,
handler : function(req,res){
res("Wow finally executed fav ")
},
config: {
description: 'Add',
tags: ['api'],
notes: ['Adds together two numbers and return the result'],
validate: {
params: {
a: joi.number()
.required()
.description('the first number'),
b: joi.number()
.required()
.description('the second number')
}
}
}
})
Step 4: Add swagger-ui :
Move “swagger-ui” folder from “/node_modules/hapi-swagger/public” to new folder “/static”
server.route({
method: 'GET',
path: '/{path*}',
handler: {
directory: { path: './static', listing: false, index: true }
}
})
Step 5: Hit “localhost:8088/swaggerui/”
Step 6: Enter localhost:8088/docs” in search options.