Skip to content

Swagger

Thiago Bustamante edited this page Jan 20, 2019 · 1 revision

Swagger

Typescript-rest can expose an endpoint with the swagger documentation for your API.

For example:

let app: express.Application = express();
app.set('env', 'test');
Server.buildServices(app);
Server.swagger(app, {
    endpoint: 'api-docs',
    filePath: './test/data/swagger.yaml',
    host: 'localhost:5674',
    schemes: ['http']
});

You can provide your swagger file as an YAML or a JSON file.

Now, just access:

http://localhost:5674/api-docs  // Show the swagger UI to allow interaction with the swagger file
http://localhost:5674/api-docs/json  // Return the swagger.json file
http://localhost:5674/api-docs/yaml  // Return the swagger.yaml file

If needed, you can provide options to customize the Swagger UI:

const swaggerUiOptions = {
  customSiteTitle: 'My Awesome Docs',
  swaggerOptions: {
    validatorUrl: null,
    oauth2RedirectUrl: 'http://example.com/oauth2-redirect.html',
    oauth: {
      clientId: 'my-default-client-id'
    }
  }
};

Server.swagger(app, {
    endpoint: 'api-docs',
    filePath: './test/data/swagger.yaml',
    host: 'localhost:5674',
    schemes: ['http'],
    swaggerUiOptions: swaggerUiOptions
});

See swagger-ui-express for more options and swagger-ui for more swaggerOptions. Note: Not all swagger-ui options are supported. Specifically, any options with a Function value will not work.

To generate the swagger file, you can use the typescript-rest-swagger tool.

npm install typescript-rest-swagger -g
swaggerGen -c ./swaggerConfig.json

typescript-rest-swagger tool can generate a swagger file as an YAML or a JSON file.