1.1.1 • Published 9 years ago

hapi-swagger-json v1.1.1

Weekly downloads
1
License
MIT
Repository
github
Last release
9 years ago

hapi-swagger-json

Build Status Coverage Status Dependency Status NPM version

NPM

A swagger plugin for Hapi to generate json swagger docs and associated endpoints through Joi validation objects. Based on hapi-swagger by Glenn Jones.

Contributing

This module makes use of a Makefile for building/testing purposes. After obtaining a copy of the repo, run the following commands to make sure everything is in working condition before you start your work:

make install
make test

Before committing a change to your fork/branch, run the following commands to make sure nothing is broken:

make test

Don't forget to bump the version in the package.json using the semver spec as a guide for which part to bump. Submit a pull request when your work is complete.

Notes:

  • Please do your best to ensure the code coverage does not drop. If new unit tests are required to maintain the same level of coverage, please include those in your pull request.
  • Please follow the same coding/formatting practices that have been established in the module.

Installation

npm install hapi-swagger-json

Usage

To install this plugin on your Hapi server, do something similar to this:

var Hapi = require('hapi');
var server = new Hapi.Server();
var pkg = require('package.json');

var hapiSwaggerJsonConfig = {
	apiVersion: pkg.version,
	basePath: 'http://localhost:3000',
	info: {
		title: pkg.name,
		description: pkg.description,
		contact: 'someones.email@domain.com'
	}
};

server.register({ register: require('hapi-swagger-json'), options: hapiSwaggerJsonConfig }, function(err) {
	if (err) {
		server.log(['error'], 'Failed loading plugin: hapi-swagger-json: ' + err);
	}
});

Plugin Options

  • apiVersion: Required. String. The version of your API.
  • basePath: String. The base URL of the API. Defaults to server.info.url i.e. http://localhost:3000
  • resourceListPath: String. The relative URL to swagger resource list. Defaults to /api-docs
  • produces: Array of string values. The MIME output types from your API. Defaults to ['application/json']
  • consumes: Array of string values. The MIME inout types from your API. Defaults to ['application/json']
  • authorizations: Object Containing swagger authorization objects, the keys mapping to HAPI auth strategy names.
  • info: a swagger info object with metadata about the API. title: Required. String. The title of the application. description: Required. String. 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.
  • extraRoutes: Object array containing any routes added to the server by means other than the hapi.js framework that you wish to have swagger generated for, where: path: Required. String. The relative url path of the route. method: Required. String. The http method for the route. description: String. Short description of the route. notes: String or String array. More detailed description of the route. validate: Object. Modeled after the route.config.validation object from the hapi.js framework. response: Object. Modeled after the route.config.resposne object from the hapi.js framework. * responseMessage: Object array. See Error Status Codes below.

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.

{
	method: 'GET',
	path: '/myRoute/{id}',
	config: {
		handler: function(request, reply){},
		description: 'Short description of the route',
		notes: ['Longer, more verbose description', 'Array gets joined by /n'],
		tags: ['api], //identifies to plugin that this route is to be documented
		validate: {
			params: {
				id: Joi.number().integer().min(0).max(50).required().description('resource id')
			}
		}
	}
}

Response Object

Hapi allows you to define a response object for an API endpoint. The response object is used by Hapi for both validation and description of the output of an API. It uses the same type of JOI validation objects used to describe the input parameters. The plugin turns these objects into swagger response models.

{
	method: 'GET',
	path: '/myRoute/{id}',
	config: {
		handler: function(request, reply){},
		description: 'Short description of the route',
		notes: ['Longer, more verbose description', 'Array gets joined by /n'],
		tags: ['api], //identifies to plugin that this route is to be documented
		validate: {
			params: {
				id: Joi.number().integer().min(0).max(50).required().description('resource id')
			}
		},
		response: {
			schema: Joi.object({
				id: Joi.number().integer().min(0).max(50).required().description('resource id'),
				name: Joi.string().min(1).required('resource name')
			}).meta({className: 'ResponseModelName'})
		}
	}
}

More in depth examples can be found be examining the controllers in the integration tests included in this repo.

Swagger Data NOT Covered by Hapi/Joi

Data not directly supported by Hapi/Joi can be added to the plugins object of the route's config object. Add a key with the same name as this plugin, the value is an object containing and plugin configuration you wish to pass in.

Path Overview

As an optional piece of data you may add a global description to the swagger resource listing of each unique path.

Error Status Codes

You can add HTTP error status codes to each of the endpoints. Hapi routes do not directly have a property for error status codes so you need to add them to the plugin configuration. The status codes need to be added as an array of objects with an error code and description:

{
	method: 'GET',
	path: '/myRoute/{id}',
	config: {
		handler: function(request, reply){},
		description: 'Short description of the route',
		notes: ['Longer, more verbose description', 'Array gets joined by /n'],
		tags: ['api], //identifies to plugin that this route is to be documented
		validate: {
			params: {
				id: Joi.number().integer().min(0).max(50).required().description('resource id')
			}
		},
		response: {
			schema: Joi.object({
				id: Joi.number().integer().min(0).max(50).required().description('resource id'),
				name: Joi.string().min(1).required('resource name')
			}).meta({className: 'ResponseModelName'})
		},
		plugins:{
			'hapi-swagger-json':{
				overview: 'Overall resource path description for swagger resource listing. This only needs to be entered once for a given path.',
				responseMessages:[
					{code: 400, message: 'Bad Request'},
					{code: 404, message: 'Not Found'}
				]
			}
		}
	}
}

Swagger Linting

hapi-swagger-json adds basic swagger validation/linting to responses from the generated routes. Specific values are not all verified, but overall schema is. If the swagger generated by this plugin violates the swagger schema (invalid properties or missing required ones), Hapi will return a 500.

Version Compatibility

Currently compatible with: Hapi 8.x.x and Swagger 1.2

  • 1.x.x - Hapi 8.x.x / Swagger 1.2

License

The MIT License (MIT)

1.1.1

9 years ago

1.1.0

9 years ago

1.0.0

9 years ago