Document your Already Existing APIs with Swagger

We recently covered speeding your restful api development with Swagger. The article is really clear on how to use swagger, and I would suggest you read it first before going through this.

The article however starts with an API from scratch. But this may not be the case for some of us. I, for instance had an API that was already in existense. If you were wondering how to leverage Swagger for your already built and hosted API, brace yourself for a short but intersting quick tip read.

Swagger UI

Swagger UI is the beautiful view we see when we document our api with swagger. The readme of the project defines it this way:

Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API. http://swagger.io

We can use Swagger UI in one of two ways:

  1. AS IS : This involves just copying the content of the dist folder and editing the source of the configuration file. (either .yaml or .json)
  2. Build : This involves cloning the Swagger UI repo, making a few tweaks based on your preferences and doing your own build. It will generate a dist folder, which you can then continue to use editing a config file.

We’ll take the latter approach to document a small API. Since this is a quick tip article, we’ll document three routes for the Open Github API, trying to cusomize it as much as possible

Setup

Clone the Swagger UI repo and install the dependecies.

# Clone the repo $ git clone https://github.com/swagger-api/swagger-ui.git # cd into the folder $ cd swagger-ui # Install dependecies $ npm install # install gulp globally $ npm install -g gulp # Build Swagger $ gulp build

While there is already a dist directory, build deletes everything and recreates the dist directory every time you run it.

Open the dist/index.html file in your browser, or better yet, serve the dist folder with httpster.

# install httpster $ npm install -g httpster # serve the dist folder $ httpster -d dist

Open http://localhost:3333 to see the default swagger ui display

Customizing Swagger


Originally published at www.laravelfeed.com.