Yet another hapi plugin providing swagger compliant API specifications (swagger specs 2.0) based on routes and joi schemas to be used with swagger-ui.
Supports hapi 7.x and 8.x
npm install hapi-swaggered --save
krakenjs/swaggerize-hapi follows a design driven approach (swagger-schema first) for building APIs. In other words: it supports you to implement an api behind a specific swagger-schema while you have to create and maintain the swagger-schema yourself (or a third-party). In contrast with hapi-swaggered you will have to design your api through hapi route defintions and joi schemas (or did already) and hapi-swaggered will generate it's swagger specifications up on that (Of course not as beautiful and shiny structured as done by hand). Based on this you are able to get beautiful hands-on swagger-ui documentation (like this) for your api up and running (e.g. through hapi-swaggered-ui).
This plugin does not include the swagger-ui interface. It just serves a bare swagger 2.0 compliant json feed. If you are looking for an easy swagger-ui plugin to drop-in? You should have a look at:
requiredTags
: an array of strings, only routes with one of the specified tags will be exposed, defaults to:['api']
produces
: an array of mime type strings, defaults to:[ 'application/json' ]
consumes
: an array of mime type strings, defaults to:[ 'application/json' ]
endpoint
: route path to the swagger specification, defaults to:'/swagger'
routeTags
: an array of strings, all routes exposed by hapi-swaggered will be tagged as specified, defaults to['swagger']
stripPrefix
: a path prefix which should be stripped from the swagger specifications. E.g. your root resource are located under/api/v12345678/resource
you might want to strip/api/v12345678
, defaults to nullsupportedMethods
: array of http methods, only routes with mentioned methods will be exposed, in case of a wildcard * a route will be generated for each method, defaults to['get', 'put', 'post', 'delete', 'patch']
host
: string, overwrite requests host (e.g. domain.tld:1337)schemes
: array of allowed schemes e.g.['http', 'https', 'ws', 'wss']
(optional)info
: exposed swagger api informations, defaults to null (optional)title
: string (required)description
: string (required)termsOfService
: stringcontact
: object (optional)name
: stringurl
: stringemail
: string
license
: object (optional)name
: string: stringurl
: string: string
version
: version string of your api, which will be exposed (required)
tagging
: Options used for grouping routesmode
: string, can bepath
(routes will be grouped by its path) ortags
(routes will be grouped by its tags), default ispath
pathLevel
integer, in case of modepath
it defines on which level the path grouping will take place (default is 1)stripRequiredTags
boolean, in case of modetags
it defines if therequiredTags
will not be exposed (default is true)
tags
: object (or array with objects according to the swagger specs) for defining tag / group descriptions. E.g. you two endpoints/get/this
and/get/that
and the tagging mode is set to path (with pathLevel: 1) they will be groupped unter /get and you are able to define a description through this object as{ 'get': 'get this and that' }
, defaults to nullcors
: boolean or object with cors configuration as according to the hapijs documentation (defaults to false)cache
: caching options for the swagger schema generation as specified inserver.method()
of hapi, defaults to:{ expiresIn: 15 * 60 * 1000 }
responseValidation
: boolean, turn response validation on and off for hapi-swaggered routes, defaults to falseauth
: authentication configuration hapijs documentation (default to undefined)
Example configuration for hapi-swaggered + hapi-swaggered-ui
var Hapi = require('hapi')
var Joi = require('joi')
var hapiSwaggered = require('hapi-swaggered')
var hapiSwaggeredUi = require('hapi-swaggered-ui')
var server = new Hapi.Server()
server.connection({
port: 8000,
labels: ['api']
})
server.register({
register: hapiSwaggered,
options: {
tags: {
'/foobar': 'Example foobar description'
},
info: {
title: 'Example API',
description: 'Tiny hapi-swaggered example',
version: '1.0'
}
}
}, {
select: 'api',
routes: {
prefix: '/swagger'
}
}, function (err) {
if (err) {
throw err
}
})
server.register({
register: hapiSwaggeredUi,
options: {
title: 'Example API',
authorization: {
field: 'apiKey',
scope: 'query' // header works as well
// valuePrefix: 'bearer '// prefix incase
}
}
}, {
select: 'api',
routes: {
prefix: '/docs'
}
}, function (err) {
if (err) {
throw err
}
})
server.route({
path: '/',
method: 'GET',
handler: function (request, reply) {
reply.redirect('/docs')
}
})
server.route({
path: '/foobar/test',
method: 'GET',
config: {
tags: ['api'],
description: 'My route description',
notes: 'My route notes',
handler: function (request, reply) {
reply({})
}
}
})
server.route({
path: '/foobar/{foo}/{bar}',
method: 'GET',
config: {
tags: ['api'],
validate: {
params: {
foo: Joi.string().required().description('test'),
bar: Joi.string().required()
}
},
handler: function (request, reply) {
reply({})
}
}
})
server.start(function () {
console.log('started on http://localhost:8000')
})
Some configurations can be overwritten on connection level:
var Hapi = require('hapi')
var server = new Hapi.Server()
server.connection({
port: 8000,
labels: ['api'],
app: {
swagger: {
info: {
title: 'Example API',
description: 'Tiny hapi-swaggered example'
}
}
}
})
To assign custom names to your Models use the Joi.meta() option (in previous joi versions Joi.options() may be used)
Joi.object({}).meta({ className: 'FooBar' })
To achieve a file upload your route should look like as follows. (Important parts are the swaggerType in the Joi options as well as the allowed payload)
server.route({
method: 'POST',
path: '/test/fileUpload',
config: {
tags: ['api'],
validate: {
payload: Joi.object().keys({ name: Joi.string(), file: Joi.object().meta({ swaggerType: 'file' }) })
},
handler: function (request, reply) {
// handle file upload as specified in payload.output
reply({ name: request.payload.name })
},
payload: {
allow: 'multipart/form-data',
output: 'data'|'stream'|'file'
}
}
})
There are 2 and a half different ways of documenting responses of routes:
The hapi way:
{
config: {
response: {
schema: Joi.object({
bar: Joi.string().description('test').required()
}).description('test'),
status: {
500: Joi.object({
bar: Joi.string().description('test').required()
})
}
}
}
}
The plugin way without schemas:
{
config: {
plugins: {
'hapi-swaggered': {
responses: {
default: {description: 'Bad Request'},
500: {description: 'Internal Server Error'}
}
}
},
response: {
schema: Joi.object({
bar: Joi.string().required()
}).description('test')
}
}
}
The plugin way with schemas:
{
config: {
plugins: {
'hapi-swaggered': {
responses: {
default: {
description: 'Bad Request', schema: Joi.object({
bar: Joi.string().description('test').required()
})
},
500: {description: 'Internal Server Error'}
}
}
}
}
}
Specify an operationId for a route:
{
config: {
plugins: {
'hapi-swaggered': {
operationId: 'testRoute'
}
}
}
}
Routes can be filtered for tags through the tags query parameter beside the requiredTags property which is always required to be present.
For example:
?tags=public,beta (equal to ?tags=+public,+beta)
- will only show apis and routes with tag public AND/OR beta.
?tags=public,-beta (equal to ?tags=+public,-beta)
- will only show apis and routes with tag public AND NOT beta.
Please have a look at a previous README.
The routes response schemas which hapi-swaggered is parsing will be dropped by hapi whenever the response validation is disabled. In this case hapi-swaggered will not be able to show any response types. A very low sampling rate is sufficient to keep the repsonse types.