Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

hapi-openapi

krakenjs1.7kApache-2.03.0.0

Design-driven apis with OpenAPI (formerly Swagger) 2.0 and hapi.

openapi, swagger, swaggerize, hapi, rest, restful, service, api, soa

readme

hapi-openapi

Build Status NPM version

Note: this project was renamed from 'swaggerize-hapi' to 'hapi-openapi'.

hapi-openapi is a design-driven approach to building RESTful services with OpenAPI (Swagger) and Hapi.

hapi-openapi provides the following features:

  • API schema validation.
  • Routes based on the OpenAPI document.
  • API documentation route.
  • Input validation.

Why "Design Driven"

There are already a number of modules that help build RESTful APIs for node with OpenAPI. However, these modules tend to focus on building the documentation or specification as a side effect of writing the application business logic.

hapi-openapi begins with the OpenAPI document first. This facilitates writing APIs that are easier to design, review, and test.

At runtime, hapi-openapi uses the API specification to build routes from previously defined paths. This ensures that everything specified is what is implemented.

Quick Start with a Generator

This guide will let you go from an api.json to a service project in no time flat.

First install generator-swaggerize (and yo if you haven't already):

$ npm install -g yo
$ npm install -g generator-swaggerize

Now run the generator.

$ mkdir petstore && cd $_
$ yo swaggerize

Follow the prompts (note: make sure to choose hapi as your framework choice).

You now have a working api and can use something like SwaggerHub to explore it.

Manual Usage

const Hapi = require('@hapi/hapi');
const Path = require("path");

const server = new Hapi.Server( { port: 3000 } );

async function init () {
  await server.register({
    plugin: require('hapi-openapi'),
    options: {
        api: Path.join(__dirname, './config/pets.json'),
        handlers: Path.join(__dirname, './handlers')
    }
  });
  await server.start();
  console.log( server.info.uri );
}

init();

Hapi Plugin

The plugin will be registered as openapi on server.plugins with the following exposed:

  • getApi() - the resolved Swagger document.
  • setHost(host) - a helper function for setting the host property on the api.

Configuration Options

  • api - a path to a valid OpenAPI 2.0 document, or a valid document in the form of an object.
  • deprecated docspath - the path to expose api docs for swagger-ui, etc. Defaults to /api-docs.
  • docs - an object used to configure the api docs route.
    • path - the path to expose api docs for swagger-ui, etc. Defaults to /api-docs.
    • auth - options auth config for this route.
    • stripExtensions - strip vendor extensions from docs. Defaults to true.
    • prefixBasePath - prefix path of docs with he OpenAPI document's basePath value. Defaults to true.
  • handlers - either a string directory structure for route handlers, object, or not set if using x-hapi-handler.
  • extensions - an array of file extension types to use when scanning for handlers. Defaults to ['js'].
  • vhost - optional domain string (see hapi route options).
  • cors - optional cors setting (see hapi route options).
  • outputvalidation - optional validate response data.

Mount Path

Api path values will be prefixed with the OpenAPI document's basePath value. This behavior can be negated if you set the option docs.prefixBasePath to false.

Handlers Directory

The options.handlers option specifies a directory to scan for handlers. These handlers are bound to the api paths defined in the OpenAPI document.

handlers
  |--foo
  |    |--bar.js
  |--foo.js
  |--baz.js

Will route as:

foo.js => /foo
foo/bar.js => /foo/bar
baz.js => /baz

Path Parameters

The file and directory names in the handlers directory can also represent path parameters.

For example, to represent the path /users/{id}:

handlers
  |--users
  |    |--{id}.js

This works with directory names as well:

handlers
  |--users
  |    |--{id}.js
  |    |--{id}
  |        |--foo.js

To represent /users/{id}/foo.

Handlers File

Each provided javascript file should export an object containing functions with HTTP verbs as keys.

Example:

module.exports = {
    get: function (req, h) { ... },
    put: function (req, h) { ... },
    ...
}

Optionally, pre handlers can be used by providing an array of handlers for a method:

module.exports = {
    get: [
        function p1(req, h) { ... },
        function handler(req, h) { ... }
    ],
}

Handlers Object

The directory generation will yield this object, but it can be provided directly as options.handlers.

Example:

{
    'foo': {
        'get': function (req, h) { ... },
        'bar': {
            'get': function (req, h) { ... },
            'post': function (req, h) { ... }
        }
    }
    ...
}

X-Hapi-Handler

Alternatively the API document can set x-hapi-handler attribute on each defined paths element if handlers is not defined.

Example:

"/pets/{id}": {
    "x-hapi-handler": "./routes/pets-by-id.js",
    .
    .
    .

This will construct a handlers object from the given x-hapi-handler files.

X-Hapi-Options

There is now support at the operations level for x-hapi-options which represent individual Hapi Route Optijons.

This support is limited to configuration supported by the JSON file type.

Example:

"/internal": {
  "post": {
    "x-hapi-options": {
      "isInternal": true
    }
    .
    .
    .

Authentication

Support for OpenAPI security schemes requires that relevant authentication scheme and strategy are registered before the hapi-openapi plugin. See the hapi docs for information about authentication schemes and strategies.

The name of the hapi authentication strategy is expected to match the name field of the OpenAPI security requirement object.

Example:

securityDefinitions:
  api_key:
    type: apiKey
    name: Authorization
    in: header
paths:
  '/users/':
    get:
      security:
        - api_key: []
const server = new Hapi.Server();

await server.register({ plugin: AuthTokenScheme });

server.auth.strategy('api_key', 'auth-token-scheme', {
    validateFunc: async function (token) {
      // Implement validation here, return { credentials, artifacts }.
    }
});

await server.register({
    plugin: require('hapi-openapi'),
    options: {
        api: require('./config/pets.json'),
        handlers: Path.join(__dirname, './handlers')
    }
});

X-Hapi-Auth

Alternatively it may be easier to automatically register a plugin to handle registering the necessary schemes and strategies.

x-hapi-auth-schemes

The root document can contain an x-hapi-auth-schemes object specifying different plugins responsible for registering auth schemes.

Example:

"x-hapi-auth-schemes": {
    "apiKey": "../lib/xauth-scheme.js"
}

This plugin will be passed the following options:

  • name - the auth scheme name, in this example apiKey.

x-hapi-auth-strategy

The securityDefinitions entries can contain an x-hapi-auth-strategy attribute pointing to a plugin responsible for registering auth strategies.

Example:

"securityDefinitions": {
  "api_key": {
    "x-hapi-auth-strategy": "../lib/xauth-strategy.js",
    "type": "apiKey",
    "name": "authorization",
    "in": "header"
  }
}

The plugin will be passed the following options:

  • name - the securityDefinitions entry's key. In this example, api_key. This is typically used as the strategy name.
  • scheme - the securityDefinitions type. In this example, apiKey. This should match a x-hapi-auth-scheme name.
  • where - securityDefinitions entry in attribute. This is search for the lookup value; in this example header.
  • lookup - securityDefinitions entry name attribute. Used as the name to look up against where.

The way you can make these play together is that for every type, a scheme exists that delegates some lookup or evaluation to the appropriate strategy.

Example:

//xauth-scheme.js

const register = function (server, { name  }) {
    server.auth.scheme(name /*apiKey*/, (server, /* options received from the strategy */ { validate }) => {
        return {
            authenticate: async function (request, h) {
                return h.authenticated(await validate(request));
            }
        };
    });
};

module.exports = { register, name: 'x-hapi-auth-scheme' };

and

//xauth-strategy.js

const Boom = require('@hapi/boom');

const register = function (server, { name, scheme, where, lookup }) {
    server.auth.strategy(name, /* the scheme to use this strategy with */ scheme, {
        //Define a validate function for the scheme above to receive
        validate: async function (request) {
            const token = request.headers[lookup];

            //Some arbitrary example
            if (token === '12345') {
                return { credentials: { scope: ['read'] }, artifacts: { token } };
            }

            throw Boom.unauthorized();
        }
    });
};

module.exports = { register, name: 'x-hapi-auth-strategy' };

changelog

3.0.0

  • Preliminary OpenAPI 3 support

2.0.2

  • Don't set undefined parameters on request in routeExt (#180)
  • Update enjoi and @hapi/joi to Joi 17 (#176)

2.0.1

  • Removed left over console.log file
  • Fixed unknown being used on all joi schemas as opposed to just objects

2.0.0

  • [BREAKING] Upgraded hapi support to v19 and other dependencies (#173)

1.2.6

  • Reduced package size

1.2.5

  • Support api level security definitions #162
  • Better cors support #159

1.2.4

1.2.3

  • Fixes #156
  • Fixes #153
  • Fixes #152

1.2.2

  • Addresses #149: allow ignoring basePath for api docs path.

1.2.1

  • Version bump for NPM security audit

1.2.0

  • Vendor extensions are now stripped from the API docs end point (option docs.stripExtensions).
  • Bumped to Enjoi 4.x.

1.1.0

  • Allow override of payload options via x-hapi-options (#137).

1.0.5

  • Allow auth in doc options to be false (#134).

1.0.4

1.0.3

1.0.2

  • Allow registering multiple of this plugin.

1.0.1

  • Fixes issue #117 (breaking on empty description).

1.0.0 Rename

  • Renamed to hapi-openapi.
  • Dropped version down to 1.0.0.

4.1.0

  • Fixes trailing spaces #104.
  • Fixes empty base path #106.
  • Fixes no operation parameters #108.
  • Adds support for API as object instead of file path #102

4.0.0

  • [BREAKING] x-* attribute support renamed to x-hapi-*.
  • New support for x-hapi-options on operations.

3.4.2

  • Updated to file validation which addresses #68.

3.4.1

  • Upgraded enjoi.

3.4.0

  • Added support for output validation (optional).

3.3.2

  • Fixed YAML parsing for api-docs route.

3.3.1

3.3.0

  • x-auth attribute support.
  • basedir is not an option (officially).

3.2.0

  • x-handler attribute support.

3.1.0

  • Add tags and description to routes based on API spec.
  • Don't restrict auth types.
  • Add route meta data from API spec.
  • docspath option is now docs and is an object.

3.0

  • [BREAKING] Migrated to Hapi 17 and Node 8.
  • [BREAKING] Severed from swaggerize-routes - this module is now standalone.
  • [BREAKING] server.plugins.swagger.api is now server.plugins.swagger.getApi().
  • [BREAKING] handlers object doesn't namespace http methods using $ anymore. Assumption is verb is last in object path.
  • [BREAKING] Currently does not work with the swaggerize-generator.
  • Routes will specify what they allow based on api spec.