hm-hapi-swagger
This is a Swagger UI plug-in for HAPI v8.x When installed it will self document HTTP API interface in a project.
Install
You can add the module to your HAPI using npm:
$ npm install git+ssh://git@git.hakunamatata.in:node-hapi/hm-hapi-swagger.git
You can add the module to your package.json
"dependencies": { "private-repo": "git+ssh://git@git.hakunamatata.in:node-hapi/hm-hapi-swagger.git" }
Adding the plug-in into your project
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') } });
Tagging your API routes
As a project may be a mixture of web pages and API endpoints you need to tag the routes you wish Swagger to document. Simply add the 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'), } } },}
Viewing the documentation page
The plugin adds a page into your site with the route /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"
Options
There are number of options for advance use case. In most case you should only have to provide the apiVersion and basePath.
apiVersion
: string The version of your APItitle
: string The Page Titile of your APIname
: string The Name of your APIlogourl
: string The Logo of your Project this url should be public accessbasePath
: string The base URL of the API i.e.http://localhost:3000
documentationPath
: string The path of the documentation page - default:/documentation
,loginRequired
: boolean Enable the the documentation login page - default:true
,username
: string The document page username - default:hakuna
,password
: string The Password document - default:hm1234$
,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 acceptsjson
orform
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 applicationdescription
string Required. A short description of the applicationtermsOfServiceUrl
string A URL to the Terms of Service of the APIcontact
string An email to be used for API-related correspondencelicense
string The license name used for the APIlicenseUrl
string A URL to the license used for the API
Response Object
HAPI allow you to define a response object for an API endpoint. The response object is used by HAPI to both validation and description the output of an API. It uses the same JOI validation objects to describe the input parameters. The plugin turns these object into visual description and examples in the Swagger UI.
An very simple example of the use of the response object:
var responseModel = Joi.object({ equals: Joi.number(),}).meta({ 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.
Error Status Codes
You can add HTTP error status codes to each of the endpoints. As HAPI routes don not directly have a property for error status codes so you need to add them the plugin configuration. The status codes need to be added as an array of objects with an error code and description:
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') } }}
File upload
The plug-in has basic support for file uploads into your API's. Below is an example of a route with a file uplaod, the three important elements are:
payloadType: 'form'
in the plugins section creates a form for upload.meta({ swaggerType: 'file' })
add to the payload property you wish to be file uploadpayload
cnfiguration how HAPI will process file
{ method: 'POST', path: '/store/file/', config: { handler: handlers.storeAddFile, plugins: { 'hapi-swagger': { payloadType: 'form' } }, tags: ['api'], validate: { payload: { file: Joi.any() .meta({ swaggerType: 'file' }) .description('json file') } }, payload: { maxBytes: 1048576, parse: true, output: 'stream' }, response: {schema : sumModel}}
Headers and .unknown()
A common issue with the use of headers is that you may only want to validate some of the headers sent in a request and you are not concerned about other headers that maybe sent also. You can use JOI .unknown() to allow any all other headers to be sent without validation errors.
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 test
The project has a small number integration and unit tests. To run the test within the project type the following command.
$ mocha --reporter list
This is a work in progress
If you find any issue please file here on git.hakunamatat.in and I will try and fix them.