Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

swag

> 编程语言
Open source

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

13.0K stars0 likes1 views
WebsiteGitHub

About

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

swag

English ∙ 简体中文 ∙ Português Swag converts Go annotations to Swagger Documentation 2.0. We've created a variety of plugins for popular Go web frameworks. This allows you to quickly integrate with an existing Go project (using Swagger UI).

Contents

  • Getting started
  • Supported Web Frameworks
  • How to use it with Gin
  • The swag formatter
  • Implementation Status
  • Declarative Comments Format
    • General API Info
    • API Operation
    • Security
  • Examples
    • Descriptions over multiple lines
    • User defined structure with an array type
    • Function scoped struct declaration
    • Model composition in response
      • Add request headers
    • Add response headers
    • Use multiple path params
    • Example value of struct
    • SchemaExample of body
    • Description of struct
    • Use swaggertype tag to supported custom type
    • Use global overrides to support a custom type
    • Use swaggerignore tag to exclude a field
    • Add extension info to struct field
    • Rename model to display
    • How to use security annotations
    • Add a description for enum items
    • Generate only specific docs file types
    • How to use Go generic types
  • About the Project

Getting started

  1. Add comments to your API source code, See Declarative Comments Format.

  2. Install swag by using:

bash
go install github.com/swaggo/swag/cmd/swag@latest

To build from source you need Go (1.19 or newer).

Alternatively you can run the docker image:

bash
docker run --rm -v $(pwd):/code ghcr.io/swaggo/swag:latest

Or download a pre-compiled binary from the release page.

  1. Run swag init in the project's root folder which contains the main.go file. This will parse your comments and generate the required files (docs folder and docs/docs.go).
bash
swag init

Make sure to import the generated docs/docs.go so that your specific configuration gets init'ed. If your General API annotations do not live in main.go, you can let swag know with -g flag.

go
import _ "example-module-name/docs"
bash
swag init -g http/api.go
  1. (optional) Use swag fmt format the SWAG comment. (Please upgrade to the latest version)
bash
swag fmt

swag cli

…
bash
swag fmt -h
NAME:
   swag fmt - format swag comments

USAGE:
   swag fmt [command options] [arguments...]

OPTIONS:
   --dir value, -d value          Directories you want to parse,comma separated and general-info file must be in the first one (default: "./")
   --exclude value                Exclude directories and files when searching, comma separated
   --generalInfo value, -g value  Go file path in which 'swagger general API Info' is written (default: "main.go")
   --help, -h                     show help (default: false)

Supported Web Frameworks

  • gin
  • echo
  • buffalo
  • net/http
  • gorilla/mux
  • go-chi/chi
  • flamingo
  • fiber
  • atreugo
  • hertz

How to use it with Gin

Find the example source code here.

Finish the steps in Getting started

  1. After using swag init to generate Swagger 2.0 docs, import the following packages:
go
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
  1. Add General API annotations in main.go code:
…

Additionally some general API info can be set dynamically. The generated code package docs exports SwaggerInfo variable which we can use to set the title, description, version, host and base path programmatically. Example using Gin:

…
  1. Add API Operation annotations in controller code
…
bash
swag init
  1. Run your app, and browse to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:

The swag formatter

The Swag Comments can be automatically formatted, just like 'go fmt'. Find the result of formatting here.

Usage:

bash
swag fmt

Exclude folder:

bash
swag fmt -d ./ --exclude ./internal

When using swag fmt, you need to ensure that you have a doc comment for the function to ensure correct formatting. This is due to swag fmt indenting swag comments with tabs, which is only allowed after a standard doc comment.

For example, use

go
// ListAccounts lists all existing accounts
//
//  @Summary      List accounts
//  @Description  get accounts
//  @Tags         accounts
//  @Accept       json
//  @Produce      json
//  @Param        q    query     string  false  "name search by q"  Format(email)
//  @Success      200  {array}   model.Account
//  @Failure      400  {object}  httputil.HTTPError
//  @Failure      404  {object}  httputil.HTTPError
//  @Failure      500  {object}  httputil.HTTPError
//  @Router       /accounts [get]
func (c *Controller) ListAccounts(ctx *gin.Context) {

Implementation Status

Swagger 2.0 document

  • Basic Structure
  • API Host and Base Path
  • Paths and Operations
  • Describing Parameters
  • Describing Request Body
  • Describing Responses
  • MIME Types
  • Authentication
    • Basic Authentication
    • API Keys
  • Adding Examples
  • File Upload
  • Enums
  • Grouping Operations With Tags
  • Swagger Extensions

Declarative Comments Format

General API Info

Example celler/main.go

annotation description example
title Required. The title of the application. // @title Swagger Example API
version Required. Provides the version of the application API. // @version 1.0
description A short description of the application. // @description This is a sample server celler server.
tag.name Name of a tag. // @tag.name This is the name of the tag
tag.description Description of the tag // @tag.description Cool Description
tag.docs.url Url of the external Documentation of the tag // @tag.docs.url https://example.com
tag.docs.description Description of the external Documentation of the tag // @tag.docs.description Best example documentation
termsOfService The Terms of Service for the API. // @termsOfService http://swagger.io/terms/
contact.name The contact information for the exposed API. // @contact.name API Support
contact.url The URL pointing to the contact information. MUST be in the format of a URL. // @contact.url http://www.swagger.io/support
contact.email The email address of the contact person/organization. MUST be in the format of an email address. // @contact.email [email protected]
license.name Required. The license name used for the API. // @license.name Apache 2.0
license.url A URL to the license used for the API. MUST be in the format of a URL. // @license.url http://www.apache.org/licenses/LICENSE-2.0.html
host The host (name or ip) serving the API. // @host localhost:8080
BasePath The base path on which the API is served. // @BasePath /api/v1
accept A list of MIME types the APIs can consume. Note that Accept only affects operations with a request body, such as POST, PUT and PATCH. Value MUST be as described under Mime Types. // @accept json
produce A list of MIME types the APIs can produce. Value MUST be as described under Mime Types. // @produce json
query.collection.format The default collection(array) param format in query,enums:csv,multi,pipes,tsv,ssv. If not set, csv is the default. // @query.collection.format multi
schemes The transfer protocol for the operation that separated by spaces. // @schemes http https
externalDocs.description Description of the external document. // @externalDocs.description OpenAPI
externalDocs.url URL of the external document. // @externalDocs.url https://swagger.io/resources/open-api/
x-name The extension key, must be start by x- and take only json value // @x-example-key {"key": "value"}

Using markdown descriptions

When a short string in your documentation is insufficient, or you need images, code examples and things like that you may want to use markdown descriptions. In order to use markdown descriptions use the following annotations.

annotation description example
title Required. The title of the application. // @title Swagger Example API
version Required. Provides the version of the application API. // @version 1.0
description.markdown A short description of the application. Parsed from the api.md file. This is an alternative to @description // @description.markdown No value needed, this parses the description from api.md
tag.name Name of a tag. // @tag.name This is the name of the tag
tag.description.markdown Description of the tag this is an alternative to tag.description. The description will be read from a file named like tagname.md // @tag.description.markdown
tag.x-name The extension key, must be start by x- and take only string value // @x-example-key value

API Operation

Example celler/controller

annotation description

Issues· 475 open

View all issuesOpen on GitHub
  • #2218

    Why not support openapi 3.x

    Updated Sep 24, 2026
  • #2222

    swag internal repository Unregister / Clear methods

    Updated Sep 22, 2026
  • #2142

    [v2] Empty object body schema generated when using @Accept

    Updated Sep 14, 2026
  • #2215

    [Go 1.27] Support generic methods (methods declaring their own type parameters)

    Updated Aug 26, 2026
  • #2216

    `@Tags` with empty values generates empty-string tags in Swagger output

    Updated Aug 25, 2026
  • #1949

    [v2]: Support `examples` keywords

    Updated Aug 11, 2026
  • #2197

    v2: every @Param body request body wrapped in a spurious 2-branch oneOf with a $ref sibling

    Updated Aug 5, 2026
  • #2207

    v2 --v3.1: panic (nil pointer dereference) on query object fields of named types

    Updated Jul 28, 2026
  • #1497

    Documentation sorted by Tags

    Updated Jul 15, 2026
  • #2198

    v2: no guard against duplicate operationId when one handler is documented on multiple @Router lines

    Updated Jul 14, 2026

> Tags

Goannotationsgolangopenapiswagger

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 28, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言