Today, almost every application has to be connected and to share data with other applications. The best way to do that is through APIs. For a long time there hasn’t been any industry standard for designing and documenting APIs. And API without a good documentation on how to use it, is useless. Because of that, developers have worked hard to create a standard way of describing APIs and documenting them. One such proposal is Swagger.

What is Swagger?

On the Swagger site we can find definition of Swagger:

Swagger is the world’s largest framework of API developer tools for the OpenAPI Specification(OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.

Swagger contains a large ecosystem of tools from which we can single out a set of core tools:

Swagger Editor

Swagger Codegen

Swagger UI

Swagger Editor

Swagger Editor is a tool that allows you to edit Swagger API specification inside your browser. While editing Swagger API specification, the tool will preview the documentation in real time. That way we can immediately see how documentation will look after applying the most recent changes. The editor is easy to use, has clean user interface and has a lot of features to help you design and document RESTful APIs. On GitHub you can find the source code of the tool:

The editor is available online and anybody can use it by accessing the following URL.

Swagger Codegen

Swagger code generator is a template-driven engine that allows you to generate interactive documentation, API clients and server stubs from Swagger definitions. List of supported languages is quite extensive and can be found on this URL.

In our opinion, these are the pros and cons of Swagger Codegen:

Pros:

Generates server code, client code and documentation

Allows quick changes of the API

The code generator is open source

Cons:

Increase in project complexity by using additional tools and libraries

Generates a lot of code that the user might not understand

Swagger UI

Swagger UI allows anyone to visualize a RESTful API. Visualization is automatically generated from the Swagger specification. So Swagger UI takes an existing JSON or YAML document and creates interactive documentation. That documentation can be used by anyone who has permission to access it. Documentation could look like this:

Figure 1. Demo application Swagger UI

How could I use Swagger?

Swagger is mainly used to document APIs. There are various approaches and the two most common ways are:

Top-down (design-first) approach : in this approach Swagger Editor is used to create Swagger definition and Swagger Codegen is then used to generate code for a client and a server. Basically, this means Swagger will be used to design the API before any code has been written.

: in this approach Swagger Editor is used to create Swagger definition and Swagger Codegen is then used to generate code for a client and a server. Basically, this means Swagger will be used to design the API before any code has been written. Bottom-up approach: in this approach user already has an existing RESTful API and Swagger will be used only to document the existing API.

In this blog post we will describe a bottom-up approach. First, we will present demo application we will be working on. After that we will add a simple Swagger UI to our demo application.

Demo application

In this chapter, we will present our backend application. We have decided that we want to create our backend application based on Node.js and Express.js. We will create RESTful API. The demo application will expose an API for user management. Through the API user will be able to create, delete, update and get one or all users. The whole demo application is defined in one file — server.js.

Dependencies

For creating a RESTful API we will use Express.js. Parsing incoming request body will be done by the body-parser. As a database, we will use MongoDB. Mongoose will be used for communication with the database.

Database Model

Mongoose internally uses MongoDB Node.js Driver for the communication with MongoDB. The questions we should be asking ourselves are: “Do we want to use the raw driver? Do we need an object-document modeling tool?” In a complex web application, we will have many types of entities in the database. By using an object modeling framework(ODM, a counterpart to ORMs from the SQL world) we will be able to create better encapsulation of data and omit low level considerations. Because of that we will use Mongoose for establishing communication with MongoDB. On the official project page we can find the definition of Mongoose:

MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

We have only one entity to model and that is user. The user model has three fields:

Email

First name

Last name

The user schema will look like this:

Controllers

In this use case, we will create very simple functions that will be used as controllers for CRUD operations on user objects. So we will have the following methods:

createUser — function for creating a new user in the system

— function for creating a new user in the system updateUser — function for updating an existing user in the system

— function for updating an existing user in the system deleteUser — function for deleting an user from the system

— function for deleting an user from the system getAllUsers — function for getting all users in the system

— function for getting all users in the system getOneUser — function for getting an user by ID

Routes

At the end, we need to route requests to appropriate functions. This will be done by using the standard Express.js routing mechanism. Basically, we will define application end points (URIs) and connect that end points with these functions that will generate a response.

We have defined a simple Express.js application in this section. In the next section we will see how can we use Swagger specification that describes application to show interactive documentation.

Adding Swagger to demo application

Which library should we use?

There are a few libraries that can be used to create Swagger interactive documentation for Node.js/Express.js RESTful API. The most notable are:

Swagger-node-express

This is the official Swagger module for Node.js. The official presentation of project doesn’t contain documentation that explains how can a user add Swagger UI to an existing project. However, here you can find a nice tutorial that explains the main steps of creating documentation. The things that we like about this solution are:

It is official package that is supported by Swagger organization. This is great because we know that there is organization that is developing this package.

The library is open source — if you have any issue you can check source code and contribute the fix. Also, this means that much more people will have a chance to review a code and to improve the code if necessary.

The solution contains Swagger Editor and Swagger Codegen — we can use same package in top-down(design first) and bottom-up approach.

However we are not the fan of the following:

Manual setup — Swagger UI needs to be copied manually into the source code of the application to which we are adding documentation. For us this is a big disadvantage. We need to copy the source code to ours application and when there is an update of Swagger UI we need to do that manually, again. In our opinion that should be included in Swagger package.

into the source code of the application to which we are adding documentation. For us this is a big disadvantage. We need to copy the source code to ours application and when there is an update of Swagger UI we need to do that manually, again. In our opinion that should be included in Swagger package. Complex setup — in order to setup your application to host Swagger documentation, you need to add quite a few paths on your server, additional to ones we have already mentioned, and configure a few things. In the tutorial there is no detailed explanation of the setup. The tutorial is complete and you will get the things working, but it is not well explained why you need to do some of the things.

on your server, additional to ones we have already mentioned, and configure a few things. In the tutorial there is no detailed explanation of the setup. The tutorial is complete and you will get the things working, but it is not well explained why you need to do some of the things. Poor documentation — documentation is quite poor and in order to find out what are arguments that are used to setup Swagger, you need to read the source code of a few different libraries.

Swagger-ui-express

A community driven package that adds a middleware to your Express.js application that serves the Swagger UI bound to your Swagger document. The library is very easy to setup, you just need to add one route that will host Swagger UI, and guess what you don’t need to copy anything manually. This is an open source project and it is still actively maintained. Documentation is good and everything that you need should be there.

Given the functionality and simplicity of use we have decided to use this library in order to add documentation to our application.

In the next section we will describe what needs to be done in order to add documentation to our application.

Implementation

First, we need to add a library to our project:

npm i swagger-ui-express -S

When the library is added to a project we need to add a route on which we will host Swagger UI. Also, we need to load the Swagger API definition of our application so that we can host it in Swagger UI. In our case the Swagger API definition is a file that contains JSON object with information about our application. For creating the Swagger API defintion, we have used Swagger Editor. In this blog post we will not describe how have we created the Swagger API definition, but we can suggest this tutorial, if the reader is not familiar with the Swagger specification, set of rules that are used to create the Swagger API definition. Created Swagger API definition will be stored in our demo project as a JSON object in swagger.json file. The entire setup should looks like this:

As you can on route api-docs we will add two middleware. First middleware that we will add is serve . This middleware will return static files that are needed for hosting Swagger UI. Second middleware is the setup function that will generate middleware that will setup Swagger UI to use users parameters.

That is it! We now have interactive Swagger documentation in our application. When demo application is started, documentation can be accessed at this URL: http://localhost:3000/api-docs.

Alternatives

At the end, you can ask yourself, do we need to use Swagger or are there any alternative? No you don’t need to use Swagger, and there are plenty of alternatives:

Postman — if you don’t want to host documentation in your application, you can create Postman collection, and distribute that to the user of your API. But if your API is changing fast, you will have a lot of versions of Postman collection and that can be pretty messy.

— if you don’t want to host documentation in your application, you can create Postman collection, and distribute that to the user of your API. But if your API is changing fast, you will have a lot of versions of Postman collection and that can be pretty messy. apiDoc — is RESTful web API documentation generator. It creates a documentation from API annotations in your source code. This tool doesn’t support design first approach, there is not code generator and fancy editor.

— is RESTful web API documentation generator. It creates a documentation from API annotations in your source code. This tool doesn’t support design first approach, there is not code generator and fancy editor. API Console — is based on RAML(RAML — RESTful API Modeling Language). RAML is direct competitor to Swagger. It supports top-down and bottom up approach and has editor and code generator.

— is based on RAML(RAML — RESTful API Modeling Language). RAML is direct competitor to Swagger. It supports top-down and bottom up approach and has editor and code generator. docbox — RESTful API documentation generator. It takes Markdown files and generates a friendly two-column layout with navigation, permalinks, and examples. This library can be used only for API documentation.

This is not a complete list of all alternatives, but a list of some that are more or less popular at the moment.

Conclusion

Congratulations! You now have a fully functional example of Express.js/Node.js project with Swagger UI. In this tutorial we have created a Node.js/Express.js application that exposes RESTful API. We then added Swagger UI that is documenting the RESTful API of our application.

The complete source code from this project can be found at the following GitHub repository:

I hope you have enjoyed this tutorial, and learned a thing, or two.

If you have any questions or issues getting this to work feel free to contact me on Twitter @robince885 or in the comments below. You can find more information about me on LinkedIn:

I would like to thank @vdimitrieski for his help and support. Feel free to contact him as well. Some more information about him and what he is doing you can find on his LinkedIn: