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.
-
swagger (optional) -
string
orobject
The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format. Or a valid Swagger object. Any$ref
pointers to other files/URLs will be interpreted as relative to the main Swagger file. -
router (optional) -
express.App
orexpress.Router
An Express Application or Router that will be used to determine settings (such as case-sensitivity and strict routing) and to register path-parsing middleware.
NOTE: If you don’t specify this parameter, then the default Express routing settings will be used (case-insensitive, non-strict). You can override this parameter (or the defaults) for any specific middleware by passing an Express App or Router to the middleware. -
callback (optional) -
function(err, middleware)
A callback function that will be called once the Swagger API is fully parsed, dereferenced, and validated. The second parameter is the Middleware object that was created.