Swagger Express Middleware

Swagger 2.0 middlware and mocks for Express.js

Files middleware

Serves your Swagger API file(s) so they can be used with front-end tools like like Swagger UI, Swagger Editor, and Postman.

Example

This example uses the PetStore.yaml sample Swagger API. If you aren’t familiar with using middleware in Express.js, then read this first.

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

let app = express();

createMiddleware('PetStore.yaml', app, function(err, middleware) {
    // Add the Files middleware to the Express app
    app.use(middleware.files({
        // Change the URL of the raw Swagger files
        rawFilesPath: '/my/custom/path'
    }));

    app.listen(8000, function() {
        console.log('Go to to http://localhost:8000/my/custom/path/PetStore.yaml');
    });
});

Run the above example and then browse to http://localhost:8000/api-docs/ and http://localhost:8000/my/custom/path/PetStore.yaml. The first URL will return the Swagger API in JSON. The second URL will return the raw PetStore.yaml file. Note that the second URL’s path has been customized in the example code.

Options

middleware.files(router, options)

This is the function you call to create the Files middleware. All of its parameters are optional.

Property Type Default Description
useBasePath bool false If set to true, then the apiPath and rawFilesPath will be prepended with the Swagger API’s basePath.

For example, if the basePath in the Swagger API is “/api/v1”, then the Swagger JSON file would be served at “/api/v1/api-docs/” instead of “/api-docs/”.
apiPath string /api-docs/ The path that will serve the fully dereferenced Swagger API in JSON format. This file should work with any third-party tools, even if they don’t support YAML, $ref pointers, or mutli-file Swagger APIs.

To disable serving this file, set the path to a falsy value (such as an empty string).
rawFilesPath string /api-docs/ The path that will serve the raw Swagger API file(s).

For example, assume that your API consists of the following files:
- Main.yaml
- Users.json
- Products/Get-Products.yml
- Products/Post-Products.yaml

By default, each of these files would be served at:
- /api-docs/Main.yaml
- /api-docs/Users.json
- /api-docs/Products/Get-Products.yml
- /api-docs/Products/Post-Products.yaml

To disable serving raw Swagger files, set the path to a falsy value (such as an empty string).