How to get started with Swagger


Posted by Christian Weiß on January 23, 2018

Swagger

Swagger is the most widely used standard for specifying and documenting REST Services.

The real power of the Swagger standard comes from the ecosystem of powerful tools that surrounds it.

For example, there’s Swagger Editor for writing the Swagger spec, Swagger Codegen for automatically generating code based on your Swagger spec, and Swagger UI for turning your Swagger spec into beautiful documentation.

Installation

Swagger is supported in node.js through its own module, here is the link to the github project: The documentation is pretty straight-forward to help beginners understand and configure Swagger.

Once we open the command line we install the module (global).

npm install -g swagger

Now let’s create our project.

swagger project create hello_world

The prompt asks for the framework we want to use, choose express.

swagger

swagger

Let’s have a look at the project directory structure

├── api
├── config
├── node_modules
└── test

Each subfolder contains a README.md.

The app.js is the main file which runs the server.

There is already a controller called hello_world.js? Whenever you create a new project, the module adds an example route, a GET request to /hello which takes a name as parameter and greets the person. Let see Swagger in action and get insight on how it works.

What about taking a look at the example in action?

Swagger editor.

Swagger editor is an elegant browser-based editor which really simplifies our efforts to develop a web API. In particular, it provides:

swagger

The picture above shows you the UI of the Swagger editor. On the left you can see the yaml file, on the right the list of routes. By clicking on any root the UI shows detailed information like required parameters, the format of request and responses, more generally a description of the route.

Start the app by running

swagger project start

swagger

Whenever a file is modified, it automatically restarts the server.

Then, open a second shell and launch the editor with:

swagger project edit

The editor opens a new tab in your browser. On the right side of the page you should notice the example path for a GET request to /hello, so open the tab and, at the bottom, click on the button try this operation.

swagger

swagger

Test it

Enter a paramenter name: Go for it and test the route. Result:

swagger

swagger

reference: https://github.com/swagger-api