DEV Community

Discussion on: How to Document an Express API with Swagger UI and JSDoc

 
hkhattabii profile image
hkhattabii

I seen that what he shared is for a maven project and I try to find for an express project :(

Thread Thread
 
kabartolo profile image
Kate Bartolo • Edited

Oh okay, I think I found a way to generate an HTML file. I'm not really familiar with Swagger Codegen, but I found this wrapper: swagger-nodegen-cli. This makes it easier to install.

You have to have Java installed, then just run

npm install -g swagger-nodegen-cli
Enter fullscreen mode Exit fullscreen mode

Try running sc version to make sure it was installed correctly.

Assuming you want to write the docs using JSDoc, you can generate a swagger.json spec file with swagger-jsdoc:

Install swagger-jsdoc globally:

npm install -g swagger-jsdoc
Enter fullscreen mode Exit fullscreen mode

In the root directory of your Express project, create a separate file for the Swagger definition object (swaggerDefinition from the tutorial):

// swagger-def.js
module.exports = {
  openapi: '3.0.0',
  info: {
    title: 'Express API for JSONPlaceholder',
    version: '1.0.0',
    description:
      'This is a REST API application made with Express. It retrieves data from JSONPlaceholder.',
    license: {
      name: 'Licensed Under MIT',
      url: 'https://spdx.org/licenses/MIT.html',
    },
    contact: {
      name: 'JSONPlaceholder',
      url: 'https://jsonplaceholder.typicode.com',
    },
  },
  servers: [
    {
      url: 'http://localhost:3000',
      description: 'Development server',
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

To create the swagger.json file, run

swagger-jsdoc -d swagger-def.js routes/*.js
Enter fullscreen mode Exit fullscreen mode

Replace routes/*.js with the paths to your files with JSDoc comments. Also see the swagger-jsdoc CLI docs.

These file paths are all relative to the root directory, so be sure to change them depending on where you want your files to live.

Finally, to create the HTML file, run

sc generate -i swagger.json -l html
Enter fullscreen mode Exit fullscreen mode

You should have an index.html in the root directory. Let me know if this works for you!

Thread Thread
 
hkhattabii profile image
hkhattabii

Thank you I will try that now ! :)