Swagger Express Middleware

Swagger 2.0 middlware and mocks for Express.js

The createMiddleware function

Swagger Express Middleware exposes several JavaScript classes, but most of them are only needed for advanced usage scenarios. Most simple apps can just use the createMiddleware function, which is a convenience function that reduces the amount of code you need to write.

Example

All of the examples in these docs use the createMiddleware function like this:

const express = require('express');
const createMiddleware = require('@apidevtools/swagger-express-middleware');

let app = express();

// Call the createMiddleware function (aliased as "middleware")
createMiddleware('PetStore.yaml', app, function(err, middleware) {
    ...
});

But any of the examples or samples could be rewritten to use the Middleware class and the init method instead, like this:

const express = require('express');
const swagger = require('@apidevtools/swagger-express-middleware');

let app = express();

// Create a Middleware object
let middleware = new swagger.Middleware(app);

// Call its init method
middleware.init('PetStore.yaml', function(err) {
    ...
});

For a complete example of this second pattern, see Sample 2

API

createMiddleware(swagger, router, callback)

The createMiddleware function is the main export of Swagger Express Middleware — it’s what you get when you require('@apidevtools/swagger-express-middleware'). It’s just a convenience function that creates a Middleware object and calls its init method.