We started the Express.js journey with a simple CRUD Express.js app that has a bunch of APIs. Though returned dummy data. Then we added MySQL support that made the app more usable. But still, one big piece is missing. And that’s API documentation in Swagger and Swagger UI. In this article, we go through how to add Swagger to an Express.js app in five minutes.

By contrast to Java Spring Boot that adding Swagger and Swagger UI is a piece of cake, thanks to huge sets of annotations. The process is quite different in Express.js and other languages like PHP. We need to handcraft the documentation, generate JSON or YAML file and then add it to the application.

Don’t panic! It is not difficult at all. We go through each step in this article.

Adding swagger-ui-express library

There are numerous libraries available for Swagger UI. Based on my experiments the best is swagger-ui-express . It’s super easy to use. Hence, I highly recommend it.

To add swagger-ui-express to the project, just run,

Creating the Swagger documentation

By far this is the most timeconsuming step. We have to handcraft the documentation. For that, we leverage on Swagger Editor. We start by modifying the example and adding the stuff related to our User APIs.

There’s nothing much for me to explain here. It’s all trial and error. Just make sure to add the correct data type. It is not difficult at all. It’s just timeconsuming.

The final result looks like this:

But we need the json version. We can generate that via Swagger Editor too. Just go to File and click on Convert and save as JSON .

Now let’s create a directory called swagger in the application root and place both YAML and JSON versions.

Use swagger.json in the project

Now that we have the documentation ready, we just need to glue things together. Head to app.js and add the following lines of code,

As you can see we just added only three lines of code. The first line imports the swagger-ui-express library. The second line points to the Swagger documentation that we created in the previous step. And the last line creates a route to serve the document.

Now if you run, npm run start and type http://localhost:8090/api-docs you should be able to see the Swagger UI and interact with the APIs,

Swagger UI

The complete example is available on GitHub at the link below,

https://github.com/kasramp/sample-rest-with-expressjs

That’s all. Hope it didn’t take more than five minutes to add Swagger to the Express.js 😀

Inline/featured images credits

Keyboard and laptop image by Paul Esch-Laurent on Unsplash