A swagger documentation UI generator plugin for hapi
npm install onestack-hapi-swagger
This is a Swagger UI plug-in for HAPI v8. When installed it will self document HTTP API interface in a project.
You can add the module to your HAPI using npm:
$ npm install hapi-swagger --save
In the .js file where you create the HAPI server object add the following code after you have created the server object:
var pack = require('../package'),
swaggerOptions = {
basePath: 'http://localhost:8000',
apiVersion: pack.version
};
server.register({
register: require('hapi-swagger'),
options: swaggerOptions
}, function (err) {
if (err) {
server.log(['error'], 'hapi-swagger load error: ' + err)
}else{
server.log(['start'], 'hapi-swagger interface loaded')
}
});
tags: ['api'] property to the route object for any endpoint you want documenting.You can even specify more tags and then later generate tag-specific documentation. If you specify tags: ['api', 'foo'], you can later use /documentation?tags=foo to load the documentation on the HTML page (see next section).
{
method: 'GET',
path: '/todo/{id}/',
config: {
handler: handlers.mapUsername,
description: 'Get todo',
notes: 'Returns a todo item by the id passed in the path',
tags: ['api'],
validate: {
params: {
username: Joi.number()
.required()
.description('the id for the todo item'),
}
}
},
}
/documentation. This page contains Swaggers UI to allow users to explore your API. You can also build custom pages on your own URL paths if you wish, see: "Adding interface into a page"The all the files in the URLs below are added by the plugin, but you must server the custom page as template using reply.view().
If you want to generate tag-specific documentation, you should change the URL from
url: window.location.protocol + '//' + window.location.host + '{{hapiSwagger.endpoint}}',
to:
url: window.location.protocol + '//' + window.location.host + '{{hapiSwagger.endpoint}}?tags=foo,bar,baz',
This will load all routes that have one or more of the given tags (foo or bar or baz). More complex use of tags include:
?tags=mountains,beach,horses
this will show routes WITH 'mountains' OR 'beach' OR 'horses'
?tags=mountains,beach,+horses
this will show routes WITH ('mountains' OR 'beach') AND 'horses'
?tags=mountains,+beach,-horses
this will show routes WITH 'mountains' AND 'beach' AND NO 'horses'
Place the HTML code below into the body fo web page where you wish the interface to render
<section id="swagger">
<h1 class="entry-title api-title">API</h1>
<div id="message-bar" class="swagger-ui-wrap"></div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</section>
* apiVersion: string The version of your API
* basePath: string The base URL of the API i.e. http://localhost:3000
* documentationPath: string The path of the documentation page - default: /documentation,
* enableDocumentationPage: boolean Enable the the documentation page - default: true,
* endpoint: string the JSON endpoint that descibes the API - default: /docs
* pathPrefixSize: number Selects what segment of the URL path is used to group endpoints - default: 1
* payloadType: string Weather accepts json or form parameters for payload - default: json
* produces: array The output types from your API - the default is: ['application/json']
* authorizations: object Containing swagger authorization objects, the keys mapping to HAPI auth strategy names. No defaults are provided.
* info: a swagger info object with metadata about the API.
* title string Required. The title of the application
* description string Required. A short description of the application
* termsOfServiceUrl string A URL to the Terms of Service of the API
* contact string An email to be used for API-related correspondence
* license string The license name used for the API
* licenseUrl string A URL to the license used for the API
An very simple example of the use of the response object:
var responseModel = hapi.types.object({
equals: Joi.number(),
}).options({
className: 'Result'
});
within you route object ...
config: {
handler: handlers.add,
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')
}
},
response: {schema: responseModel}
}
A working demo of more complex uses of response object can be found in the be-more-hapi project.
config: {
handler: handlers.add,
description: 'Add',
tags: ['api'],
jsonp: 'callback',
notes: ['Adds together two numbers and return the result'],
plugins: {
'hapi-swagger': {
responseMessages: [
{ code: 400, message: 'Bad Request' },
{ code: 500, message: 'Internal Server Error'}
]
}
},
validate: {
params: {
a: Joi.number()
.required()
.description('the first number'),
b: Joi.number()
.required()
.description('the second number')
}
}
}
validate: {
params: {
a: Joi.number()
.required()
.description('the first number'),
b: Joi.number()
.required()
.description('the second number')
},
headers: Joi.object({
'authorization': Joi.string().required()
}).unknown()
}
$ mocha --reporter list
If you are considering sending a pull request please add tests for the functionality you add or change.