Generate Gin API Documentation with Swagger
Swagger is an API tool ecosystem built around the OpenAPI specification. It can be used for API design, documentation generation, interface testing, and maintenance.
In Go projects,
swaggo/swagandgin-swaggerare commonly used to automatically generate API documentation, making frontend and backend integration more efficient.
Environment Setup
| Technology | Version |
|---|---|
| Go | >= 1.20 |
| Gin | >= 1.9 |
| swaggo/swag | >= 1.8 |
| gin-swagger | Latest stable version |
Project structure
project
├── main.go
├── controller
│ └── user.go
├── model
│ └── response.go
└── docs
├── docs.go
├── swagger.json
└── swagger.yaml
Swagger and OpenAPI
OpenAPI is a specification for describing REST APIs.
Swagger is a tool ecosystem built around OpenAPI, including:
- Swagger UI
- Swagger Editor
- Swagger Codegen
The workflow in a Go project:
Go comments
↓
swag parsing
↓
OpenAPI documentation
↓
Swagger UI rendering
Install swag CLI
go install github.com/swaggo/swag/cmd/swag@latest
BashCheck installation:
swag --version
BashAdd Swagger Basic Information
main.go:
package main
// @title User Management System API Documentation
// @version 1.0
// @description User service API documentation
// @host localhost:8080
// @BasePath /api/v1
// @schemes http https
func main() {
}
GoJWT Authentication Configuration
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description Enter Bearer Token
GoApply authentication to an API:
// @Security BearerAuth
GoDefine Response Models
It is recommended to use explicit structs instead of interface{}:
package model
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
type UserResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data User `json:"data"`
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
GoAdd API Comments in Controller
package controller
import (
"github.com/gin-gonic/gin"
"project/model"
)
// GetUserInfo
// @Summary Get user information
// @Description Query user details by user ID
// @Tags User Module
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} model.UserResponse
// @Failure 400 {object} model.Response
// @Failure 500 {object} model.Response
// @Router /user/{id} [get]
func GetUserInfo(c *gin.Context) {
c.JSON(
200,
model.UserResponse{
Code: 200,
Msg: "success",
Data: model.User{
ID: 1,
Name: "Test User",
},
},
)
}
GoGenerate Swagger Documentation
Run:
swag init
BashGenerated files:
docs
├── docs.go
├── swagger.json
└── swagger.yaml
Note:
The
docsdirectory contains automatically generated files. It is not recommended to modify them manually.
Multi-Directory Projects
If the application entry point is located at:
cmd/server/main.go
Run:
swag init -g cmd/server/main.go
BashFor dependency parsing:
swag init --parseDependency --parseInternal
BashIntegrate gin-swagger
Install:
go get github.com/swaggo/gin-swagger
go get github.com/swaggo/files/v2
BashComplete main.go Example
package main
import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files/v2"
ginSwagger "github.com/swaggo/gin-swagger"
_ "project/docs"
)
func main() {
r := gin.Default()
r.GET(
"/swagger/*any",
ginSwagger.WrapHandler(swaggerFiles.Handler),
)
r.Run(":8080")
}
GoNote:
The import path
project/docsmust be replaced with the actual module name defined ingo.mod.
Access Swagger UI
Start the application:
go run main.go
BashOpen:
http://localhost:8080/swagger/index.html
Production Environment Considerations
In production environments, Swagger is usually disabled:
if gin.Mode() != gin.ReleaseMode {
r.GET(
"/swagger/*any",
ginSwagger.WrapHandler(
swaggerFiles.Handler,
),
)
}
GoCommon Issues
Swagger UI Shows No APIs:
Check:
swag init
BashConfirm:
import _ "project/docs"
GoRouter annotation:
// @Router /user/{id} [get]
GoDocumentation Does Not Update After API Changes:
Run again:
swag init
Bashswag init Cannot Find APIs:
Check:
- The path of
main.go - Whether the Controller package is scanned
- Whether the following command has been executed:
swag init --parseDependency --parseInternal
BashAutomatically Generate Swagger in CI/CD
Example:
- name: Generate Swagger
run: swag init
- name: Check docs
run: git diff --exit-code
YAMLPurpose:
Prevent API documentation from becoming inconsistent with code changes.
Summary
Go comments
↓
swag init
↓
swagger.json
↓
gin-swagger
↓
Swagger UI
Gin + Swagger provides a fast way to build standardized API documentation.
For enterprise projects, it is recommended to combine it with:
- JWT authentication
- API Versioning
- Request and response model design
- CI/CD automatic generation
- Documentation version management
Together, these practices form a complete API documentation management system.