In this article, I'll explain how to generate an API blueprint instantly using SwagGo in Golang.
API blueprint is a document that contains a bunch of API endpoints, it's slightly the same as documentation but with less description. It allows another programmer to read and see all the available endpoint and try it out with sandbox feature.
Swagger is one of the most used API blueprints right now, it's available in free but limited usage. if you wanna use the free credit, you need to understand YAML notation, you can read the example notation in Swagger official documentation. But again, it's really hard and takes an expensive time to arranges all the notation to achieve a good API blueprint.
Fortunately, there are tools in Golang that allow us to generate the YAML notation and automatically generate the blueprint page with only using markup notation, and it's FREE unlimited for self-host, insane right?
SwagGo tools are available here, the documentation is very clear, but in my experience, I need a lot of time to totally understand how to use it. here I wanna explain what I got and what I have been implemented.
These tools support familiar frameworks, such as echo and gin, but in this tutorial, I would like to use default standard Go web server.
Prerequisites
You can also use Linux, but if you are using windows, it might be has a different result and experience.
first thing first, you need to install SwagGo Generator.
$ go get -u github.com/swaggo/swag/cmd/swag
after installation success, check the availability by using bellow command
$ swag --version
swag version v1.6.7
then, move to your project, in my example, I will make a simple project that contains several files. in order to use these tools, you need files at least main.go
run command to initiate SwagGo files in your root project.
$ swag init
2021/02/02 22:52:14 Generate swagger docs....
2021/02/02 22:52:14 Generate general API Info, search dir:./
2021/02/02 22:52:14 create docs.go at docs/docs.go
2021/02/02 22:52:14 create swagger.json at docs/swagger.json
2021/02/02 22:52:14 create swagger.yaml at docs/swagger.yaml
right now, your project will contain newly added swagger files and folders.
$ ls -al
total 8
drwxr-xr-x 4 jauharibill staff 128 Feb 2 22:52 .
drwxr-xr-x 56 jauharibill staff 1792 Feb 2 22:47 ..
drwxr-xr-x 5 jauharibill staff 160 Feb 2 22:52 docs
-rw-r--r-- 1 jauharibill staff 80 Feb 2 22:52 main.go
in docs folder contains these files.
$ cd docs
$ ls -al
total 24
drwxr-xr-x 5 jauharibill staff 160 Feb 2 22:52 .
drwxr-xr-x 4 jauharibill staff 128 Feb 2 22:52 ..
-rw-r--r-- 1 jauharibill staff 1397 Feb 2 22:52 docs.go
-rw-r--r-- 1 jauharibill staff 84 Feb 2 22:52 swagger.json
-rw-r--r-- 1 jauharibill staff 45 Feb 2 22:52 swagger.yaml
there are docs.go that used to renew and generate the following swagger.json and YAML file. you don't need to modify these file, just ignore it and they will changes when you run the swag command. I will explain it below.
after knowing directory structure, then we will write minimalis code like below. in main.go write these code :
package main
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi"
_ "GOLANG-API-BLUEPRINT/docs"
httpSwagger "github.com/swaggo/http-swagger"
)
// main
func main() {
http.ListenAndServe(":8080", router())
}
// router
func router() http.Handler {
r := chi.NewRouter()
r.Get("/", HelloWorld)
return r
}
// default response
type response struct {
Message string `json:"message"`
Status bool `json:"status"`
}
// HelloWorld Controller
func HelloWorld(w http.ResponseWriter, r *http.Request) {
var response response
response.Message = "Success Retrieve Data"
response.Status = true
payload, _ := json.Marshal(response)
w.Write(payload)
}
above code is a simple webserver build with golang, it will represent REST API. first thing first, we will try to put identity for our REST API. Put markup comment that already define by SwagGo above main method.
// @title EXAMPLE REST API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://localhost:8080/terms/
// @contact.name Bill Tanthowi Jauhari
// @contact.url http://localhost:8080/support
// @contact.email bill@localhost
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /
// @query.collection.format multi
func main() {
http.ListenAndServe(":8080", router())
}
Run command swag to generate markup docs into yaml and json Swagger.
$ swag init -g main.go
2021/02/03 20:58:36 Generate swagger docs....
2021/02/03 20:58:36 Generate general API Info, search dir:./
2021/02/03 20:58:36 create docs.go at docs/docs.go
2021/02/03 20:58:36 create swagger.json at docs/swagger.json
2021/02/03 20:58:36 create swagger.yaml at docs/swagger.yaml
above command will update json and yaml files in docs folder. if you want to see the result, you can put that generated notation into swagger hub. you can also self host your blueprint, simply add swagger router.
// router
func router() http.Handler {
r := chi.NewRouter()
r.Get("/", HelloWorld)
// swagger self host router
r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("http://localhost:8080/swagger/doc.json"),
))
return r
}
after adding swagger router, you can see the blueprint at http://localhost:8080/swagger/index.html
cool, the first markup swagger that we write before already published. but the thing is there is no endpoint available yet. to put endpoint blueprint, you can put more markup into targeted method, for example :
// GET Hello World Message
// @tags Message
// @Summary show message hello world
// @Description show message hello world
// @Accept json
// @Produce json
// @Success 200 {object} response
// @Failure 400 {object} response
// @Failure 500 {object} response
// @Router / [get]
func HelloWorld(w http.ResponseWriter, r *http.Request) {
var response response
response.Message = "Success Retrieve Data"
response.Status = true
payload, _ := json.Marshal(response)
w.Write(payload)
}
Run swag command again, then you can see the result.
finally the endpoint blueprint available, inside the endpoint there is a description and a lot of REST API information.
also the best part is, you can try the endpoint directly from that page, klik "try it out" button and execute the endpoint.
Finally, we already make a REST API blueprint using SwagGo. you can modify and improve all the markup by learning deeper from the documentation here. Reach me out at my social media, Good luck!
Also published on: https://www.bill.web.id/2020/09/automatic-api-documentation-swagger-in.html