Swagger API Documentation β
Swagger is a powerful API documentation generation tool, Gin-Vue-Admin integrates Swagger to automatically generate and maintain API documentation. This guide will introduce how to install, configure and use Swagger.
π What is Swagger β
Swagger is an open source software framework for designing, building, documenting and using RESTful Web services. It provides:
- π Automatic API Documentation Generation: Automatically generate documentation from code comments
- π§ͺ Online Testing: Test APIs directly in the browser
- π Visual Interface: Clear API structure display
- π Real-time Updates: Documentation automatically syncs when code changes
π οΈ Install Swagger β
Method 1: Direct Installation (Recommended) β
If your network environment is good, you can install directly:
# Install the latest version of swag tool
go install github.com/swaggo/swag/cmd/swag@latestMethod 2: Install with Proxy β
If you encounter network issues, it's recommended to configure Go module proxy:
# Enable Go Modules
go env -w GO111MODULE=on
# Configure domestic proxy (choose one)
go env -w GOPROXY=https://goproxy.cn,direct
# or use
# go env -w GOPROXY=https://goproxy.io,direct
# Install swag tool
go install github.com/swaggo/swag/cmd/swag@latestVerify Installation β
After installation, verify that the swag tool is correctly installed:
# Check swag version
swag --version
# View help information
swag --helpπ Configure Swagger Comments β
1. Main Program Comments β
Add basic API information in the main.go file:
// @title Gin-Vue-Admin API
// @version 1.0
// @description This is a sample server for Gin-Vue-Admin.
// @termsOfService https://github.com/flipped-aurora/gin-vue-admin
// @contact.name API Support
// @contact.url https://github.com/flipped-aurora/gin-vue-admin/issues
// @contact.email support@gin-vue-admin.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8888
// @BasePath /
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name x-token
func main() {
// Application code
}2. API Interface Comments β
Add detailed comments for each API interface:
// CreateUser Create user
// @Tags User Management
// @Summary Create user
// @Description Create new user account
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.CreateUserReq true "User information"
// @Success 200 {object} response.Response{data=response.UserResponse} "Created successfully"
// @Failure 400 {object} response.Response "Request parameter error"
// @Failure 500 {object} response.Response "Internal server error"
// @Router /user [post]
func (u *UserApi) CreateUser(c *gin.Context) {
// Interface implementation code
}3. Data Model Comments β
Add comments for data structures:
// User User information
type User struct {
ID uint `json:"id" example:"1"` // User ID
Username string `json:"username" example:"admin"` // Username
Email string `json:"email" example:"admin@example.com"` // Email
Phone string `json:"phone" example:"13800138000"` // Phone number
Status int `json:"status" example:"1"` // Status: 1-enabled, 0-disabled
}π Generate API Documentation β
1. Generate Documentation β
Run in the project root directory (directory containing main.go):
# Generate Swagger documentation
swag init2. Generation Success β
After the command executes successfully, the following files will be generated in the project:
server/
βββ docs/
β βββ docs.go # Documentation data
β βββ swagger.json # JSON format documentation
β βββ swagger.yaml # YAML format documentation
βββ main.go3. Automated Generation β
You can also add go:generate directive in main.go to automate documentation generation:
//go:generate swag init
package mainThen use the go generate command:
go generateπ Access Swagger Documentation β
1. Start Service β
Ensure the backend service is running:
go run main.go2. Access Documentation β
Access Swagger UI in your browser:
Local Access: http://localhost:8888/swagger/index.html
3. Documentation Features β
Swagger UI provides the following features:
- π API List: View all available API interfaces
- π Interface Details: View detailed information such as parameters and responses for each interface
- π§ͺ Online Testing: Test API interfaces directly on the page
- π₯ Download Documentation: Download API documentation in JSON or YAML format
π― Usage Tips β
1. Interface Grouping β
Use @Tags comments to group interfaces:
// @Tags User Management
// @Tags Permission Management
// @Tags System Settings2. Parameter Validation β
Combine binding tags for parameter validation:
type CreateUserReq struct {
Username string `json:"username" binding:"required" example:"admin"` // Username (required)
Password string `json:"password" binding:"required,min=6" example:"123456"` // Password (required, minimum 6 characters)
Email string `json:"email" binding:"email" example:"admin@example.com"` // Email (email format)
}3. Response Examples β
Provide detailed response examples:
// @Success 200 {object} response.Response{data=[]model.User} "Retrieved successfully"
// @Success 200 {object} response.PageResult{list=[]model.User} "Paginated retrieval successful"4. Error Handling β
Define common error responses:
// @Failure 400 {object} response.Response "Request parameter error"
// @Failure 401 {object} response.Response "Unauthorized"
// @Failure 403 {object} response.Response "Insufficient permissions"
// @Failure 404 {object} response.Response "Resource not found"
// @Failure 500 {object} response.Response "Internal server error"π§ Advanced Configuration β
1. Custom Configuration β
Create .swaggo configuration file:
# .swaggo
dir: ./
general_info: main.go
output_dir: ./docs
parse_vendor: false
parse_dependency: false
parse_internal: false
generate_types: false2. Exclude Specific Files β
Use --exclude parameter to exclude files that don't need parsing:
swag init --exclude ./vendor3. Specify Output Directory β
swag init --output ./api-docsπ Related Resources β
Official Documentation β
Comment Standards β
Example Projects β
π Best Practices β
- Update Documentation Timely: Regenerate documentation after every API modification
- Detailed Comments: Provide clear descriptions and examples for each interface
- Unified Standards: Unify comment format and naming conventions within the team
- Version Management: Maintain corresponding documentation for different API versions
- Test Validation: Use Swagger UI to test interfaces to ensure documentation accuracy


