Yet another hapi plugin providing swagger compliant API specifications based on routes and joi schemas to be used with swagger-ui.
JavaScript Makefile
Latest commit fe10f44 Jul 22, 2016 @z0mt3c 2.7.0
Permalink
Failed to load latest commit information.
lib standard@6 Feb 7, 2016
test Update dependencies Jul 22, 2016
.gitignore Adding maxLength, minLength to outputted swagger, if a property is a … Jan 7, 2016
.npmignore npmignore Oct 15, 2014
.travis.yml build targets Nov 22, 2015
LICENSE.txt Create LICENSE.txt Nov 24, 2015
Makefile Tests Apr 22, 2015
README.md ES6 Jan 22, 2016
index.js ES6 Jan 22, 2016
package.json 2.7.0 Jul 22, 2016

README.md

hapi-swaggered

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 10.x and up

Build Status Coverage Status Dependency Status js-standard-style npm downloads

Install

npm install hapi-swaggered --save

Similar swagger-projects for hapi

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).

Swagger-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:

Plugin Configuration

  • requiredTags: an array of strings, only routes with all 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 null
  • basePath: string, optional url base path (e.g. used to fix reverse proxy routes)
  • supportedMethods: 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: string
    • contact: object (optional)
      • name: string
      • url: string
      • email: string
    • license: object (optional)
      • name: string: string
      • url: string: string
    • version: version string of your api, which will be exposed (required)
  • tagging: Options used for grouping routes
    • mode: string, can be path (routes will be grouped by its path) or tags (routes will be grouped by its tags), default is path
    • pathLevel integer, in case of mode path it defines on which level the path grouping will take place (default is 1)
    • stripRequiredTags boolean, in case of mode tags it defines if the requiredTags 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 null
  • cors: 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 in server.method() of hapi, defaults to: { expiresIn: 15 * 60 * 1000 }
  • responseValidation: boolean, turn response validation on and off for hapi-swaggered routes, defaults to false
  • auth: authentication configuration hapijs documentation (default to undefined)

Example (Hapi 9 and 10)

Example configuration for hapi-swaggered + hapi-swaggered-ui

var Hapi = require('hapi')

var server = new Hapi.Server()
server.connection({
  port: 8000,
  labels: ['api']
})

server.register([
  require('inert'),
  require('vision'),
  {
    register: require('hapi-swaggered'),
    options: {
      tags: {
        'foobar/test': 'Example foobar description'
      },
      info: {
        title: 'Example API',
        description: 'Powered by node, hapi, joi, hapi-swaggered, hapi-swaggered-ui and swagger-ui',
        version: '1.0'
      }
    }
  },
  {
    register: require('hapi-swaggered-ui'),
    options: {
      title: 'Example API',
      path: '/docs',
      authorization: {
        field: 'apiKey',
        scope: 'query', // header works as well
        // valuePrefix: 'bearer '// prefix incase
        defaultValue: 'demoKey',
        placeholder: 'Enter your apiKey here'
      },
      swaggerOptions: {
        validatorUrl: null
      }
    }
  }], {
    select: 'api'
  }, function (err) {
  if (err) {
    throw err
  }

  server.route({
    path: '/',
    method: 'GET',
    handler: function (request, reply) {
      reply.redirect('/docs')
    }
  })

  server.start(function () {
    console.log('started on http://localhost:8000')
  })
})

Demo Routes

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({})
    }
  }
})

Overwriting configuration on server level (Hapi 8)

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'
      }
    }
  }
})

Features

Model naming

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' })

File upload (Hapi 8)

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'
    }
  }
})

Document responses

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'
      }
    }
  }
}

Tag filtering

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.

Hapi 8 usage

Please have a look at a previous README.

Known issues

No repsonse types

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.