How to Document an Existing API Using Swagger

How to Document an Existing API Using Swagger

A few months ago, I jumped into an exciting project with my teammates at Shockoe. My expertise was needed for testing and debugging, which led me to begin working with the middleware API. In this particular case, the project presented new challenges, APIs that had already been set up by a client and the fact that this was an ongoing project, which meant that it was still changing and being updated regularly.

Adding features to the project required new resources and endpoints. Updating how error messages were handled required updating API responses and, after a certain point, enough changes had been made that the documentation had to be remade.

I came across two popular resources for documenting APIs: Swagger and RAML.

RAML takes a top-down approach to defining APIs, which means that you first define what your methods will be and then how they will work. By using a methodology that involves defining the system and providing the details later, this works well while developing an API since it goes alongside the developing mindset.

On the other hand, Swagger uses a bottom-up approach, defining each method one at a time. In my case, I decided to use Swagger because this methodology works better when documenting an already existing API. Swagger basically allows you to work through each API call and document as you go.

Swagger uses JSON objects to describe its API request and responses. For example, an API with a pets endpoint for a GET request could look like the example below, with a separate items object defined later in the document to increase readability.

{
  "/pets": {
    "get": {
      "description": "Returns all pets from the system that the user has access to",
      "produces": [
        "application/json"
      ],
      "responses": {
        "200": {
          "description": "A list of pets.",
          "schema": {
            "type": "array",
            "items": {
              "$ref": "#/definitions/pet"
            }
          }
        }
      }
    }
  }
}

Since I had already been using Postman to test each call, I had a quick way to go through each call, document the request and response, and move on to the next step.  Because the API only returned JSON the similarity between formatting for the response and the swagger response documentation led me to create a simple conversion program. This allowed me to easily input the response from an API call and output a properly formatted swagger documentation for it.

function convertToSwagger(item){
  var string = '';
  if(item === null){
    string += '{\n'+'"type": "string"\n'+'},';
  } else {
    switch(typeof item){
      case "string":
        string += '{\n'+'"type": "' + typeof item +'",';
        if(item.length > 150){
          item = item.substring(0,150);
        }
        if(item.includes('"')){
          string = string.slice(0,-1);
          string += '\n'+'},';
        } else {
          string += '\n';
          string += response ? '"example": "' : '"default": "'
          string += item + '"\n'+'},';
        }
        break;
      case "number":
        if(Number.isInteger(item)){
          string += '{\n'+'"type": "' + 'integer' +'",';
        } else {
          string += '{\n'+'"type": "' + 'number' +'",';
          string += '\n'+'"format":"float",';
        }
          string += '\n';
          string += response ? '"example": ' : '"default": '
          string += item + '\n'+'},';
        break;
      case "boolean":
        string += '{\n'+'"type": "' + 'boolean' +'"\n'+'},';
        break;
      case "object":
        if(Array.isArray(item)){
          string += '{\n'+'"type": "' + 'array' +'",';
          string += '\n'+'"items": ' + convertToSwagger(item[0]).slice(0,-2) + '\n'+'},';
        } else {
          string += '{\n'+'"type": "' + 'object' +'",';
          string += '\n'+'"properties": ' + '{\n' + createProperties(item) + '\n'+'}\n'+'},';
        }
        break;
      default:
        // do nothing
    }
  }
  return string+"\n";
}

At this point the process became simple, look up the API request, document the new path in Swagger (which can be made easier by copying an existing path and changing the different fields), make a request to get a sample response, put the response in the converter and copy it over to the swagger file. From here, I was able to quickly finish documenting the API and set up a process to easily keep it updated or document another finished API.

Documenting a project can seem daunting when you need to do it all at once, but it is still a very important part of the process. In the end, I found Swagger to be a great API document that was easy to use for my project needs. I was able to quickly pick it up and get started. Adding each method was simple to do after the first one and it helped give an overview of all the available methods while showing example requests and responses along the way. I hope this helps you when you find yourself documenting existing APIs, leave us a comment if you have any questions or insight on how to use Swagger.

Editor: Interested in learning how our developers debug applications? You can read more from our last week’s blog. For our blog on API Description Language for the Enterprise click here.

Want to stay connected on all things mobile?

Sign up for the Shockoe newsletter and we'll keep you updated with the latest blogs, podcasts, and events focused on emerging mobile trends.

Begin With the End in Mind

Begin With the End in Mind

“Begin with the end in mind” is the 2nd habit of Stephen Covey’s The 7 Habits of Highly Effective People. The driving rationale behind this habit is that if you envision what you want in the future, you can work and plan towards it. Utilizing this approach when managing Mobile App development projects is a central tenet to Shockoe’s project success.

We begin vision casting with our clients early and often. Project initiation is where the nature and scope of a project is determined. Although we become well versed in what you DO and what kind of systems and information you HAVE, what we really like to focus on is where do you want to GO and where do you want to BE. We help our clients learn to dream again.

Planning a project involves determining the time, cost, and resources needed to deliver a project successfully.  If you are clear on where you want to be, you can plan the project efficiently. Clarified purpose and common goals can then be communicated to the people involved. Clear goals, along with well planned tasks to align with those goals, help provide the proper motivation to tackle the project.

As project execution occurs, the coordination of the resources and deliverables against the planned activities will be closely monitored. A clear destination will allow you to accurately measure the steps you are undertaking. It will also allow the team to course correct quickly if they are not headed in the right direction.

It has been known to happen that (on occasion) the client’s vision of the future will change. Change is a normal and an expected part. Consistent, continuous communications will allow the team to understand the adjusted goals and assess any impacts. It will clarify the new version of the future and expectations can be set with regard to what will be required to now accomplish this revised vision.

With the end — the client vision and dream — in mind, Shockoe helps our clients plan and navigate into a future clearly driven by these goals. We always begin (and continue) with the end in mind.

[/vc_column_text][/vc_column][/vc_row]

Want to stay connected on all things mobile?

Sign up for the Shockoe newsletter and we'll keep you updated with the latest blogs, podcasts, and events focused on emerging mobile trends.