Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Getting Started with Swagger: Node.js applications to document APIs

In this tutorial we shall learn how to make use of Swagger for Node.js applications that can help in documenting APIs.

If you are developer, you might prefer the model where documentation of the API happens directly with the source code where APIs are implemented as well. This primarily has certain advantages. One is that it surely helps developers in keeping the implementation and documentation of the APIs in sync. Another advantage is that this also helps in creating awareness for the upwards compatibility of APIs. Now, while this method happens to be very popular for Java applications, others can also make use of this approach. One can also do this for Node.js applications by making use of a popular web application framework known as Express.

However, the Swagger Node Express module doesn’t exist on GitHub at present. Also, the page redirects to another, Swagger Node, which is probably the replacement.

What is Swagger?

In short, Swagger is a formal specification with associated ecosystem tools to cover everything from user interfaces, code libraries and commercial API management solutions.

Swagger is basically the representation of RESTful API in a documentation format. As such, with an API that is Swagger enabled, one gets interactive documentation, generation of SDK and much more. One can make use of it to describe the available endpoints that an API exposes, the contract or interface that consumes these endpoints, and much more. Besides providing a common interface for the description of REST APIs, it also has its own Swagger UI, which is a nice interface that creates documentation and also provides a built-in client, all for interaction with the REST API.

It belongs to the open source camp and also has plenty of developers who are looking to support it in every modern programming language and environment. The Swagger community also provides plenty of libraries and tools that allow the integration of Swagger into a project. At present, many popular companies are known to make use of Swagger, and big names like Microsoft and PayPal are also among them.

What are the benefits of using Swagger?

Now we know that Swagger is a open source tool for documenting APIs. Let's have a look at the benefits of using it

  • Common language: Swagger provides some easy set of rules to be followed by both the consumers and providers. So it is very easy to use it.
  • User friendly: Swagger supports both JSON and YAML formats. So it is very user friendly for developers.
  • Complete API lifecycle: Swagger provides complete API lifecycle, starting from design, documentation, code generation, testing, monitoring etc. So the user can pick up any number of choices.
  • Easy integration: Swagger provides easy integration for both new and new APIs.
  • Community support: It has a strong community support for development and future growth.
  • Continuous enhancement: Swagger provides continuous enhancement and growing tool sets.

What are the approaches to use Swagger?

For API providers:

Swagger is mainly used to document APIs. So the API providers should know the approaches to use it in their documentation. There are various approaches and following are the two most common ways.

  • Top-down approach: In this top-down approach, Swagger Editor is used to create Swagger definition and then Swagger Codegen tool (integrated with Swagger) is used to generate implementation details for the server.
  • Bottom-up approach: This bottom-up approach is suitable when you have an existing REST API. This REST API is used to create Swagger definition. Now the definition can be created in two ways. First, you can create it manually by using Swagger editor. In the second option, you need to use supporting frameworks like JAX-RS, node.js, and the definition will be generated automatically.

For API consumers:

API consumers generally used to integrate with an API which is having existing Swagger definition. For them, the online version of Swagger UI for exploring the API is very useful. But, here you should have a URL to the Swagger definition API. After this you can use Swagger Codegen tool to generate the client library.

What is Node.js?

Node.js happens to be runtime environment which is mainly meant for the development of server-side web applications. It has an open source license and is also supported across all platforms. As such, Node.js is not a JavaScript framework. However, its applications are written in JavaScript and can also be run within its platform as well.

Primarily, Node.js offers an event-driven architecture and non-blocking I/O API. This is responsible for optimizing an application’s scalability and throughput.

Swagger Node comes with a large number of great capabilities and in order to define APIs, makes use of separate YAML files. Here, the API documentation is close to the implementation of the API, but still not in the same files. We shall now take a look at how this method is implemented.

What are the Swagger-tools?

Swagger-tools basically happened to be an API that was meant for the full validation of Swagger documents. However, at present, it is a lot more than just that. Now, to give a more comprehensive idea, we shall take a look at what swagger-tools have, to offer.

  • A tool for command line
  • An API for JavaScript
  • Connect middleware.

We shall now take a look at what these actually are.

The Swagger project with its eco-system provides a set of core tools to facilitate its usage in various situations. All these tools are open-source projects freely available under Apache License. Apart from the core tools, Swagger also provides associate tools for handling other project requirements.

Let’s have a look at the core tools first.

  • Swagger Core: It contains Java related libraries to generate and read Swagger definitions
  • Swagger Codegen: This is code generation tool. It is used to generate client and server side code from Swagger definitions
  • Swagger UI: This is used to browse Swagger APIs
  • Swagger Editor: This is also a browser based editor for writing Swagger definitions in JSON or TAML format

Now let’s check the adjacent tools.

  • Swagger JS: This is a Java script library used to consume Swagger defined APIs for both node.js and client applications.
  • Swagger Node: This is a very specific module designed for node.js applications only.
  • Swagger-Socket: This is another useful tool to be used with WebSockets. It is mainly used to invoke or expose Swagger defined APIs.
  • Swagger parser: This is a stand-alone parsing library to parse Swagger definitions from Java.

What is the role of JavaScript API in Swagger?

Swagger-tools is known to provide few APIs that can help in interacting with Swagger documents and also supplies metadata for specification, such as schema files or the location of documentation. Also, a majority of the center around what we need to solve here, i.e. validation.

  • composeModel – Such a function is responsible for the creation of a JSON schema file, either by name or by reference, for a model.
  • convert – Such a function is mainly used to convert a document from Swagger 1.2 to Swagger 2.0.
  • resolve – A resolve function accepts the a Swagger document and then returns a completely resolved document. A fully resolves document has all external and internal references replaced with resolved values.
  • validate – The validate function naturally validates Swagger documents.
  • validateModel – Th task of this function is to validate a model value in your Swagger document against its respective schema.

Command Line Interface

Swagger-tools is known to provide a command line interface, so that one can perform the APIs available against the Swagger documents. Some of the commands that can be used in swagger-tools CLI has been given below, with their definitions explained.

  • convert [APIdeclarations] – This is used for the conversion of Swagger 1.2 documents to Swagger 2.0 documents.
  • info - Its task is to print the Swagger specification information for a particular version.
  • validate [APIdeclarations] – This is used for the validation of Swagger documents.

The CLI commands given here can be run against files that are available locally or remotely. They can also be any format, such as JSON or YAML.

What is Connect middleware?

API and CLI provided by swagger-tools are clearly very important components. However, in the Connect middleware something is also very important and plays a very interesting role in the building of API tools using Swagger. Swagger-tools is known to ship with Connect middleware that allows one to describe the API contract in one place, and further allow the Node.js request/response cycle to use the information available in Swagger documents. Node.js needs this information to validate requests and responses, mock responses, and also request routing. The present middleware that is shipped with swagger-tools is defined below.

  • swaggerMetadata – This is used to attach relevant Swagger information to the relevant object when a request matches the API that is described in the Swagger document. It is to be noted that this is required by all middleware, except where mentioned.
  • swaggerRouter – This is a simply method used to request routing. When a Swagger route is requested, the relevant code is then executed.
  • swaggerSecurity – This allows one to carry out pre-routing of security checks, based on the information available in Swagger documents.
  • swaggerUI – This is for the deployment of swagger-ui along with an API, which allows the easy accessibility of the API’s documentation. This middleware does not require the implementation of swaggerMetadata.
  • swaggerValidator – This is to enable request validation based on the contract that is defined in the Swagger document. It is also used for optional response validation.

Swagger-tools enable the easy development of RESTful APIs using Node.js. In order to avoid rewriting of a lot of documentatyin that is already provided by Swagger tools project, it requested that you take good look into the specifics.

Now, we shall proceed with the ways and means to implement Swagger.

Implementing Swagger

Swagger Node library arrives with a nice editor meant for defining APIs and also an integrated web application for testing APIs. The first step, after a first API development process should be that of a mock mode in order to test the APIs. This is also done without the implementation of the controllers or APIs. Using the help of a verify command, you can make sure that the API definitions and project structures are right. There is also a wizard that can help in the creation of various projects for many different frameworks, such as Express and Connect. This also creates the base structure and configuration for upcoming new projects.

Here is a very easy five steps that can help you build your hello world sample. The sample defines that JSON is returned but returns only a JSON content type with string. So, that line has been changed.

Listing 1: Example to implement Swagger

function helloworld(req, res) {
  // variables that have been defined in Swagger document can be referenced by using req.swagger.params.{parameter_name}
  var name1 = || 'unknown';
  var hello1 = util.format('Hello!, %s!', name1);
  // this part sends back a JSON response which is basically a single string
  res.json({ message: hello});

Figure 1: Output sample

To start a Swagger project, one needs to invoke the ‘swagger project start’ command or the ‘node app.js’. The latter is needed if you wish to run the core Node application only. Following this, you can run the API and get the API definition of Swagger.

Now, if you wish to run the editor, you can invoke the command “swagger project edit”.

Figure 2: Response model


In this short tutorial, we have shown you how to get started with Swagger, which can be an interactive way to document APIs. There is also a little example that can help you as well. Documenting APIs are important and certainly has quite a few advantages, as has been already mentioned in the article. We hope this helps you in documenting APIs in a more friendly and easy to use manner.

Website: Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login