iChengHub
HomeBlogsToolsLinksAbout
ZH
Submit / Wish
iChengHub
ICP License: 2025085990-1
© 2026 iChengHub. All rights reserved.
© 2026 iChengHub. All rights reserved.
ICP License: 2025085990-1
//Generate Gin API Documentation with Swagger

Generate Gin API Documentation with Swagger

API Documentation2026-08-116

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/swag and gin-swagger are commonly used to automatically generate API documentation, making frontend and backend integration more efficient.

Environment Setup

TechnologyVersion
Go>= 1.20
Gin>= 1.9
swaggo/swag>= 1.8
gin-swaggerLatest 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
Bash

Check installation:

swag --version
Bash

Add 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() {

}
Go

JWT Authentication Configuration

// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
// @description Enter Bearer Token
Go

Apply authentication to an API:

// @Security BearerAuth
Go

Define 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"`
}
Go

Add 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",
            },
        },
    )
}
Go

Generate Swagger Documentation

Run:

swag init
Bash

Generated files:

docs
├── docs.go
├── swagger.json
└── swagger.yaml

Note:

The docs directory 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
Bash

For dependency parsing:

swag init --parseDependency --parseInternal
Bash

Integrate gin-swagger

Install:

go get github.com/swaggo/gin-swagger
go get github.com/swaggo/files/v2
Bash

Complete 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")
}
Go

Note:

The import path project/docs must be replaced with the actual module name defined in go.mod.

Access Swagger UI

Start the application:

go run main.go
Bash

Open:

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,
        ),
    )

}
Go

Common Issues

Swagger UI Shows No APIs:

Check:

swag init
Bash

Confirm:

import _ "project/docs"
Go

Router annotation:

// @Router /user/{id} [get]
Go

Documentation Does Not Update After API Changes:

Run again:

swag init
Bash

swag 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
Bash

Automatically Generate Swagger in CI/CD

Example:

- name: Generate Swagger
  run: swag init

- name: Check docs
  run: git diff --exit-code
YAML

Purpose:

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.

Last updated on·2026-08-11

←Back to ListWhat Can the select Statement Be Used For?→
Environment SetupProject structureInstall swag CLICheck installation:Add Swagger Basic InformationJWT Authentication ConfigurationDefine Response ModelsAdd API Comments in ControllerGenerate Swagger DocumentationRun:Generated files:Multi-Directory ProjectsIf the application entry point is located at:Run:For dependency parsing:Integrate gin-swaggerInstall:Complete `main.go` ExampleAccess Swagger UIStart the application:Open:Production Environment ConsiderationsIn production environments, Swagger is usually disabled:Common IssuesSwagger UI Shows No APIs:Documentation Does Not Update After API Changes:swag init Cannot Find APIs:Automatically Generate Swagger in CI/CDExample:Summary
Home
Blog