How to Implement Swagger API Server for Golang: Step by Step Guide

      Comments Off on How to Implement Swagger API Server for Golang: Step by Step Guide

Introduction

This tutorial will walk you through the setup of go swagger API documentation. This will help developers to create API documentation for Go APIs which will help other to easily understand and integrate with the Go API which you have written.

Step 1 : Download swagger for GO

Download swagger for GO by using following command,
# go get github.com/yvasiyarov/swagger

This will pull all necessary packages for Swagger UI and also this will create a swagger binary in your $GOPATH/bin directory.

 

 

Step 2 : Download dependencies to run swagger

There are two dependency packages we should download to run swagger-ui

// Zero downtime restarts for go servers (Drop in replacement for http.ListenAndServe)
# go get github.com/fvbock/endless
// log XI is a structured 12-factor app logger built for speed and happy development.
# go get -u github.com/mgutz/logxi/v1

Step 3 : Annotations needs to be added to generate swagger go file for swagger-ui

There are two ways we can generate doc.go file for swagger.

First one is using swagger generator command line tool and second way is where we can cre- ate doc.go file manually.

In first way we should use Declarative 2omments where we should add annotations in our API source code to generate the doc.go file.

Note: Instead of adding annotations in code we can directly create the required Doc.go file if you are familiar with GoLang and Json.

1, Annotations for General API info:

This general API info annotations should be added in the main file of our application and it should be above the package keyword. This are all optional, although using at least @APITi- tle and @APIDescription is highly recommended.

Actual format is below,

  // @APIDescription DESCRIPTION

2, Annotations for Sub API Definitions (One per Resource)

This should be added in the route file of the application this means the file which has the handler definition,

Actual format is below,

  // @SubApi DESCRIPTION [URI]

This Description will be displayed in the swagger-ui

3, Annotations for API Operations

The most important annotation comments for swagger UI generation are these comments that describe an operation (GET, PUT, POST, etc.). These comments are placed within your controller source code. One full set of these comments is used for each operation. They are placed just above the code that handles that operation.

Example for GET Request:

// @Title GetCpuUtil
// @Description get Cpu by ID
// @Accept json
// @Produce json
// @Param some_id path int true "Some ID"
// @Success 200 {object} string
// @Failure 400 {object} APIError "We need ID!!"
// @Failure 404 {object} APIError "Can not find ID"
// @Router /get-cpu/{some_id} [get]
func getCpu(c *Context) {
r := getContent()
c.Json(200, r)
}

@Title – It is kind of an “alias” or nickname for this API operation. @Description – A longer description for the operation.

@Accept – One of: json, xml, plain, or html. Should be equal to the “Accept” header of your API.

@Param – Defines a parameter that is accepted by this API operation. components of Param,

  • param_name – name of the parameter.
  • transport_type – defines how this parameter is passed to the operation. Can be one of path/query/form/header/body
  • ** data_type** – type of parameter
  • required – Whether or not the parameter is mandatory (true or false).
  • ** description** – parameter description. Must be quoted.

@Success/@Failure – Use these annotations to define the possible responses by the API operation. The format is as follows:

@Success http_response_code response_type response_data_type response_description

@Router – define route path, which should be used to call this API operation. It has the fol- lowing format: @Router request_path [request_method]

@Resource – Forces the resource identifier to be something other than the first segment of the route URI.

4, Struct Tags

type Actor struct {
Id *string `required:"true" json:"id"`
FirstName *string `json:"firstName,required" description:"Server Name"`
LastName *string `json:"lastName,required" description:"Server Name (sorted by)"`
HeadshotImage *string `json:"-"`
Filmography []Film `json:"filmography,omitempty"`
Contact *Contact `json:"contact,omitempty"`
}
  • If a required:”true” struct tag is found, then the field is marked as required, e.g. Id, above.
  • If required is found within a json struct tag, then the field is marked as required, e.g. FirstName, above.
  • If a description struct tag is found, then it provides the field’s description, e.g. FirstName, above.
  • If – is found within a json struct tag, then the field is ignored (not documented), e.g. HeadshotImage, above.

Step 4: Generate go swagger file

Once we added proper annotations to our source code we can proceed to generate the swagger file for swagger-ui.

To generate doc.go file we should use the following command,

// This will create a doc.go file into your output path given
# swagger -apiPackage="github.com/costcontrolcenter/lib/controllers/" -mainApiFile=github.com/costcontrolcenter/main.go -output=./ -format=go

End of this command we will have our doc.go file with us so now we are ready to run the swagger-ui

Step 5 : Run swagger UI to see the API Dashboard

once we generate the doc.go file we can run it using go command,
 

We should be in the swagger directory where our swagger-ui files are present, we should place our doc.go file here in swagger directory. Then build and run the application like bel- low,

# go build
# ls
doc.go swagger-test swagger-ui web.go
# ./swagger-test ==> Running swagger api

Step 6 : Check the Swagger in browser

Once we are done with the steps we can directly see our swagger UI in browser like http://127.0.0.1:8080,

Sample Doc.go File :

package main 
//This file is generated for cpu utilization api 

var resourceListingJson = `
 
   "apiVersion":"1.0.0",
   "swaggerVersion":"1.2",
   "basePath":"http://localhost:8080",
   "apis": 
       
         "path":"/v1/cpu",
         "description":"CpuUtilization-Utils"
      }
   ],
   "info": 
      "title":"CpuUtilization API",
      "description":"CpuUtilization API Documentation",
      "contact":"[email protected]",
      "termsOfServiceUrl":"http://localhost/terms-of-service",
      "license":"BSD",
      "licenseUrl":"http://localhost/licence"
   }
}
var apiDescriptionsJson = map[string]string{"v1/cpu":`
{  
   "apiVersion":"1.0.0",
   "swaggerVersion":"1.2",
   "basePath":"http://localhost:8081",
   "resourcePath":"/v1/cpu",
   "produces": 
      "application/json"
   ],
   "apis": 
       
         "path":"/v1/cpu",
         "description":"get cpu from server",
         "operations": 
             
               "httpMethod":"GET",
               "nickname":"cpuutils",
               "type":"string",
               "items": 

               },
               "summary":"Get Cpu from Server",
               "responseMessages": 
                   
                     "code":200,
                     "message":"",
                     "responseType":"object",
                     "responseModel":"string"
                  }
               ],
               "produces": 
                  "application/json"
               ]
            }
         ]
      }
   ]
}`,

}

Sharing is caring!

About Dinesh Sobitharaj C

An IT professional having multiple years of experience in IT Infrastructure planning, System integrations, Project implementation and delivery. Devops Enthusiast skilled with broad ranges of technology adoption. Well versed with Cloud Computing and Application Service Offerings such as SaaS/PaaS/IaaS. Expert in aligning business goals, mission and process to architect innovative solutions and strategies.