openapi-doc

Programmatically builds an Open API (Swagger 2.0) document as an Express endpoint so that the documentation and source can live together in one place. It is like annotating an Express endpoint. Later, the API can be bound to Express.

Usage no npm install needed!

<script type="module">
  import openapiDoc from 'https://cdn.skypack.dev/openapi-doc';
</script>

README

openapi-doc

Programmatically builds an Open API (Swagger 2.0) document as an Express endpoint so that the documentation and source can live together in one place. It is like annotating an Express endpoint. Later, the API can be bound to Express.

Features

  • Programmatically define an Open API (Swagger 2.0) API.
  • Generates a syntactically correct Swagger API JSON document from source.
  • Swagger API document can be served via Express.

Install

npm install --save openapi-doc

API Reference

Open API documentation for node.js and Express.js

Example (Quick start)

    const Swagger = require('openapi-doc');
    const swagger = new Swagger();
    swagger.info('My API', '1.0', 'This is *API*');

    // describe API endpoint and action
    swagger.get('/logs')
        .operationId('getLogs')
        .tag('logging')
        .summary('Gets an array of logs.')
        .response(200)
        .action((req, res) => {
            res.sendStatus(200);
        });

Example (Bind API to Express endpoint)

    const prefix = '/api';
    Swagger.forEachAction(swagger, (verb, path) => {
        const endpoint = uriUtils.oasPathToExpress(prefix + path);
        // express app
        app[verb](
            endpoint,
            Swagger.actionMiddleware(swagger, verb, path)
        );
    });

Example (Apply security)

    const prefix = '/api';
    swagger.securityDefinition(
        'basicAuth', {
            type: 'basic',
            description: 'Username and password',
        },
        (req) => {
            return true;
        }
    );
    Swagger.forEachAction(swagger, (verb, path) => {
        const endpoint = uriUtils.oasPathToExpress(prefix + path);
        // express app
        app[verb](
            endpoint,
            Swagger.securityMiddleware(swagger, verb, path),
            Swagger.actionMiddleware(swagger, verb, path)
        );
    });

Example (Bind generated Swagger API document to Express endpoint)

    app.get('/api-doc', function (req, resp) {
        resp.send(swagger.apidoc());
    });

openapi-doc~Swagger

Kind: inner class of openapi-doc

new Swagger()

Construct a Swagger builder.

swagger.securityHandlers ⇒ object

Returns all of the security handlers associated with the API endpoints.

Kind: instance property of Swagger
Returns: object - Map of callback functions.
Access: public
Example

Object.keys(swagger.securityHandlers, (key) => {
    swagger.securityHandlers[key];
});

swagger.actions ⇒ object

Returns all of the actions associated with the API endpoints.

Kind: instance property of Swagger
Returns: object - Map of [path][verb].
Access: public

swagger.info(title, version, description) ⇒ Swagger

Adds information for the API.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
title string the title of the API
version string the version of the API
description string the description of the API

Example

swagger.info('My API', '1.0', 'This is *API*');

swagger.host(name) ⇒ Swagger

Sets the host for the API

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string the hostname of the API, e.g. 'localhost'

swagger.license(name) ⇒ Swagger

Sets the license for the API

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string the license name

swagger.contact(name, [email], [url]) ⇒ Swagger

Sets the contact name and email

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string the contact name
[email] string the contact email
[url] string the contact url

swagger.termsOfService(terms) ⇒ Swagger

Sets the terms of service for the API

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
terms string the terms of service

swagger.basePath(path) ⇒ Swagger

Sets the API base path

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
path string the API base path

swagger.globalSchemes(schemes) ⇒ Swagger

Sets the schemes for the API

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
schemes array An array of http schemes

swagger.schemes(schemes) ⇒ Swagger

Sets the schemes for the method

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
schemes array An array of http schemes

swagger.securityDefinition(name, options, handler) ⇒ Swagger

Adds a Security Definition.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string the name of the security definition
options object The options for this security definition. See: http://swagger.io/specification/#securityDefinitionsObject
handler customAuthentication The middleware handler function. security definition.

Example

swagger.securityDefinition(
    'basicAuth',
    {
         type: 'basic',
         description: 'Requires username:password'
    },
    (req) => {
         return true;
    }
});
// Assign security definition globally.
swagger.security('basicAuth');

swagger.security(definitions) ⇒ Swagger

Adds a Security Requirement to the current method. If definitions is empty, then then no security is applied. The definitions can be a string, an array of string, or an array of object. If definitions is an array of object, then it must be an array of security Requirement Objects, e.g. [{apikey: []}].

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
definitions array An array of the Security Definition to apply.

swagger.globalSecurity(definitions) ⇒ Swagger

Adds a Security Requirement globally for the API. If definitions is empty, then then no security is applied. The definitions can be a string, an array of string, or an array of object. If definitions is an array of object, then it must be an array of security Requirement Objects, e.g. [{apikey: []}].

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
definitions array An array of the Security Definition to apply.

swagger.globalParameter(param) ⇒ Swagger

Adds a global parameter to the document which can be referred to using $ref later.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
param object A valid Swagger parameter specification.

Example

swagger.globalParameter({
     in: 'path',
     name: 'foo',
     type: 'string',
     description: 'My foo param'});
swagger.post('/foo')
    .operationId('CreateFoo')
    .parameter({ $ref: '#/parameters/foo' })
    .response(200, 'Success');

swagger.globalTag(tag) ⇒ Swagger

Adds a global tag to the document.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
tag object A Swagger tag object.

Example

swagger.globalTag({
     name: 'foo',
     description: 'My foo tag'});

swagger.globalResponse(name, description, [type], [isArray], [headers]) ⇒ Swagger

Adds a global response to the document which can be referred to using $ref later.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string The unique name of the response.
description string The description of the response.
[type] string Optional type (to be used in $ref).
[isArray] boolean Optional indicator that the repsonse is an array of type.
[headers] array Optional headers to include in the response.

swagger.globalExternalDocs(doc) ⇒ Swagger

Sets the global externalDocs of the swagger doc

Kind: instance method of Swagger
Returns: Swagger - The current object (this).

Param Type Description
doc string A valid ExternalDocumentationObject.

swagger.globalConsumes(mimeType) ⇒ Swagger

Adds a consumes to the doc

Kind: instance method of Swagger
Returns: Swagger - The current object (this)

Param Type Description
mimeType string | Array.<string> MimeType or array of mimetypes to add

swagger.globalProduces(mimeType) ⇒ Swagger

Adds a produces to the doc

Kind: instance method of Swagger
Returns: Swagger - The current object (this)

Param Type Description
mimeType string | Array.<string> MimeType or array of mimetypes to add

swagger.nosecurity() ⇒ Swagger

Sets no security on the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Example

swagger.get('/foos/:id')
    .nosecurity();

swagger.schema(name, spec) ⇒ Swagger

Adds a schema definition to the API.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string The type name.
spec object A valid JSON schema draft 04 spec.

Example

const spec = { type: 'object', properties: { name: { type: 'string' } } };
swagger.schema('Item', spec)
    .get('/items')
    .response(200, 'Success', 'Item', true);
swagger.schema('Item', spec)
    .get('/items/:id')
    .response(200, 'Success', 'Item');

swagger.schemas(schemas) ⇒ Swagger

Adds multiple schema to the API.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).

Param Type Description
schemas array schemas to add

swagger.post(path, [options]) ⇒ Swagger

Creates a post method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.post('/foos');

swagger.get(path, [options]) ⇒ Swagger

Creates a get method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.get('/foos/:id');

swagger.put(path, [options]) ⇒ Swagger

Creates a put method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.put('/foos/:id');

swagger.delete(path, [options]) ⇒ Swagger

Creates a delete method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.delete('/foos/:id');

swagger.patch(path, [options]) ⇒ Swagger

Creates a patch method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.patch('/foos/:id');

swagger.head(path, [options]) ⇒ Swagger

Creates a head method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.head('/foos/:id');

swagger.options(path, [options]) ⇒ Swagger

Creates a options method for the specified path. Use Express style routing.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
path string The path for the method.
[options] object Options for controlling the merge.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.

Example

swagger.options('/foos/:id');

swagger.summary(summary) ⇒ Swagger

Sets the summary for the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
summary string The summary for the method.

Example

swagger.delete('/foos/:id').summary('Deletes foo.');

swagger.description(description) ⇒ Swagger

Sets the description for the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
description string The description for the method.

Example

swagger.delete('/foos/:id').description('Deletes foo');

swagger.operationId(name) ⇒ Swagger

Sets the operationId for the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
name string The name for the method.

Example

swagger.delete('/foos/:id').operationId('DeleteFoo');

swagger.tag(tag) ⇒ Swagger

Adds a tag to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
tag string The tag to add.

Example

swagger.delete('/foos/:id').tag('foo');

swagger.tags(tags) ⇒ Swagger

Adds multiple tags to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
tags Array.<string> The tags for the method.

Example

swagger.delete('/foos/:id').tags(['foo', 'bar']);

swagger.body(type, description) ⇒ Swagger

Convenience method to add a body parameter to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
type string The type of object (not full ref), e.g. "Type"
description string The description of the body parameter.

Example

swagger.post('/foo').body('Foo', 'Foo to create');

swagger.parameter(param) ⇒ Swagger

Adds a parameter to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
param object A valid Swagger parameter specification.

Example

swagger.post('/foo').parameter({
     in: 'path',
     name: 'foo',
     type: 'string',
     description: 'My foo param'});

swagger.parameters(parameters) ⇒ Swagger

Sets multiple parameters on the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
parameters array A valid Swagger parameters array.

swagger.extension(key, value) ⇒ Swagger

Adds an extension to either the current method or the doc.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
key string The x- extension to add
value object | array | number | null | string | boolean the value of the extension

swagger.consumes(mimeType) ⇒ Swagger

Adds a consumes to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
mimeType string | Array.<string> The mime-type that can be consumed.

swagger.produces(mimeType, forceGlobal) ⇒ Swagger

Adds a produces to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
mimeType string | Array.<string> The mime-type that can be consumed.
forceGlobal boolean Write to the document level produces even if in a path.

swagger.response(code, [description], [type], [isArray], [headers], [noValidation]) ⇒ Swagger

Adds a response to the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
code number The HTTP response code.
[description] string Optional description. If not specified, uses the standard HTTP response string.
[type] string Optional type (to be used in $ref).
[isArray] boolean Optional indicator that the repsonse is an array of type.
[headers] array Optional headers to include in the response.
[noValidation] boolean remove extra validation steps.

swagger.responses(responses, [options]) ⇒ Swagger

Sets multiple response on the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
responses object A valid Swagger responses object.
[options] object Options for controlling the merge.
[options.extensions] RegExp Test to allow (or deny) extensions.
[options.noValidation] booelan disable extra validation checks.

swagger.action(handler) ⇒ Swagger

Applies an action to the current method to be used with Express.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Description
handler expressHandlerCallback The Express handler function.

swagger.merge(swagger, [options]) ⇒ Swagger

Merges a well defined swagger document into this one by merging all definitions, paths, responses, tags, and externalDocs into this document.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
swagger object A well defined swagger document.
[options] object Options for controlling the merge.
[options.prefix] string All paths will be prefixed with prefix.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.
[options.filter] pathFilter Selectively filter paths.
[options.mergeBlacklist] Array.<string> [] Skip over these properties when merging

swagger._sanitizeProperties(props) ⇒ Swagger

Sanitizes the current document with respect to a list of props. It will delete any matching global properties and any method level properties that match.

Kind: instance method of Swagger
Returns: Swagger - The current object (this)

Param Type Description
props Array.<string> A list of properties to delete.

swagger.externalDocs(doc) ⇒ Swagger

Sets externalDocs on the current method.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).

Param Type Description
doc string A valid ExternalDocumentationObject.

swagger.paths(swagger, [options]) ⇒ Swagger

Merges a well defined swagger paths into this one by merging the paths found in the supplied swagger.paths into this document.

Kind: instance method of Swagger
Returns: Swagger - The current object (this).
Access: public

Param Type Default Description
swagger object A well defined swagger document.
[options] object Options for controlling the merge.
[options.defaultResponses] object Applies a default set of responses to all methods when merging, but will not override existing responses.
[options.responses] object Applies all responses to all methods when merging, overriding any existing responses.
[options.prefix] string All paths will be prefixed with prefix.
[options.express] boolean true All expressjs paths will be rewritten to Swagger.
[options.filter] pathFilter Selectively filter paths.
[options.noValidation] boolean disable extra validation
[options.extensions] RegExp Test to allow (or deny) extensions from paths and responses.

swagger.apidoc() ⇒ object

Returns the Swagger 2.0 API document.

Kind: instance method of Swagger
Returns: object - Swagger 2.0 API document.
Access: public

Swagger.forEachAction(swagger, callback)

Iterates over each endpoint in the swagger document. Useful for binding to Express.

Kind: static method of Swagger
Access: public

Param Type Description
swagger Swagger The swagger document.
callback forEachActionCallback Called for each endpoint action.

Swagger.actionMiddleware(swagger, verb, path) ⇒ object

Gets the Swagger action middleware function for Express.

Kind: static method of Swagger
Returns: object - The middleware for the specified endpoint
Access: public

Param Type Description
swagger Swagger The swagger document.
verb string The HTTP verb.
path string The HTTP path.

Swagger.securityMiddleware(swagger, verb, path) ⇒ function

Gets the Swagger security middleware function for Express.

Kind: static method of Swagger
Returns: function - middleware
Access: public

Param Type Description
swagger Swagger The swagger document.
verb string The HTTP verb.
path string The HTTP path.

openapi-doc~customAuthentication ⇒ boolean

Callback function for custom authentication.

Kind: inner typedef of openapi-doc
Returns: boolean - Return true if valid, or false if invalid.
Access: public

Param Type Description
req object The express request object.

openapi-doc~expressHandlerCallback : function

Callback for handling Express action.

Kind: inner typedef of openapi-doc

Param Type Description
request object The Express request object.
response object The Express response object.

openapi-doc~pathFilter ⇒ boolean

Callback function to selectively filter out specific methods. Return true to include the path.

Kind: inner typedef of openapi-doc
Returns: boolean - Return true if include, or false to exclude.
Access: public

Param Type Description
swagger object The swagger document.
path string The path.
verb string The verb.

openapi-doc~forEachActionCallback : function

Callback for iterating over Swagger endpoint actions.

Kind: inner typedef of openapi-doc

Param Type Description
path string The endpoint path.
verb string The endpoint verb.

Author

Axway support@axway.com https://axway.com

License

This code is proprietary, closed source software licensed to you by Axway. All Rights Reserved. You may not modify Axway’s code without express written permission of Axway. You are licensed to use and distribute your services developed with the use of this software and dependencies, including distributing reasonable and appropriate portions of the Axway code and dependencies. Except as set forth above, this code MUST not be copied or otherwise redistributed without express written permission of Axway. This module is licensed as part of the Axway Platform and governed under the terms of the Axway license agreement (General Conditions) located here: https://support.axway.com/en/auth/general-conditions; EXCEPT THAT IF YOU RECEIVED A FREE SUBSCRIPTION, LICENSE, OR SUPPORT SUBSCRIPTION FOR THIS CODE, NOTWITHSTANDING THE LANGUAGE OF THE GENERAL CONDITIONS, AXWAY HEREBY DISCLAIMS ALL SUPPORT AND MAINTENANCE OBLIGATIONS, AS WELL AS ALL EXPRESS AND IMPLIED WARRANTIES, INCLUDING BUT NOT LIMITED TO IMPLIED INFRINGEMENT WARRANTIES, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, AND YOU ACCEPT THE PRODUCT AS-IS AND WITH ALL FAULTS, SOLELY AT YOUR OWN RISK. Your right to use this software is strictly limited to the term (if any) of the license or subscription originally granted to you.