Swagger is a specification and a suite of tools to help you model and build a RESTful API.

In this post, we'll install Swagger and then create the scaffolding for a Microservices API with a Swagger UI.

Prerequisites

  • Xcode Command Line Tools
  • Homebrew (the missing package manager for OSX)
  • Node.js

Note: This post will walk you through the steps required to install the Xcode Command Line Tools, Homebrew and Node.js.

Install Swagger

To install Swagger, enter the following command:

npm install -g swagger

Now, we can use the Swagger CLI to create the scaffolding for a new Microservices API project:

cd ~/opt/WebStorm/projects/
swagger project create qbuddy-api 

Swagger will prompt you to choose a RESTful API framework, we're going to use Express.js so use the arrow key to select it. Swagger will create the scafolding for a new Express project and then run npm install (for you) in order to install the required dependencies:

From the project directory we'll use the Swagger CLI to launch the newly scaffolded API, enter the following command:

swagger project start

Note: The server will restart if you make any changes to the project.

To test the API, run the following command in another Terminal session:

curl http://localhost:10010/Hello?name=World

And, you'll get back the response 'Hello, World'.

The Swagger Editor

Swagger also includes an editor so that you can model your API interactively. From the project directory, enter the following command:

swagger project edit

Swagger Tools

Swagger Tools includes Connect middleware for Swagger UI. To add swagger-tools to the project, enter the following command:

npm install swagger-tools --save

Now, we just need to add a couple of lines to the project's app.js:

var SwaggerUi = require('swagger-tools/middleware/swagger-ui');

and:

app.use(SwaggerUi(swaggerExpress.runner.swagger));

The project's updated app.js:

Now, when your server is running, this URL http://localhost:10010/docs will serve the project's Swagger UI:

And, this URL http://localhost:10010/api-docs will serve the Swagger document (api/swagger/swagger.yaml).

References: