DEV Community

Cover image for How to Document an Express API with Swagger UI and JSDoc

How to Document an Express API with Swagger UI and JSDoc

Kate Bartolo on November 29, 2020

JSDoc is a popular tool for generating documentation from comments in the source code of your app. This serves two purposes. First, the documentati...
Collapse
 
hkhattabii profile image
hkhattabii

It is possible to generate the documentation into a static html page to be readeable without launching the server ?

Collapse
 
kabartolo profile image
Kate Bartolo

Good question! I'll look into this and get back to you

Collapse
 
hkhattabii profile image
hkhattabii

Thank you very much :)

Thread Thread
 
kabartolo profile image
Kate Bartolo

No problem. It looks like Rolf's answer is the way to go. Good luck :)

Thread Thread
 
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 ! :)

Collapse
 
hyeonss0417 profile image
Hyeonss

If you are using Tspec, it automatically parses your TypeScript types and generates up-to-date OpenAPI specification with beautiful Swagger UI.
I strongly recommend you to try it out to make static html page with Tspec.

Collapse
 
rolfstreefkerk profile image
Rolf Streefkerk
Collapse
 
hkhattabii profile image
hkhattabii

Thank toi, I will look forward tous afternoon :)

Collapse
 
pshdevio profile image
pshdevio

This might sound crazy, but the easiest way I've found is to simply Save the HTML page out from your browser once it's generated ! Crazily simple.

Collapse
 
ats1999 profile image
Rahul kumar

Go through the source code and trigger the function/file which is being executed

Collapse
 
sherwinwater profile image
Shuwen

GET /users/:id doesn't work for me. I change it to GET /users/{id}, which works.

In the api-docs, once I input id number and click execute, here is the difference:

/users/{id}
curl -X GET "localhost:3000/users/1" -H "accept: application/json"

/users/:id
curl -X GET "localhost:3000/users/:id" -H "accept: application/json"

Collapse
 
kabartolo profile image
Kate Bartolo

Hi Shuwen!
I'm really glad you pointed this out because it's totally a bug. I'm not sure why I thought :id worked, but you're right that it doesn't.

I'll update the tutorial and sample project. Thank you!

Collapse
 
sherwinwater profile image
Shuwen

Hi Kate, Thank you your article to help me setting up my swagger documentation. One of the best article I find and I've recommend it to my coworkers.

Thread Thread
 
kabartolo profile image
Kate Bartolo

Thank you so much! I'm happy it was helpful

Collapse
 
habereder profile image
Raphael Habereder

Good find! And also, welcome to DEV :)

As far as I know, swagger implements {} as template delimiters, not colons, but I'm not using node a lot (yet), so maybe I am missing something here.
I can't find any information in the swagger-docs that mention the colon-style, so input from @kabartolo would be great here :)

Collapse
 
rolfstreefkerk profile image
Rolf Streefkerk

There's another way of doing this with tools provided by Swagger.io you can have it load in the OpenAPI yaml document, and it will generate the HTML specification document for you.

github.com/swagger-api/swagger-cod...

Collapse
 
kabartolo profile image
Kate Bartolo

This is good to know, thank you!

Collapse
 
mamta92 profile image
Mamta Shettigar

Hi I'm using swagger-jsdoc library. Wanted to know if Visual Studio code offers any extensions for intellisense? There is an extension named swagger-jsdoc but the syntax for post request is quite outdated according to openapi 3.0.0 and hence not able to get automatic intellisense for requestBody..It still uses ;-
parameters:

  • - name: "param_name"
  • description: "매개변수"
  • in: body
  • required: true
  • type: string
  • example: "foo"

Instead of requestBody:

  • required: true
  • content:
  • application/json:
  • schema:
  • $ref: '#/components/schemas/NewUser'
Collapse
 
ave profile image
Alexander • Edited

This is the main drawback of the whole swagger-jsdoc approach to swagger.
Defining API schema as an annotation to your method in the comment section is prone to typos and other mistakes that are not picked up.

I usually go to editor.swagger.io and define the whole API spec there with all the "definitions" schemas and what not. Alternatively, you could use the OpenAPI (Swagger) Editor extension for VS Code ( I don't use it though, so not sure how up-to-date it is).
Then it is a matter of copying pieces of it into right places in the code.
Also, note that you don't have to define the common definitions and schemas in the annotation section in your code. It is cleaner to put them into a separate yaml file, say definitions.yaml, then load the file directly into swaggerJSDoc object:

const options = {
  swaggerDefinition,
  // Paths to files containing OpenAPI definitions
  apis: ['./routes/*.js', './doc/definitions.yaml'],
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
burloiumarian23 profile image
burloiumarian23 • Edited

Good hint ... it wasn't working initially for me , because I also added anotation paths which was wrong

Collapse
 
apanjwani0 profile image
Aman Panjwani

Hi, is there any way to specify schema in a variable form ?
eg-> using joi-tos-wagger(npmjs.com/package/joi-to-swagger).

It would be great if I can just specify swagger components schemas in the validation files itself, would save a lot of time. Or is there any other alternate available ?

PS-: currently there are some articles to use joi-to-swagger, which does the same thing, like -: medium.com/swlh/do-not-repeat-your.... But I'm asking if we can do this with jsdoc.

Thanks.

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

Thanks for sharing. I wasn't aware of this.

Collapse
 
rizkyrajitha profile image
Rajitha Gunathilake

thanks for the article
this was really helpful .👌

Collapse
 
galelmalah profile image
Gal Elmalah

This is great!
Thank you 🙂

Collapse
 
kabartolo profile image
Kate Bartolo

Thanks! Hope it was helpful :)

Collapse
 
sherwinwater profile image
Shuwen

This is the article I am looking for. Thank you!

Collapse
 
hyeonss0417 profile image
Hyeonss

In 2023, you don't need to do that.

⚠️ The worst down-side of generating OpenAPI with JSDoc is REPEATING yourself for every schemas you made even if some schemas are shared with other APIs. (violating the DRY principle) ⚠️

Tspec automatically parses your TypeScript types and generates up-to-date OpenAPI specification with beautiful Swagger UI.

I strongly recommend you to try it out as I'm a maintainer of Tspec.

Collapse
 
yyyj2813 profile image
yeahhaey

Nice

Collapse
 
darkmavis1980 profile image
Alessio Michelini

Really nice and comprehensive article!

Collapse
 
vturnus profile image
William Rookwood

Thank you for your greate article,

Would you have or know any article that customize the CSS of the swagger?

Collapse
 
mahbod profile image
Mahbod Ahmadi

Can we use a javascript variable in the swagger comment doc?
I have a json file and stored the responses messages and I wanna use them into doc. How can I do that?

Collapse
 
akhil27styles profile image
Akhil Kumar Singh

can we auto-generate the yaml file by using some command?

Collapse
 
burloiumarian23 profile image
burloiumarian23

Very good article ! Thanks man!

Collapse
 
abold profile image
Amond Bold

Thank you. Good post!!!

Collapse
 
noone_ profile image
Nurgul

Can I use this method for API projects that are coded in CPP?