[go: nahoru, domu]

Skip to content

kogosoftwarellc/open-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

express-openapi NPM version Downloads Build Status Coveralls Status

Effortlessly add routes and middleware to express apps with openapi documents.

Highlights

Example

Let's use the sample project located at ./test/sample-projects/basic-usage/.

The project layout looks something like this:

basic express-openapi-project

Here's how we add our routes to express:

var app = require('express')();
var bodyParser = require('body-parser');
var openapi = require('express-openapi');
var cors = require('cors');

app.use(cors());
app.use(bodyParser.json());

openapi.initialize({
  apiDoc: require('./api-doc.js'),
  app: app,
  routes: './api-routes'
});

app.use(function(err, req, res, next) {
  res.status(err.status).json(err);
});

app.listen(3000);

Our routes are now active and we can test them out with Swagger UI:

swagger ui

For more examples see the sample projects used in tests.

Configuring Middleware

You can directly control what middleware express-openapi adds to your express app by using the following vendor extension properties. These properties are scoped, so if you use one as a root property of your API Document, all paths and operations will be affected. Similarly if you just want to disable middleware for an operation, you can use these properties in said operation's apiDoc. See full examples in the ./test/sample-projects/ directory.

Supported vendor extensions

  • 'x-express-openapi-disable-middleware': true - Disables all middleware.
  • 'x-express-openapi-disable-coercion-middleware': true - Disables coercion middleware.
  • 'x-express-openapi-disable-defaults-middleware': true - Disables defaults middleware.
  • 'x-express-openapi-disable-response-validation-middleware': true - Disables response validation middleware I.E. no res.validateResponse method will be available in the affected operation handler method.
  • 'x-express-openapi-disable-validation-middleware': true - Disables input validation middleware.

API

.initialize(args)

Initializes routes and middleware on an express app.

args.apiDoc

Type Required Description
Object Y This is an openapi (swagger 2.0) compliant document. See the OpenAPI-Specification for more details.

args.apiDoc.paths should be an empty object. express-openapi will populate this for you. This prevents you from defining your paths in 2 places.

args.apiDoc.basePath will add a prefix to all routes added by express-openapi.

args.apiDoc.definitions will be used for de-referencing $ref properties in parameters.

args.app

Type Required Description
Object Y The express app you wish to initialize.

args.routes

Type Required Description
String Y A path to the directory that contains your route files.

Route files are logically structured according to their URL path. For cross platform compatibility, URLs that accept a parameter use the swagger format for parameters as opposed to the express format (i.e. use {id} instead of :id). Filenames in Windows do not allow the : character as it is confused with drive names.

For example, if you have the following api routes that you wish to add to your express app:

GET /v1/users/{id}
POST /v1/users

You would define basePath: '/v1' in your apiDoc, and layout your routes directory as follows:

<project>
        `routes/
               `users/
                     `{id}.js
                users.js

The contents of <project>/routes/users/{id}.js would look like this:

module.exports = {
  // parameters for all operations in this path
  parameters: [
    {
      in: 'path',
      name: 'id',
      required: true,
      type: 'integer'
    }
  ],
  get: [
    /* business middleware not expressible by openapi documentation goes here */
    function(req, res, next) {
      var validationError = res.validateResponse(200, /* return the user or an error */);

      if (validationError)
        return next(validationError);
      }

      res.status(200).json(/* return the user or an error */);
    }
  ]
};

module.exports.get.apiDoc = {
  description: 'A description for retrieving a user.',
  tags: ['users'],
  operationId: 'getUser',
  // parameters for this operation
  parameters: [
    {
      in: 'query',
      name: 'firstName',
      type: 'string'
    }
  ],
  responses: {
    default: {
      $ref: '#/definitions/Error'
    }
  }
};

Modules under args.routes expose methods. Methods may either be a method handler function, or an array of business specific middleware + a method handler function.

express-openapi will prepend middleware to this stack based on the parameters defined in the method's apiDoc property. If no apidoc property exists on the module method, then express-openapi will add no additional middleware.

args.docsPath

Type Required Default Value Description
String N /api‑docs Sets the path that Swagger UI will use to request args.apiDoc with populated paths. You can use this to support multiple versions of your app.

args.errorTransformer

Type Required Description
Function N Transforms errors to a standard format as defined by the application. See express-openapi-validation#args.errorTransformer and express-openapi-response-validation for more info.

args.exposeApiDocs

Type Required Default Value Description
Boolean N true Adds a route at args.apiDoc.basePath + args.docsPath. The route will respond with args.apiDoc.

args.validateApiDoc

Type Required Default Value Description
Boolean N true Validates args.apiDoc before and after path population. This does not effect individual route validation of route parameters. You can disable this behavior by passing false.

LICENSE

The MIT License (MIT)

Copyright (c) 2016 Kogo Software LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.