Skip to main content

Automatic API Documentation Swagger in Golang #GolangDev




pixabay.com
pixabay.com

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, its slickly same as documentation but less description, it's allow 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 framework 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

Popular posts from this blog

Membuat Game Sederhana Dengan JavaScript

Assalamualaikum Wr Wb Javascript adalah Bahasa pemrograman yang di pakai di web, javascript kebanyakan di gunakan untuk kebutuhan membuat animasi, tapi tidak semata-mata javascript hanya bisa di pakai untuk membuat animasi, untuk kebutuhan operasi web pun sering di gunakan. Javascript bersifat Client Side, maksudnya adalah javascript berjalan di PC pengguna atau pengakses web, dan scriptnya pun bisa di lihat oleh user, berbeda dengan PHP yang scriptnya tidak bisa di lihat oleh user. Selain di buat animasi, Javascript juga bisa di pakai untuk membuat aplikasi web, salah satunya adalah GAME, pada kesempatan kali ini saya akan memberikan tutorial bagaimana membuat GAME sederhana dengan Javascript, memanfaatkan event-event dalam javascript. berikut screenshoot dari game sederhana : Alur Game : 1. Klik button Start. 2. gambar monster akan bergerak cepat. 3. klik sebanyak mungkin gambar monsternya. 4. Apabila skor lebih dari 20, maka anda akan menang. untuk s

Laravel Tips : Membuat Model, Migration dan Controller dengan Sekali Jalan

  php artisan adalah generator laravel yang berfungsi untuk membuat file kodingan dengan mudah, seperti membuat controller, model, seeder, migration dan masih banyak lagi. artisan hanya bisa di lakukan di dalam lingkungan console, seperti cmd dan terminal. berikut akan saya tunjukan cara membuat controller, model, migration menggunakan php artisan. # membuat controller ketikkan perintah di bawah ini php artisan make:controller BlogController # membuat model ketikkan perintah di bawah ini php artisan make:model Blog # membuat migration ketikkan perintah di bawah ini php artisan make:migration blog # membuat seeder ketikkan perintah di bawah ini php artisan make:seeder BlogSeeder # membuat migration, controller, dan model sekaligus ketikkan perintah di bawah ini php artisan make:model -crm Blog perintah di atas akan mengenerate controller dengan nama BlogController dengan keadaan Resource method tertulis, model

Mengerti Brontok dan Cara Membersihkannya

relate search :  cara menghapus virus brontok, membersihkan virus brontok, mengembalikan data yang di hapus virus brontok. Virus brontok adalah virus buatan orang indonesia, yang bertujuan untuk mendeklarasikan aspirasi rakyat, sebenernya aspirasi pribadi si pembuat hanya saja bersifat umum, sifat dari virus ini sebenernya sama saja dengan virus-virus yang lain, hanya saja virus ini tidak merusak apapun yang ada di perangkat kita. Sebenernya karna sifat-sifat tersebut,   brontok ini lebih cocok kalau di sebut worm . Virus ini akan memunculkan pesan-pesan sosial yang tujuannya mengkritik kesalahan yang ada di negeri ini, seperti berikut : -           Hentikan KKN (Korupsi Kolusi Nepotisme) -           Hentikan Seks Bebas -           Dll Baca Juga : Langkah-Langkah Membersihkan Virus Shortcut Versi 3.x Tapi dari beberapa efek dari adanya brontok ini, yang paling menyebalkan adalah komputer atau laptop kita akan tiba-tiba shutdown atau restart sendiri, kalau kita t