Effortlessly Generate Beautiful Go API Docs with Swagger and Swag
This guide walks you through the challenges of manual API documentation, introduces Swagger as a powerful solution, and provides a step‑by‑step tutorial for integrating Swagger with Go projects using the Swag tool, Gin framework, and custom UI enhancements.
Note: The content applies to Go projects; other languages have not been verified.
Preface
During many project developments we encounter the problem of how to quickly and simply write API documentation for our interfaces.
Developers usually write API information in markdown files and host them somewhere, such as a Git repository or a public documentation system like ShowDoc or a wiki.
Writing documentation manually is cumbersome: you must write code, add comments, and also write documentation; you must specify many parameters, which can lead to errors; when the API changes, the documentation must be updated or users will be confused.
Is there a way to automatically generate a beautiful API document from code and comments?
Many community solutions exist, such as phpDoc, ApiDoc, and Swagger, with Swagger being the most popular.
Swagger Overview
Swagger is a simple yet powerful API design expression tool that currently supports almost all mainstream programming languages.
Swagger forms a complete ecosystem, illustrated below:
In a typical project with front‑end and back‑end separation, waiting for all code and comments before generating documentation slows progress. Instead, you can write documentation first with an editor, then use a code‑generation tool to produce the code.
For detailed Swagger information, refer to the official site: https://swagger.io
Using Swagger in Go Projects
While code‑generation tools can produce fixed‑style code that may not match your project’s architecture, Go’s good interface design lets you define interfaces, annotate them, and generate documentation for front‑end consumption before implementing business logic.
This article focuses on documentation generators.
Go Swagger Documentation Tools
swag: https://github.com/swaggo/swag
It supports common web frameworks:
gin
echo
buffalo
net/http
Example with Gin Framework
1. Install swag go get -u github.com/swaggo/swag/cmd/swag 2. Add general API comments in
main.go // @title UCenter Docs
// @version 0.1
// @description 用户中心项目文档
// @host ucenter.gtarcade.com
// @license.name Apache 2.0
// @BasePath /api
func main() {
startServer()
}3. Add API operation comments in controller functions
// GetAccountUsers 获取帐号下用户列表
// @Summary 获取帐号下用户列表
// @Description 获取帐号下用户列表
// @Accept json
// @Produce json
// @Param obj body api.Account true "用户帐号"
// @Success 200 {array} api.UserInfo "返回用户信息"
// @failure 400 {object} api.Error "错误信息"
// @Router /account/users [post]
func GetUsersInfo(c *gin.Context) {
service.GetUsersInfo()
}
// Account 内部帐号
type Account struct {
Account string `json:"account" binding:"required"`
}
// UserInfo 用户信息
type UserInfo struct {
Account string `json:"account"`
Nickname string `json:"nickname"`
Sex int `json:"sex"`
FirstName string `json:"first_name"`
}4. Add Swagger route
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
"./docs" // generated by swag
)
func initRouters() {
router := gin.New()
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
router.GET("/api/getUserInfo", api.GetUserInfo)
}5. Generate documentation $ swag init 6. Run the program and open http://localhost:8080/swagger/index.html If everything works, you’ll see a page like this:
This page is rendered by SwaggerUI, allowing you to view request URLs, parameters, model attributes, and even test the API online.
For detailed Swagger syntax and Swag usage, refer to the official repository: https://github.com/swaggo/swag.
Optimizing Documentation Display
Swagger UI is great, but its drawer‑style detail pages can be inconvenient for project documentation management. We created a new UI to centralize documentation.
Swagger documentation is described by a swagger.json file in JSON format.
When you run swag init, this JSON file is generated for each project.
Thus we only need to obtain each project’s JSON file URL, parse its content according to Swagger rules, and render it on the page.
Add a yaml configuration file to manage the source of each project’s documentation:
ucenter:
title: UCenter Api Docs
ns: ucenter
url: http://xxxxx1.gtarcade.com/swagger/doc.json
osauth:
title: OsAuth Api Docs
ns: osauth
url: http://xxxxx2.gtarcade.com/swagger/doc.json
storage:
title: Storage API Docs
ns: storage
url: http://xxxxx3.gtarcade.com/swagger/doc.jsonWhen requesting different routes, the system fetches the corresponding JSON file, parses Swagger parameters, and renders them to HTML.
The final effect looks like this:
Packages Used
https://github.com/swaggo/swag (Swagger documentation generator)
https://github.com/swaggo/gin-swagger (Swagger support for Gin)
https://github.com/flosch/pongo2 (Go template engine for parsing JSON and rendering pages)
https://github.com/sentsin/layui (Frontend UI framework)
(End of article)
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
YooTech Youzu Tech Team
Official tech account of Youzu Network, sharing insights and discussions on technology, research, and product.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
