Tutorial

Document your Already Existing APIs with Swagger

Draft updated on Invalid Date
Default avatar

By Chris Ganga

Document your Already Existing APIs with Swagger

This tutorial is out of date and no longer maintained.

Introduction

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 existence. If you were wondering how to leverage Swagger for your already built and hosted API, brace yourself for a short but interesting 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 customize it as much as possible

Setup

Clone the Swagger UI repo and install the dependencies.

  1. # Clone the repo
  2. git clone https://github.com/swagger-api/swagger-ui.git
  3. # cd into the folder
  4. cd swagger-ui
  5. # Install dependencies
  6. npm install
  7. # install gulp globally
  8. npm install -g gulp
  9. # Build Swagger
  10. 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.

  1. # install httpster
  2. npm install -g httpster
  3. # serve the dist folder
  4. httpster -d dist

Open http://localhost:3333 to see the default Swagger UI display:

Default Swagger Configuration

Customizing Swagger

If you are good at CSS, you can do quite some customization for Swagger. I’ll do two quick customizations just to show this.

The default Swagger header background color is green. Since we are documenting the Open GitHub API, it would be nice to change it to black.

Look for the header style in the screen.less file

src/main/less/screen.less
#header {
    background-color: #89bf04;
    padding: 9px 14px 19px 14px;
    height: 23px;
    min-width: 775px;
  }

And simply change the color to black.

src/main/less/screen.less
#header {
    background-color: black;
    padding: 9px 14px 19px 14px;
    height: 23px;
    min-width: 775px;
  }

Next, we’ll change the title and the logo to use the GitHub logo. I did a quick Google search for a GitHub logo and added the URL directly to the src attribute of its img tag.

src/main/html/index.html
<!DOCTYPE html>
<html>
<head>
<!-- Markup commented out for brevity-->
    <title>GITHUB API</title>
<!-- Markup commented out for brevity -->
</head>
<body class="swagger-section">
     <div id='header'>
          <div class="swagger-ui-wrap">
            <a id="logo" href="http://swagger.io">
                <!-- We change the Logo displayed here in the src property -->
                <img class="logo__img" alt="swagger" height="30" width="30" src="https://github.githubassets.com/images/modules/logos_page/GitHub-Logo.png" />
                <span class="logo__title">Github API</span></a>
                <!-- Markup Commented out for brevity-->
          </div>
        </div>
</body>
</html>

Configuring our Swagger API file

Before we look at the results of the customization, let’s quickly create our configuration file. Create a new file called github.json in src/main/ directory.

Note: This file can either be a .json file or a .yaml file. It’s what Swagger reads to interpret your API. YAML file has a different syntax, however.

src/main/github.json
{
  "swagger": "2.0",
  "info": {
    "description": "This is a sample documentation for the open GitHub API. The API is located at https://api.github.com/",
    "version": "0.0.1",
    "title": "GitHub API",
    "contact": {
      "email": "john.doe@example.com"
    },
    "license": {
      "name": "MIT",
      "url": "https://github.com/swagger-api/swagger-ui/blob/master/LICENSE"
    }
  },
  "host": "api.github.com",
  "basePath": "/",
  "produces": ["application/json"],
  "schemes": [
    "https"
  ]
}

Note: The key things here are the host and schemes properties. They should show where your API is hosted.

Finally, let’s change the loaded configuration file from Swagger’s default to our GitHub JSON.

src/main/index.html
<!DOCTYPE html>
<html>
<head>
    <!-- Markup commented out for brevity-->
    <script type="text/javascript">
        $(function () {
          var url = window.location.search.match(/url=([^&]+)/);
          if (url && url.length > 1) {
            url = decodeURIComponent(url[1]);
          } else {
            // Use our custom configuration file
            url = '/github.json';
          }
        // JS code commented out for brevity
        });
    </script>
</head>
<!-- Markup commented out for brevity -->
</html>

Notice the line url = '/github.json' in the else block. That will load our Github JSON Swagger config file.

Build swagger and run httpster.

  1. npm run build
  2. httpster -d dist

Open locahost:3333

GitHub API Swagger

Documenting the Routes

We’ll document two routes:

  1. GET / - Get information about the GitHub API
  2. GET /users - Get a list of GitHub users
  3. GET /users/:username - Get a specific GitHub user when a username is provided

GET /

Let’s edit the github.json file.

src/main/github.json
{
  ....,
  "schemes": ["https"],
  "paths": {
    "/": {
      "get": {
        "tags": ["info"],
        "description": "Get information about the Github API",
        "responses": {
          "200": {
            "description": "successfully got info",
            "schema": {
              "type": "object",
              "properties": {
                "current_user_url": {
                  "type": "string"
                },
                "authorizations_url": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    }
  }
}

I won’t go much into the details of the path properties, as Sam had covered them already here. You could also read more about the spec here.

But notice my response schema is in-line, I haven’t referenced it anywhere, and I have an example object. We can do a build and open the UI with httpster.

Swagger GET /

When you click on try it out, the API will be called, and you will see the results below the button.

GET /users

This path returns about 30 users from the GitHub API. We’ll quickly add its configuration to the config file.

Assuming your httpster server is still running, we can edit the github.json file directly without a rebuild.

dist/github.json
{
    ...,
    "paths": {
        ...,
        "/users": {
          "get": {
            "tags": ["Users"],
            "description": "Get list of users from github",
            "responses": {
                  "200": {
                    "description": "Successfully got users",
                    "schema": {
                          "type": "array",
                          "items": [{}]
                    }
                  }
            }
          }
        }
    }
}

I’ve left the items property empty, but ideally, you could fill in an array of objects based on Github’s response, or your API’s response.

Refreshing the browser should give this.

GET /users GitHub

Once again, you can click on the try it out button, and it should return a response from the API.

GET /users/:username

Our final route to document is getting a user by the username. Let’s add this to the github.json file.

dist/github.json
{
    ...,
    "paths": {
        ...,
        "/users/{username}": {
            "get": {
                "tags": [
                    "Users"
                ],
                "description": "Get a github user by passing in their username",
                "parameters": [
                    {
                        "name": "username",
                        "in": "path",
                        "description": "The github username of the user",
                        "required": true,
                        "type": "string"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "Successfully got github user",
                        "schema": {
                            "type": "object",
                            "properties": {
                                "login": {
                                    "type": "string"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

This time around we have a parameter, username, and we’ve included it in our JSON properties.

Refreshing the page should display

GET /users/{username} swagger

Put in a username you know about, like scotch, and click on try it now. You should see the details of the Github user below the button.

Conclusion

We’ve seen how to document an already existing API. If you look closely, all it entails is editing a config file that is either JSON or YAML.

Swagger UI is also easily customizable, which means you can tune it to your liking and even theme your API documentation based on a predefined scheme, or preference.

What’s left now is to just study the Specifications for the config file and you are good to go.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Chris Ganga

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel