Add Swagger Docs to a Go API

Swagger allows developers to easily create api documentation which is defined using comments in the code and then generated as a yaml config file. In this post we’ll be using it alongside Go (golang).

Using tools like Swagger has many advantages, like allowing you to generate documentation automatically (saving you time) and that it keeps your code and documentation as close as possible (in distance terms). The idea being that if the docs are hard to update and far away, you just won’t.

Definitions are show like below, where we give the documentation a title:

1
// @title        My API documentation

1. Grab the packages you need

We use the http-swagger package, which provides us with some middleware for showing the docs in our app.

1
go get "github.com/swaggo/http-swagger"

Run the command above to install it into your project.

2. Install Swag (cmd swagger generator)

We’ll also need the “Swag” tool to read our comments and generate the swag definition file.

View On Github (with install instructions)  

3. View our example code

Put it all together and we have our code, like shown below. The code could be shown in more detail, as many projects will - but it does show us a working example.

The important bit is add adding _ "swaggerexample/docs" and making a new router endpoint for it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"

	// Super important: import the docs into project
	// we used "swaggerexample" as that was our project name, use your own.
	_ "swaggerexample/docs"

	// Import the swagger docs middleware
	httpSwagger "github.com/swaggo/http-swagger"
)

type HealthCheckResponse struct {
	Result string `json:"result" example:"ok"`
}

// @title        My API documentation
// @version      0.1
// @description  A collection of fun related api endpoints.
// termsOfService  http://swagger.io/terms/
// @x-logo       {"url": "https://example.com/img.png", "backgroundColor": "#000000", "altText": "example logo", "href": "https://example.com/img.png"}

// contact.name   API Support
// @contact.url   https://gophercoding.com
// contact.email  support@gophercoding.com

// @host                        api.gophercoding.com
// @securityDefinitions.apikey  ApiKeyAuth
// @in                          header
// @name                        Authorization

func main() {

	http.HandleFunc("/v1/health-check", HealthCheckHandler)
	http.HandleFunc("/docs/", httpSwagger.WrapHandler)
	http.HandleFunc("/", RootHandler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	log.Println("App started on http://localhost:" + port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		panic(err)
	}
}

func RootHandler(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, "/docs/", http.StatusTemporaryRedirect)
}

// HealthCheckHandler shows if the api is running
// @Summary      Health Check
// @Description  check api is running
// @Accept       json
// @Produce      json
// @Tags         Tools
// @Security     ApiKeyAuth
// @Success      200  {object}  HealthCheckResponse
// @Router       /v1/health-check [get]
func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
	var hc HealthCheckResponse
	hc.Result = "ok"
	json.NewEncoder(w).Encode(hc)
}

Example In Action

generate swagger api docs in golang