sse

swagger-spec-express

Allows you to programatically annotate your express routes with swagger info and then generate and validate your json spec file

Showing:

Popularity

Downloads/wk

950

GitHub Stars

33

Maintenance

Last Commit

2yrs ago

Contributors

10

Package

Dependencies

5

License

MIT

Type Definitions

Built-In

Tree-Shakeable

No?

Categories

Readme

swagger-spec-express

Programmatically generate your Swagger specification (JSON) file.

NPM

Build status

A library that allows you to programmatically annotate your existing express api with swagger info and then generate and validate your json spec file. All without completely starting over or changing the structure of your express routes.

Why

There are already a few libraries out there to add Swagger documentation to your express api, like swagger-node-express and swagger-node which work really well, however they require you to either start from scratch or change your routes to work with their format. This libary is different and can easily be added to an existing and established express api using the normal patterns you are used to.

##Installation Requires Express 4.x

Install the package:

npm install swagger-spec-express --save-exact

Basic code example:

var express = require('express');
var swagger = require('swagger-spec-express');
var packageJson = require('./package.json');

var app = express();
var options = {
    title: packageJson.title,
    version: packageJson.version
};
swagger.initialise(app, options);

app.get('/swagger.json', function (err, res) {
    res.status(200).json(swagger.json());
}).describe({
    responses: {
        200: {
            description: "Returns the swagger.json document"
        }
    }
});

swagger.compile();
var port = 3000;
app.listen(port, appListening);
function appListening() {
    console.info(packageJson.name + ' is listening on port ' + port);
}

This will create a very basic express app that serves up the swagger.json document when you navigate to http://localhost:3000/swagger.json

The JSON Schema file that will be used to validate the supplied metadata on the route can be found here in addition the fields are detailed below. Wherever possible the library tries to adhear to the official Swagger Specification so that is a good place to look for extra information about what you can specify.

Describing Your Routes

As seen above, once you have called initialise on your app, the describe method is automatically added and can be added to routes you declare directly on your app object.

But what if you want to use the router object? In the above example code above add the following to the top of the page:

var exampleRouter = require('./example-route');

And then after calling swagger.initialise(app, options); add the following:

app.use(exampleRouter);

Code for the example router:

'use strict';
var express = require('express');
var swagger = require('swagger-spec-express');
var router = new express.Router();
swagger.swaggerize(router);
module.exports = router;

router.get('/one', function (req, res) {
    res.status(200).json({example: 1})
}).describe({
    responses: {
        200: {
            description: "Returns example 1"
        }
    }
});

Adding the UI

Simply follow the instructions for the official Swagger UI project. or use your favourite, alternative Swagger UI theme.

API

Table of Contents

initialise

lib/initialise.js:120-136

Will initialise your app with the required swaggers-spec information. In addition you can pass in some options which will be used when generating the swagger JSON document later on. Both British and American spelling supported.

Parameters

  • app object The express app class that you want to describe using swagger
  • options.externalDocs.url string Required. The URL for the target documentation. Value MUST be in the format of a URL.
  • options.document [object] An existing or manually created swagger document to use as a base document and expanded upon. Note that the other options will override the base items in this supplied document. See http://swagger.io/specification/ for info on how to manually construct a document.
  • options.title [string] The title of the application.
  • options.description [string] A short description of the application. GFM syntax can be used for rich text representation.
  • options.termsOfService [string] The Terms of Service for the API.
  • options.contact [object] The contact information for the exposed API. See Contact Object.
    • options.contact.name [string] The identifying name of the contact person/organization.
    • options.contact.url [string] The URL pointing to the contact information. MUST be in the format of a URL.
    • options.contact.email [string] The email address of the contact person/organization. MUST be in the format of an email address.
  • options.license [object] The license information for the exposed API. See License Object.
    • options.license.name string Required. The license name used for the API.
    • options.license.url [string] A URL to the license used for the API. MUST be in the format of a URL.
  • options.version [string] Provides the version of the application API.
  • options.host [string] The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the host is not included, the host serving the documentation is to be used (including the port). The host does not support Path Templating.
  • options.basePath [string] The base path on which the API is served, which is relative to the host. If it is not included, the API is served directly under the host. The value MUST start with a leading slash (/). The basePath does not support Path Templating. (optional, default /)
  • options.schemes [Array<string>] The transfer protocol of the API. Values MUST be from the list: "http", "https", "ws", "wss". If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself.
  • options object The options object, used to control how the swagger document will be generated
    • options.produces [Array<string>] A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under Mime Types.
    • options.paths [object] The available paths and operations for the API. See Paths Object.
    • options.definitions [object] An object to hold data types produced and consumed by operations. See Definitions Object.
    • options.parameters [object] An object to hold parameters that can be used across operations. This property does not define global parameters for all operations. See Parameter Definitions Object.
    • options.responses [object] An object to hold responses that can be used across operations. This property does not define global responses for all operations. See Response Definitions Object.
    • options.securityDefinitions [object] Security scheme definitions that can be used across the specification. See Security Definitions Object.
    • options.security [object] A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition. See Security Requirement Object.
    • options.defaultSecurity [(string | Array<string>)] The default security schema to use on a route when the security parameter is set to true. Must be a single Security Requirement Object.
    • options.tags [object] A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. See Tag Object.
      • options.tags.name string Required. The name of the tag.
      • options.tags.description [string] A short description for the tag. GFM syntax can be used for rich text representation.
      • options.tags.externalDocs [object] Additional external documentation for this tag.
        • options.tags.externalDocs.description [string] A short description of the target documentation. GFM syntax can be used for rich text representation.
        • options.tags.externalDocs.url string Required. The URL for the target documentation. Value MUST be in the format of a URL.
    • options.externalDocs [object] Additional external documentation. See External Documentation Object.
      • options.externalDocs.description [string] A short description of the target documentation. GFM syntax can be used for rich text representation.
    • options.consumes [Array<string>] A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under Mime Types.

Examples

Minimal

var express = require('express');
var swagger = require('swagger-spec-express');
var packageJson = require('./package.json');
var app = express();

swagger.initialise(app, options);

Extensive

var express = require('express');
var swagger = require('swagger-spec-express');
var packageJson = require('./package.json');
var app = express();
var options = {
   document: {
       // An existing swagger json spec file that you may want to build on
   },
   title: packageJson.title,
   description: packageJson.description,
   termsOfService: 'You may only use this api for reasons!',
   contact: {
       name: '',
       url: '',
       email: ''
   },
   license: {
       name: '',
       url: ''
   },
   version: packageJson.version,
   host: 'localhost',
   basePath: '/',
   schemes: ['http', 'https'],
   consumes: ['application/json'],
   produces: ['application/json'],
   paths: {
       //manual paths here if desired, not required.
   },
   definitions: {
       //manual definitions here if desired, not required.
   },
   parameters: {
       //manual definitions here if desired, not required.
   },
   responses: {
       //manual responses here if desired, not required.
   },
   securityDefinitions: {
       basicAuth: {
           type: "basic",
           description: "HTTP Basic Authentication. Works over HTTPS"
       }
   },
   security: [{basicAuth: []}],
   defaultSecurity: "basicAuth",
   tags: [
       {
           name: 'My Manual Tag',
           description: 'Manually added to swagger',
           externalDocs: {
               description: 'This doc describes how to make tags',
               url: 'https://github.com/eXigentCoder/swagger-spec-express'
           }
       }
   ],
   externalDocs: {
       description: 'This doc describes how to use swagger spec express',
       url: 'https://github.com/eXigentCoder/swagger-spec-express'
   }
};
swagger.initialise(app, options);
  • Throws Error if already initialised, should call reset first if reinitialisation required
  • Throws Error if no app object provided
  • Throws Error if no options object provided

Returns void

swaggerise

lib/swaggerise.js:16-68

Adds the .describe function onto the provided object. The object should either be an express app or express router.

Parameters

  • item object the item to apply

Examples

var swagger = require('swagger-spec-express');
var express = require('express');
var app = express();
swagger.swaggerize(app);
var router = new express.Router();
swagger.swaggerize(router);

Returns void

describe

lib/swaggerise.js:62-67

Allows you describe an app our router route.

Parameters

  • metaData object Metadata about a route. At least one of metaData.responses or metaData.common.responses must be specified.
    • metaData.summary [string] A brief summary of the operation.
    • metaData.description [string] A longer description of the operation, GitHub Flavored Markdown is allowed.
    • metaData.externalDocs [object] information about external documentation
      • metaData.externalDocs.description [string] A short description of the target documentation. GFM syntax can be used for rich text representation.
      • metaData.externalDocs.url string Required. The URL for the target documentation. Value MUST be in the format of a URL.
    • metaData.operationId [string] A unique identifier of the operation.
    • metaData.produces [Array<string>] A list of MIME types the API can produce.
    • metaData.consumes [Array<string>] A list of MIME types the API can consume.
    • metaData.parameters [(object | string)] An object to hold parameters that can be used across operations. This property does not define global parameters for all operations. See Parameter Definitions Object.
    • metaData.tags [Array<string>] A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. See Tag Object.
    • metaData.schemes [Array<string>] The transfer protocol of the API.
    • metaData.deprecated [boolean] Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is false.
    • metaData.security [(array | boolean | string)] A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition. See Security Requirement Object.
    • metaData.common [object] A collection of common data to include in this route.
      • metaData.common.responses [Array<string>] Common responses as added by calling common.addResponse
      • metaData.common.parameters [object] A collection of common parameters to use for this route.
        • metaData.common.parameters.header [Array<string>] A common header parameter as added by calling common.parameters.addHeader
        • metaData.common.parameters.body [Array<string>] A common body parameter as added by calling common.parameters.addBody
        • metaData.common.parameters.query [Array<string>] A common query string parameter as added by calling common.parameters.addQuery
        • metaData.common.parameters.formData [Array<string>] A common form data parameter as added by calling common.parameters.addFormData
    • metaData.responses [object] Response objects names can either be any valid HTTP status code or 'default'.
  • metaData.common.parameters.path [Array<string>] A common path parameter as added by calling common.parameters.addPath

Examples

var swagger = require('swagger-spec-express');
var express = require('express');
var router = new express.Router();
swagger.swaggerize(router);
router.get('/', function (req, res) {
    //...
}).describe({
    //...
});

Returns void

compile

lib/index.js:52-59

Will gather together all your described app routes and compile them into a single document to be served up by your api when you call json. Can only be called once initialise has been called. Should only call this once you have completely finished describing your routes.

Examples

var swagger = require('swagger-spec-express');
var express = require('express');
var router = new express.Router();
swagger.swaggerize(router);
router.get('/', function (req, res) {
    //...
}).describe({
    //...
});
swagger.compile();
  • Throws Error Will throw an error if initialise wasn't called or if you don't yet have any routes defined or if there are certain errors in your metadata

Returns void

validate

lib/index.js:83-85

Will validate the internal json document created by calling compile. This is done using the ajv validator against the official JSON schema. * @throws {Error} Throws an exception if called before compile or initialise.

Examples

var swagger = require('swagger-spec-express');
var express = require('express');
var router = new express.Router();
var os = require('os');
swagger.swaggerize(router);
router.get('/', function (req, res) {
    //...
}).describe({
    //...
});
swagger.compile();
var result = swagger.validate();
if (!result.valid) {
    console.warn("Compiled Swagger document does not pass validation: " + os.EOL + result.message);
}

Returns {valid: boolean, errors: Array<Object>, message: string} The result of the validation

json

lib/index.js:113-117

Returns the swagger specification as a json object.

Examples

var swagger = require('swagger-spec-express');
var express = require('express');
var app = express();
var options = {
    title: packageJson.title,
    version: packageJson.version
};
swagger.initialise(app, options);
app.get('/swagger.json', function (err, res) {
    res.status(200).json(swagger.json());
}).describe({
    responses: {
        200: {
            description: "Returns the swagger.json document"
        }
    }
});
swagger.compile();
  • Throws Error Throws an exception if called before compile or initialise. You do not need to call validate first.

Returns Object The Swagger JSON object describing your api. See http://swagger.io/specification/.

addTag

lib/common.js:44-51

Adds a common tag for later use.

Parameters

  • tag object Allows adding meta data to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag used there.
    • tag.name string Required. The name of the tag.
    • tag.description [string] A short description for the tag. GFM syntax can be used for rich text representation.
    • tag.externalDocs [object] information about external documentation
      • tag.externalDocs.description [string] A short description of the target documentation. GFM syntax can be used for rich text representation.
      • tag.externalDocs.url string Required. The URL for the target documentation. Value MUST be in the format of a URL.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.addTag({
    name: "Info",
    description: "Info about the api"
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    tags: ["Info"],
    //...
});

Returns void

addHeaderParameter

lib/common.js:106-114

Adds a common header for later use.

Parameters

  • header object todo
    • header.format [string] The extending format for the previously mentioned type. See Data Type Formats for further details.
    • header.items [object] Required if type is array. Describes the type of items in the array.
    • header.collectionFormat [string] Determines the format of the array if type array is used. Possible values are:- csv comma separated values foo,bar.
      • ssv space separated values foo bar.
      • tsv tab separated values foo bar.
      • pipes pipe separated values foo|bar.
      • multi corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in query or formData.Default value is csv.
    • header.maximum [number] See json-schema.org.
    • header.exclusiveMaximum [boolean] See json-schema.org.
    • header.minimum [number] See json-schema.org.
    • header.exclusiveMinimum [boolean] See json-schema.org.
    • header.type string Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of string, number, integer, boolean, array or file. If type is file, the consumes MUST be either multipart/form-data, application/x-www-form-urlencoded or both and the parameter MUST be in formData.
    • header.minLength [number] See json-schema.org.
    • header.pattern [string] See json-schema.org.
    • header.maxItems [number] See json-schema.org.
    • header.minItems [number] See json-schema.org.
    • header.uniqueItems [boolean] See json-schema.org.
    • header.multipleOf [number] See json-schema.org.
    • header.description [string] A short description of the header.
    • header.name string The name used to refer to this header at a later stage.
    • header.maxLength [number] See json-schema.org.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.parameters.addHeader({
    name: "Originator-Id",
    description: "Tells the server where the request originated from",
    required: true,
    type: "string"
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    common: {
        //...
        parameters: {
            header: ["Originator-Id"]
        }
        //...
    }
    //...
});

Returns void

addBodyParameter

lib/common.js:159-167

Adds a common body parameter for later use.

Parameters

  • body object The payload that's appended to the HTTP request. Since there can only be one payload, there can only be one body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation.
    • body.description [string] A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
    • body.name [string] The name of the parameter.
    • body.in [string] Determines the location of the parameter.
    • body.required [boolean] Determines whether or not this parameter is required or optional.
    • body.schema [object] A deterministic version of a JSON Schema object.
    • body.model [string] The name of the model produced or consumed.
    • body.arrayOfModel [string] The name of the model produced or consumed as an array.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.parameters.addBody({
    name: "process",
    description: "Kicks off the process function on the server at the rest endpoint using the options provided",
    required: true,
    schema : {
        type: "object",
        properties: {
            "async": {
                "type": "boolean"
            }
        }
        additionalProperties: true
    }
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    common: {
        //...
        parameters: {
            body: ["process"]
        }
        //...
    }
    //...
});

Returns void *

addQueryParameter

lib/common.js:225-233

Adds a common query parameter for later use.

Parameters

  • query object Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id
    • query.in string Determines the location of the parameter.
    • query.description [string] A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
    • query.name string The name of the parameter.
    • query.allowEmptyValue [boolean] allows sending a parameter by name only or with an empty value.
    • query.type string Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of string, number, integer, boolean, array or file. If type is file, the consumes MUST be either multipart/form-data, application/x-www-form-urlencoded or both and the parameter MUST be in formData.
    • query.format [string] The extending format for the previously mentioned type. See Data Type Formats for further details.
    • query.items [object] Required if type is array. Describes the type of items in the array.
    • query.collectionFormat [string] Determines the format of the array if type array is used. Possible values are:- csv comma separated values foo,bar.
      • ssv space separated values foo bar.
      • tsv tab separated values foo bar.
      • pipes pipe separated values foo|bar.
      • multi corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in query or formData.Default value is csv.
    • query.maximum [number] See json-schema.org.
    • query.required [boolean] Determines whether or not this parameter is required or optional.
    • query.minimum [number] See json-schema.org.
    • query.exclusiveMinimum [boolean] See json-schema.org.
    • query.maxLength [number] See json-schema.org.
    • query.minLength [number] See json-schema.org.
    • query.pattern [string] See json-schema.org.
    • query.maxItems [number] See json-schema.org.
    • query.minItems [number] See json-schema.org.
    • query.uniqueItems [boolean] See json-schema.org.
    • query.multipleOf [number] See json-schema.org.
    • query.exclusiveMaximum [boolean] See json-schema.org.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.parameters.addQuery({
    name: "sort",
    description: "The sort order of records e.g. sort=field1,-field2",
    required: false,
    type: "string"
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    common: {
        //...
        parameters: {
            query: ["sort"]
        }
        //...
    }
    //...
});

Returns void

addFormDataParameter

lib/common.js:293-301

Adds a common form data parameter for later use.

Parameters

  • formData object Used to describe the payload of an HTTP request when either application/x-www-form-urlencoded, multipart/form-data or both are used as the content type of the request (in Swagger's definition, the consumes property of an operation). This is the only parameter type that can be used to send files, thus supporting the file type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4):- application/x-www-form-urlencoded Similar to the format of Query parameters but as a payload. For example, foo=1&bar=swagger both foo and bar are form parameters. This is normally used for simple parameters that are being transferred.
    • multipart/form-data each parameter takes a section in the payload with an internal header. For example, for the header Content-Disposition: form-data; name="submit-name" the name of the parameter is submit-name. This type of form parameters is more commonly used for file transfers.
    • formData.in string Determines the location of the parameter.
    • formData.description [string] A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
    • formData.name string The name of the parameter.
    • formData.allowEmptyValue [boolean] allows sending a parameter by name only or with an empty value.
    • formData.type string Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of string, number, integer, boolean, array or file. If type is file, the consumes MUST be either multipart/form-data, application/x-www-form-urlencoded or both and the parameter MUST be in formData.
    • formData.format [string] The extending format for the previously mentioned type. See Data Type Formats for further details.
    • formData.items [object] Required if type is array. Describes the type of items in the array.
    • formData.collectionFormat [string] Determines the format of the array if type array is used. Possible values are:- csv comma separated values foo,bar.
      • ssv space separated values foo bar.
      • tsv tab separated values foo bar.
      • pipes pipe separated values foo|bar.
      • multi corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in query or formData.Default value is csv.
    • formData.maximum [number] See json-schema.org.
    • formData.required [boolean] Determines whether or not this parameter is required or optional.
    • formData.minimum [number] See json-schema.org.
    • formData.exclusiveMinimum [boolean] See json-schema.org.
    • formData.maxLength [number] See json-schema.org.
    • formData.minLength [number] See json-schema.org.
    • formData.pattern [string] See json-schema.org.
    • formData.maxItems [number] See json-schema.org.
    • formData.minItems [number] See json-schema.org.
    • formData.uniqueItems [boolean] See json-schema.org.
    • formData.multipleOf [number] See json-schema.org.
    • formData.exclusiveMaximum [boolean] See json-schema.org.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.parameters.addFormData({
    name: "csvString",
    description: "The csv string to import",
    required: true,
    type: "string"
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    common: {
        //...
        parameters: {
            formData: ["csvString"]
        }
        //...
    }
    //...
});

Returns void

addPathParameter

lib/common.js:358-366

Adds a common path parameter for later use.

Parameters

  • path object Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId.
    • path.in string Determines the location of the parameter.
    • path.description [string] A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed.
    • path.name string The name of the parameter.
    • path.type string Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of string, number, integer, boolean, array or file. If type is file, the consumes MUST be either multipart/form-data, application/x-www-form-urlencoded or both and the parameter MUST be in formData.
    • path.format [string] The extending format for the previously mentioned type. See Data Type Formats for further details.
    • path.items [object] Required if type is array. Describes the type of items in the array.
    • path.collectionFormat [string] Determines the format of the array if type array is used. Possible values are:- csv comma separated values foo,bar.
      • ssv space separated values foo bar.
      • tsv tab separated values foo bar.
      • pipes pipe separated values foo|bar.
      • multi corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in query or formData.Default value is csv.
    • path.maximum [number] See json-schema.org.
    • path.required boolean Determines whether or not this parameter is required or optional.
    • path.minimum [number] See json-schema.org.
    • path.exclusiveMinimum [boolean] See json-schema.org.
    • path.maxLength [number] See json-schema.org.
    • path.minLength [number] See json-schema.org.
    • path.pattern [string] See json-schema.org.
    • path.maxItems [number] See json-schema.org.
    • path.minItems [number] See json-schema.org.
    • path.uniqueItems [boolean] See json-schema.org.
    • path.multipleOf [number] See json-schema.org.
    • path.exclusiveMaximum [boolean] See json-schema.org.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.parameters.addPath({
    name: "entityId",
    description: "The id of the entity which contains the data we are using",
    required: true,
    type: "string"
});
//...
router.get('/:entityId', function (req, res) {
    //...
}).describe({
    //...
    common: {
        //...
        parameters: {
            path: ["entityId"]
        }
        //...
    }
    //...
});

Returns void

addResponse

lib/common.js:401-408

Adds a common response for later use.

Parameters

  • response object Describes a single response from an API Operation.
    • response.description string Required. A short description of the response. GFM syntax can be used for rich text representation.
    • response.schema [object] A definition of the response structure. It can be a primitive, an array or an object. If this field does not exist, it means no content is returned as part of the response. As an extension to the Schema Object, its root type value may also be file. This SHOULD be accompanied by a relevant produces mime-type.
    • response.headers [object] A list of headers that are sent with the response. See http://swagger.io/specification/#headersObject
    • response.examples [object] An example of the response message. See http://swagger.io/specification/#exampleObject
    • response.name string The name or http status code used to refer to this response at a later stage.
    • response.model [string] The name of the model produced or consumed.
    • response.arrayOfModel [string] The name of the model produced or consumed as an array.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.addResponse({
    name: "500",
    description: "Server Error",
    "schema": {
        $ref: "#/definitions/serverError"
    }
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    common: {
        //...
        responses: ["500", "400", "401", "404"],
        //...
    }
    //...
});

Returns void

addResponseHeader

lib/common.js:461-469

Adds a common response header for later use.

Parameters

  • responseHeader object todo
    • responseHeader.format [string] The extending format for the previously mentioned type. See Data Type Formats for further details.
    • responseHeader.items [object] Required if type is array. Describes the type of items in the array.
    • responseHeader.collectionFormat [string] Determines the format of the array if type array is used. Possible values are:- csv comma separated values foo,bar.
      • ssv space separated values foo bar.
      • tsv tab separated values foo bar.
      • pipes pipe separated values foo|bar.
      • multi corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in query or formData.Default value is csv.
    • responseHeader.maximum [number] See json-schema.org.
    • responseHeader.exclusiveMaximum [boolean] See json-schema.org.
    • responseHeader.minimum [number] See json-schema.org.
    • responseHeader.exclusiveMinimum [boolean] See json-schema.org.
    • responseHeader.type string Required. The type of the parameter. Since the parameter is not located at the request body, it is limited to simple types (that is, not an object). The value MUST be one of string, number, integer, boolean, array or file. If type is file, the consumes MUST be either multipart/form-data, application/x-www-form-urlencoded or both and the parameter MUST be in formData.
    • responseHeader.minLength [number] See json-schema.org.
    • responseHeader.pattern [string] See json-schema.org.
    • responseHeader.maxItems [number] See json-schema.org.
    • responseHeader.minItems [number] See json-schema.org.
    • responseHeader.uniqueItems [boolean] See json-schema.org.
    • responseHeader.multipleOf [number] See json-schema.org.
    • responseHeader.description [string] A short description of the header.
    • responseHeader.name string The name used to refer to this header at a later stage.
    • responseHeader.maxLength [number] See json-schema.org.
  • options [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.addResponseHeader({
    name: "Response-Id",
    description: "A unique response id for tracking in logs",
    type: "string"
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    responses: {
        "200": {
            //...
            commonHeaders: ["Response-Id"]
        }
    }
    //...
});

Returns void

addModel

lib/common.js:499-527

Adds a common model for later use.

Parameters

  • model object The schema for the model object to add. Should be a valid Schema object.
  • inputOptions [AddCommonItemOptions] Options to apply when adding the provided item.

Examples

var swagger = require('swagger-spec-express');
swagger.common.addModel({
    "name": "serverError",
    "type": "object",
    "properties": {
        "message": {
            "type": "string"
        }
    }
});
//...
router.get('/', function (req, res) {
    //...
}).describe({
    //...
    responses: {
        "500": {
            //...
            model: "serverError"
        }
    }
    //...
});

Returns void

AddCommonItemOptions

lib/common.js:554-558

Parameters

  • validation string Controls how validation works, can either be warn (Sends message to console.warn), throw (Throws an Error) or ignore.
  • deleteNameFromCommon Controls if, after adding the item to common, it should remove the name in order to pass the Swagger schema validation.

Reporting Bugs & Issues

Log them on GitHub

Contributing

If you would like to help contribute to the library, fork it and submit a pull request.

Leveraging this module to validate the data returned from your integration tests

todo

Awesome code reuse

todo

Roadmap

Low

  • Currently populating rootDocument.responses but then injecting the responses directly into the operation. Should use the $ref
  • Currently populating rootDocument.parameters but then injecting the responses directly into the operation. Should use the $ref

Medium

  • Ability to describe the app like a router (alternate to passing all the data into the init method).
  • More tests

High

  • addResponse should look for model & arrayOfModel
  • Better error messages in general so you don't need to debug
  • Ability to inject certain things into parameters. E.g. many GET routes will have GET /thing/:identifier would be nice to inject the name in there
  • when using arrayOfModel the schema doesn't have an id, so makes it harder to use ajv. Currently we just wrapping in {items:}. Still an issue?
  • proper error classes for specific errors to allow filtering and handling

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial