Top Related Projects
Swagger 2.0 implementation for go
Generate Go client and server boilerplate from OpenAPI 3 specifications
OpenAPI 3.0 (and Swagger v2) implementation for Go (parsing, converting, validation, and more)
The OpenAPI Specification Repository
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
📘 OpenAPI/Swagger-generated API Reference Documentation
Quick Overview
Swaggo/swag is an open-source tool that automatically generates Swagger 2.0 documentation for Go APIs. It analyzes Go source code and comments to produce OpenAPI Specification (OAS) files, making it easier for developers to document their APIs and generate interactive API documentation.
Pros
- Automates the process of creating Swagger documentation, saving time and reducing manual errors
- Supports various Go web frameworks, including Gin, Echo, Buffalo, and net/http
- Allows customization of generated documentation through special comments and annotations
- Integrates well with existing Go projects and CI/CD pipelines
Cons
- Limited to Swagger 2.0 specification, not supporting the newer OpenAPI 3.0
- Requires specific comment formatting, which may be seen as intrusive by some developers
- May not capture all API details accurately, especially for complex or dynamically generated endpoints
- Learning curve for proper usage and customization of annotations
Code Examples
- Basic API endpoint documentation:
// @Summary Get user information
// @Description Retrieve user details by ID
// @Tags users
// @Accept json
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
// Implementation
}
- Defining custom types for Swagger documentation:
// User represents user information
// @Description User account details
type User struct {
ID int `json:"id" example:"1"`
Username string `json:"username" example:"johndoe"`
Email string `json:"email" example:"john@example.com"`
CreatedAt string `json:"created_at" example:"2023-04-01T12:00:00Z"`
}
- Adding security definitions:
// @SecurityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @Security ApiKeyAuth
// @Summary Create a new user
// @Description Register a new user account
// @Tags users
// @Accept json
// @Produce json
// @Param user body User true "User information"
// @Success 201 {object} User
// @Router /users [post]
func CreateUser(c *gin.Context) {
// Implementation
}
Getting Started
-
Install swag:
go install github.com/swaggo/swag/cmd/swag@latest
-
Add Swagger annotations to your API handlers and types.
-
Generate Swagger documentation:
swag init
-
Import and initialize Swagger in your main.go:
import ( _ "yourproject/docs" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" ) func main() { // ... your Gin setup r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // ... start your server }
-
Run your application and access Swagger UI at
/swagger/index.html
.
Competitor Comparisons
Swagger 2.0 implementation for go
Pros of go-swagger
- More comprehensive toolset with CLI and runtime components
- Supports a wider range of Swagger/OpenAPI specifications
- Better suited for large, complex API projects
Cons of go-swagger
- Steeper learning curve and more complex setup
- Requires more configuration and boilerplate code
- May be overkill for smaller projects or simple APIs
Code Comparison
go-swagger example:
// swagger:operation GET /pets/{id} pets getPet
// ---
// summary: Find pet by ID
// description: Returns a single pet
// parameters:
// - name: id
// in: path
// description: ID of pet to return
// required: true
// type: integer
// format: int64
// responses:
// "200":
// description: successful operation
// schema:
// $ref: "#/definitions/Pet"
swag example:
// @Summary Find pet by ID
// @Description Returns a single pet
// @ID get-pet-by-id
// @Produce json
// @Param id path int true "ID of pet to return"
// @Success 200 {object} Pet
// @Router /pets/{id} [get]
Both tools generate Swagger/OpenAPI documentation, but go-swagger offers more features and flexibility at the cost of complexity, while swag provides a simpler, annotation-based approach that's easier to integrate into existing Go projects.
Generate Go client and server boilerplate from OpenAPI 3 specifications
Pros of oapi-codegen
- Generates server and client code from OpenAPI 3.0 specifications
- Supports multiple programming languages (Go, TypeScript, Python)
- Offers more flexibility in generated code structure
Cons of oapi-codegen
- Steeper learning curve for newcomers to OpenAPI
- May require more manual configuration for complex APIs
- Less integrated with existing Go frameworks compared to swag
Code Comparison
swag example:
// @Summary Get user by ID
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
// Implementation
}
oapi-codegen example:
paths:
/users/{id}:
get:
summary: Get user by ID
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
Both tools aim to simplify API development, but they approach it differently. swag focuses on generating Swagger documentation from Go code annotations, while oapi-codegen generates code from OpenAPI specifications. The choice between them depends on your project's needs and your team's familiarity with OpenAPI standards.
OpenAPI 3.0 (and Swagger v2) implementation for Go (parsing, converting, validation, and more)
Pros of kin-openapi
- More comprehensive OpenAPI toolset, supporting both v2 and v3 specifications
- Provides a robust OpenAPI validator and parser
- Offers more flexibility for working with OpenAPI definitions programmatically
Cons of kin-openapi
- Steeper learning curve due to its more extensive feature set
- Less focused on automatic API documentation generation from code comments
- May require more manual configuration for complex use cases
Code Comparison
swag:
// @Summary Get user by ID
// @Description Get user information by user ID
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
// Implementation
}
kin-openapi:
var spec = &openapi3.T{
Info: &openapi3.Info{
Title: "User API",
Version: "1.0.0",
},
Paths: openapi3.Paths{
"/users/{id}": &openapi3.PathItem{
Get: &openapi3.Operation{
Summary: "Get user by ID",
Description: "Get user information by user ID",
Parameters: openapi3.Parameters{
{
Name: "id",
In: openapi3.ParameterInPath,
Required: true,
Schema: openapi3.NewIntegerSchema(),
},
},
Responses: openapi3.Responses{
"200": &openapi3.ResponseRef{
Value: &openapi3.Response{
Description: "Successful response",
Content: openapi3.Content{
"application/json": &openapi3.MediaType{
Schema: &openapi3.SchemaRef{
Ref: "#/components/schemas/User",
},
},
},
},
},
},
},
},
},
}
The OpenAPI Specification Repository
Pros of OpenAPI-Specification
- Industry-standard specification for describing RESTful APIs
- Language-agnostic, allowing for broader adoption and tooling support
- Extensive ecosystem of tools and libraries for various programming languages
Cons of OpenAPI-Specification
- Requires manual writing and maintenance of API specifications
- Steeper learning curve for developers new to the OpenAPI format
- May require additional tooling to generate documentation from code
Code Comparison
OpenAPI-Specification (YAML):
openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: List users
swag (Go):
// @Summary List users
// @Description Get a list of users
// @Produce json
// @Success 200 {array} User
// @Router /users [get]
func ListUsers(w http.ResponseWriter, r *http.Request) {
// Implementation
}
OpenAPI-Specification provides a standardized, language-agnostic approach to API documentation, while swag offers a more code-centric solution specifically for Go projects. OpenAPI-Specification has broader industry adoption and tooling support, but requires manual specification writing. swag simplifies the process by generating documentation from code comments, but is limited to Go applications.
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Pros of openapi-generator
- Supports multiple programming languages and frameworks
- Generates client SDKs, server stubs, and documentation
- Highly customizable with templates and configuration options
Cons of openapi-generator
- Steeper learning curve due to its extensive features
- May generate more boilerplate code than necessary for simple projects
- Requires manual maintenance of OpenAPI specifications
Code comparison
swag:
// @Summary Get user by ID
// @Description Get user information by user ID
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
// Implementation
}
openapi-generator:
paths:
/users/{id}:
get:
summary: Get user by ID
description: Get user information by user ID
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
'200':
description: Successful response
content:
application/json:
schema:
$ref: '#/components/schemas/User'
Summary
swag is more Go-centric and integrates directly with code annotations, making it easier for Go developers to maintain API documentation alongside their code. openapi-generator offers broader language support and more extensive code generation capabilities but requires separate specification maintenance. Choose swag for Go-specific projects with simpler API needs, and openapi-generator for multi-language support or more complex API ecosystems.
📘 OpenAPI/Swagger-generated API Reference Documentation
Pros of Redoc
- Provides a more visually appealing and interactive API documentation interface
- Supports multiple themes and customization options for better branding
- Offers a standalone version that can be easily embedded in any web page
Cons of Redoc
- Requires a pre-generated OpenAPI/Swagger specification file
- May have a steeper learning curve for customization compared to Swag
- Limited to documentation generation, unlike Swag which also offers code generation
Code Comparison
Redoc (HTML embedding):
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
<redoc spec-url="https://api.example.com/openapi.json"></redoc>
Swag (Go code annotation):
// @Summary Get user by ID
// @Description Get user information by user ID
// @Produce json
// @Param id path int true "User ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
While Redoc focuses on rendering API documentation from existing OpenAPI specifications, Swag generates OpenAPI specifications from Go code annotations. Redoc excels in creating visually appealing documentation, whereas Swag streamlines the process of keeping API documentation in sync with the codebase.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
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
- Examples
- Descriptions over multiple lines
- User defined structure with an array type
- Function scoped struct declaration
- Model composition in response
- 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
-
Add comments to your API source code, See Declarative Comments Format.
-
Install swag by using:
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:
docker run --rm -v $(pwd):/code ghcr.io/swaggo/swag:latest
Or download a pre-compiled binary from the release page.
- Run
swag init
in the project's root folder which contains themain.go
file. This will parse your comments and generate the required files (docs
folder anddocs/docs.go
).
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.
import _ "example-module-name/docs"
swag init -g http/api.go
- (optional) Use
swag fmt
format the SWAG comment. (Please upgrade to the latest version)
swag fmt
swag cli
swag init -h
NAME:
swag init - Create docs.go
USAGE:
swag init [command options] [arguments...]
OPTIONS:
--quiet, -q Make the logger quiet. (default: false)
--generalInfo value, -g value Go file path in which 'swagger general API Info' is written (default: "main.go")
--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
--propertyStrategy value, -p value Property Naming Strategy like snakecase,camelcase,pascalcase (default: "camelcase")
--output value, -o value Output directory for all the generated files(swagger.json, swagger.yaml and docs.go) (default: "./docs")
--outputTypes value, --ot value Output types of generated files (docs.go, swagger.json, swagger.yaml) like go,json,yaml (default: "go,json,yaml")
--parseVendor Parse go files in 'vendor' folder, disabled by default (default: false)
--parseDependency, --pd Parse go files inside dependency folder, disabled by default (default: false)
--parseDependencyLevel, --pdl Enhancement of '--parseDependency', parse go files inside dependency folder, 0 disabled, 1 only parse models, 2 only parse operations, 3 parse all (default: 0)
--markdownFiles value, --md value Parse folder containing markdown files to use as description, disabled by default
--codeExampleFiles value, --cef value Parse folder containing code example files to use for the x-codeSamples extension, disabled by default
--parseInternal Parse go files in internal packages, disabled by default (default: false)
--generatedTime Generate timestamp at the top of docs.go, disabled by default (default: false)
--parseDepth value Dependency parse depth (default: 100)
--requiredByDefault Set validation required for all fields by default (default: false)
--instanceName value This parameter can be used to name different swagger document instances. It is optional.
--overridesFile value File to read global type overrides from. (default: ".swaggo")
--parseGoList Parse dependency via 'go list' (default: true)
--tags value, -t value A comma-separated list of tags to filter the APIs for which the documentation is generated.Special case if the tag is prefixed with the '!' character then the APIs with that tag will be excluded
--templateDelims value, --td value Provide custom delimiters for Go template generation. The format is leftDelim,rightDelim. For example: "[[,]]"
--collectionFormat value, --cf value Set default collection format (default: "csv")
--state value Initial state for the state machine (default: ""), @HostState in root file, @State in other files
--parseFuncBody Parse API info within body of functions in go files, disabled by default (default: false)
--help, -h show help (default: false)
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
How to use it with Gin
Find the example source code here.
Finish the steps in Getting started
- After using
swag init
to generate Swagger 2.0 docs, import the following packages:
import "github.com/swaggo/gin-swagger" // gin-swagger middleware
import "github.com/swaggo/files" // swagger embed files
- Add General API annotations in
main.go
code:
// @title Swagger Example API
// @version 1.0
// @description This is a sample server celler server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.basic BasicAuth
// @externalDocs.description OpenAPI
// @externalDocs.url https://swagger.io/resources/open-api/
func main() {
r := gin.Default()
c := controller.NewController()
v1 := r.Group("/api/v1")
{
accounts := v1.Group("/accounts")
{
accounts.GET(":id", c.ShowAccount)
accounts.GET("", c.ListAccounts)
accounts.POST("", c.AddAccount)
accounts.DELETE(":id", c.DeleteAccount)
accounts.PATCH(":id", c.UpdateAccount)
accounts.POST(":id/images", c.UploadAccountImage)
}
//...
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run(":8080")
}
//...
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:
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/files"
"github.com/swaggo/gin-swagger"
"./docs" // docs is generated by Swag CLI, you have to import it.
)
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
func main() {
// programmatically set swagger info
docs.SwaggerInfo.Title = "Swagger Example API"
docs.SwaggerInfo.Description = "This is a sample server Petstore server."
docs.SwaggerInfo.Version = "1.0"
docs.SwaggerInfo.Host = "petstore.swagger.io"
docs.SwaggerInfo.BasePath = "/v2"
docs.SwaggerInfo.Schemes = []string{"http", "https"}
r := gin.New()
// use ginSwagger middleware to serve the API docs
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.Run()
}
- Add API Operation annotations in
controller
code
package controller
import (
"fmt"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/swaggo/swag/example/celler/httputil"
"github.com/swaggo/swag/example/celler/model"
)
// ShowAccount godoc
// @Summary Show an account
// @Description get string by ID
// @Tags accounts
// @Accept json
// @Produce json
// @Param id path int true "Account ID"
// @Success 200 {object} model.Account
// @Failure 400 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Router /accounts/{id} [get]
func (c *Controller) ShowAccount(ctx *gin.Context) {
id := ctx.Param("id")
aid, err := strconv.Atoi(id)
if err != nil {
httputil.NewError(ctx, http.StatusBadRequest, err)
return
}
account, err := model.AccountOne(aid)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, account)
}
// ListAccounts godoc
// @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) {
q := ctx.Request.URL.Query().Get("q")
accounts, err := model.AccountsAll(q)
if err != nil {
httputil.NewError(ctx, http.StatusNotFound, err)
return
}
ctx.JSON(http.StatusOK, accounts)
}
//...
swag init
- 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:
swag fmt
Exclude folderï¼
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
// 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
- 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 support@swagger.io |
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 |
---|---|
description | A verbose explanation of the operation behavior. |
description.markdown | A short description of the application. The description will be read from a file. E.g. @description.markdown details will load details.md |
id | A unique string used to identify the operation. Must be unique among all API operations. |
tags | A list of tags to each API operation that separated by commas. |
summary | A short summary of what the operation does. |
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. |
produce | A list of MIME types the APIs can produce. Value MUST be as described under Mime Types. |
param | Parameters that separated by spaces. param name ,param type ,data type ,is mandatory? ,comment attribute(optional) |
security | Security to each API operation. |
success | Success response that separated by spaces. return code or default ,{param type} ,data type ,comment |
failure | Failure response that separated by spaces. return code or default ,{param type} ,data type ,comment |
response | As same as success and failure |
header | Header in response that separated by spaces. return code ,{param type} ,data type ,comment |
router | Path definition that separated by spaces. path ,[httpMethod] |
deprecatedrouter | As same as router, but deprecated. |
x-name | The extension key, must be start by x- and take only json value. |
x-codeSample | Optional Markdown usage. take file as parameter. This will then search for a file named like the summary in the given folder. |
deprecated | Mark endpoint as deprecated. |
Mime Types
swag
accepts all MIME Types which are in the correct format, that is, match */*
.
Besides that, swag
also accepts aliases for some MIME Types as follows:
Alias | MIME Type |
---|---|
json | application/json |
xml | text/xml |
plain | text/plain |
html | text/html |
mpfd | multipart/form-data |
x-www-form-urlencoded | application/x-www-form-urlencoded |
json-api | application/vnd.api+json |
json-stream | application/x-json-stream |
octet-stream | application/octet-stream |
png | image/png |
jpeg | image/jpeg |
gif | image/gif |
event-stream | text/event-stream |
Param Type
- query
- path
- header
- body
- formData
Data Type
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- file (param data type when uploading)
- user defined struct
Security
annotation | description | parameters | example |
---|---|---|---|
securitydefinitions.basic | Basic auth. | // @securityDefinitions.basic BasicAuth | |
securitydefinitions.apikey | API key auth. | in, name, description | // @securityDefinitions.apikey ApiKeyAuth |
securitydefinitions.oauth2.application | OAuth2 application auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.application OAuth2Application |
securitydefinitions.oauth2.implicit | OAuth2 implicit auth. | authorizationUrl, scope, description | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
securitydefinitions.oauth2.password | OAuth2 password auth. | tokenUrl, scope, description | // @securitydefinitions.oauth2.password OAuth2Password |
securitydefinitions.oauth2.accessCode | OAuth2 access code auth. | tokenUrl, authorizationUrl, scope, description | // @securitydefinitions.oauth2.accessCode OAuth2AccessCode |
parameters annotation | example |
---|---|
in | // @in header |
name | // @name Authorization |
tokenUrl | // @tokenUrl https://example.com/oauth/token |
authorizationurl | // @authorizationurl https://example.com/oauth/authorize |
scope.hoge | // @scope.write Grants write access |
description | // @description OAuth protects our entity endpoints |
Attribute
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
// @Param default query string false "string default" default(A)
// @Param example query string false "string example" example(string)
// @Param collection query []string false "string collection" collectionFormat(multi)
// @Param extensions query []string false "string collection" extensions(x-example=test,x-nullable)
It also works for the struct fields:
type Foo struct {
Bar string `minLength:"4" maxLength:"16" example:"random string"`
Baz int `minimum:"10" maximum:"20" default:"15"`
Qux []string `enums:"foo,bar,baz"`
}
Available
Field Name | Type | Description |
---|---|---|
validate | string | Determines the validation for the parameter. Possible values are: required,optional . |
default | * | Declares the value of the parameter that the server will use if none is provided, for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request. (Note: "default" has no meaning for required parameters.) See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2. Unlike JSON Schema this value MUST conform to the defined type for this parameter. |
maximum | number | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.2. |
minimum | number | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.3. |
multipleOf | number | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. |
maxLength | integer | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.1. |
minLength | integer | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.2. |
enums | [*] | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1. |
format | string | The extending format for the previously mentioned type . See Data Type Formats for further details. |
collectionFormat | string | Determines the format of the array if type array is used. Possible values are:
csv . |
example | * | Declares the example for the parameter value |
extensions | string | Add extension to parameters. |
Future
Field Name | Type | Description |
---|---|---|
pattern | string | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. |
maxItems | integer | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.2. |
minItems | integer | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.3. |
uniqueItems | boolean | See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.3.4. |
Examples
Descriptions over multiple lines
You can add descriptions spanning multiple lines in either the general api description or routes definitions like so:
// @description This is the first line
// @description This is the second line
// @description And so forth.
User defined structure with an array type
// @Success 200 {array} model.Account <-- This is a user defined struct.
package model
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
}
Function scoped struct declaration
You can declare your request response structs inside a function body.
You must have to follow the naming convention <package-name>.<function-name>.<struct-name>
.
package main
// @Param request body main.MyHandler.request true "query params"
// @Success 200 {object} main.MyHandler.response
// @Router /test [post]
func MyHandler() {
type request struct {
RequestField string
}
type response struct {
ResponseField string
}
}
Model composition in response
// JSONResult's data field will be overridden by the specific type proto.Order
@success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
type JSONResult struct {
Code int `json:"code" `
Message string `json:"message"`
Data interface{} `json:"data"`
}
type Order struct { //in `proto` package
Id uint `json:"id"`
Data interface{} `json:"data"`
}
- also support array of objects and primitive types as nested response
@success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
@success 200 {object} jsonresult.JSONResult{data=string} "desc"
@success 200 {object} jsonresult.JSONResult{data=[]string} "desc"
- overriding multiple fields. field will be added if not exists
@success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order,data4=[]proto.Order} "desc"
- overriding deep-level fields
type DeepObject struct { //in `proto` package
...
}
@success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject},data2=[]proto.Order{data=[]proto.DeepObject}} "desc"
Add request headers
// @Param X-MyHeader header string true "MyHeader must be set for valid response"
// @Param X-API-VERSION header string true "API version eg.: 1.0"
Add response headers
// @Success 200 {string} string "ok"
// @failure 400 {string} string "error"
// @response default {string} string "other error"
// @Header 200 {string} Location "/entity/1"
// @Header 200,400,default {string} Token "token"
// @Header all {string} Token2 "token2"
Use multiple path params
/// ...
// @Param group_id path int true "Group ID"
// @Param account_id path int true "Account ID"
// ...
// @Router /examples/groups/{group_id}/accounts/{account_id} [get]
Add multiple paths
/// ...
// @Param group_id path int true "Group ID"
// @Param user_id path int true "User ID"
// ...
// @Router /examples/groups/{group_id}/user/{user_id}/address [put]
// @Router /examples/user/{user_id}/address [put]
Example value of struct
type Account struct {
ID int `json:"id" example:"1"`
Name string `json:"name" example:"account name"`
PhotoUrls []string `json:"photo_urls" example:"http://test/image/1.jpg,http://test/image/2.jpg"`
}
SchemaExample of body
// @Param email body string true "message/rfc822" SchemaExample(Subject: Testmail\r\n\r\nBody Message\r\n)
Description of struct
// Account model info
// @Description User account information
// @Description with user id and username
type Account struct {
// ID this is userid
ID int `json:"id"`
Name string `json:"name"` // This is Name
}
#708 The parser handles only struct comments starting with @Description
attribute.
But it writes all struct field comments as is.
So, generated swagger doc as follows:
"Account": {
"type":"object",
"description": "User account information with user id and username"
"properties": {
"id": {
"type": "integer",
"description": "ID this is userid"
},
"name": {
"type":"string",
"description": "This is Name"
}
}
}
Use swaggertype tag to supported custom type
type TimestampTime struct {
time.Time
}
///implement encoding.JSON.Marshaler interface
func (t *TimestampTime) MarshalJSON() ([]byte, error) {
bin := make([]byte, 16)
bin = strconv.AppendInt(bin[:0], t.Time.Unix(), 10)
return bin, nil
}
func (t *TimestampTime) UnmarshalJSON(bin []byte) error {
v, err := strconv.ParseInt(string(bin), 10, 64)
if err != nil {
return err
}
t.Time = time.Unix(v, 0)
return nil
}
///
type Account struct {
// Override primitive type by simply specifying it via `swaggertype` tag
ID sql.NullInt64 `json:"id" swaggertype:"integer"`
// Override struct type to a primitive type 'integer' by specifying it via `swaggertype` tag
RegisterTime TimestampTime `json:"register_time" swaggertype:"primitive,integer"`
// Array types can be overridden using "array,<prim_type>" format
Coeffs []big.Float `json:"coeffs" swaggertype:"array,number"`
}
type CerticateKeyPair struct {
Crt []byte `json:"crt" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
Key []byte `json:"key" swaggertype:"string" format:"base64" example:"U3dhZ2dlciByb2Nrcw=="`
}
generated swagger doc as follows:
"api.MyBinding": {
"type":"object",
"properties":{
"crt":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
},
"key":{
"type":"string",
"format":"base64",
"example":"U3dhZ2dlciByb2Nrcw=="
}
}
}
Use global overrides to support a custom type
If you are using generated files, the swaggertype
or swaggerignore
tags may not be possible.
By passing a mapping to swag with --overridesFile
you can tell swag to use one type in place of another wherever it appears. By default, if a .swaggo
file is present in the current directory it will be used.
Go code:
type MyStruct struct {
ID sql.NullInt64 `json:"id"`
Name sql.NullString `json:"name"`
}
.swaggo
:
// Replace all NullInt64 with int
replace database/sql.NullInt64 int
// Don't include any fields of type database/sql.NullString in the swagger docs
skip database/sql.NullString
Possible directives are comments (beginning with //
), replace path/to/a.type path/to/b.type
, and skip path/to/a.type
.
(Note that the full paths to any named types must be provided to prevent problems when multiple packages define a type with the same name)
Rendered:
"types.MyStruct": {
"id": "integer"
}
Use swaggerignore tag to exclude a field
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Ignored int `swaggerignore:"true"`
}
Add extension info to struct field
type Account struct {
ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` // extensions fields must start with "x-"
}
generate swagger doc as follows:
"Account": {
"type": "object",
"properties": {
"id": {
"type": "string",
"x-nullable": true,
"x-abc": "def",
"x-omitempty": false
}
}
}
Rename model to display
type Resp struct {
Code int
}//@name Response
How to use security annotations
General API info.
// @securityDefinitions.basic BasicAuth
// @securitydefinitions.oauth2.application OAuth2Application
// @tokenUrl https://example.com/oauth/token
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
Each API operation.
// @Security ApiKeyAuth
Make it OR condition
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
Make it AND condition
// @Security ApiKeyAuth && firebase
// @Security OAuth2Application[write, admin] && APIKeyAuth
Add a description for enum items
type Example struct {
// Sort order:
// * asc - Ascending, from A to Z.
// * desc - Descending, from Z to A.
Order string `enums:"asc,desc"`
}
Generate only specific docs file types
By default swag
command generates Swagger specification in three different files/file types:
- docs.go
- swagger.json
- swagger.yaml
If you would like to limit a set of file types which should be generated you can use --outputTypes
(short -ot
) flag. Default value is go,json,yaml
- output types separated with comma. To limit output only to go
and yaml
files, you would write go,yaml
. With complete command that would be swag init --outputTypes go,yaml
.
How to use Generics
// @Success 200 {object} web.GenericNestedResponse[types.Post]
// @Success 204 {object} web.GenericNestedResponse[types.Post, Types.AnotherOne]
// @Success 201 {object} web.GenericNestedResponse[web.GenericInnerType[types.Post]]
func GetPosts(w http.ResponseWriter, r *http.Request) {
_ = web.GenericNestedResponse[types.Post]{}
}
See this file for more details and other examples.
Change the default Go Template action delimiters
If your swagger annotations or struct fields contain "{{" or "}}", the template generation will most likely fail, as these are the default delimiters for go templates.
To make the generation work properly, you can change the default delimiters with -td
. For example:
swag init -g http/api.go -td "[[,]]"
The new delimiter is a string with the format "<left delimiter>
,<right delimiter>
".
Parse Internal and Dependency Packages
If the struct is defined in a dependency package, use --parseDependency
.
If the struct is defined in your main project, use --parseInternal
.
if you want to include both internal and from dependencies use both flags
swag init --parseDependency --parseInternal
About the Project
This project was inspired by yvasiyarov/swagger but we simplified the usage and added support a variety of web frameworks. Gopher image source is tenntenn/gopher-stickers. It has licenses creative commons licensing.
Contributors
This project exists thanks to all the people who contribute. [Contribute].
Backers
Thank you to all our backers! ð [Become a backer]
Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
License
Top Related Projects
Swagger 2.0 implementation for go
Generate Go client and server boilerplate from OpenAPI 3 specifications
OpenAPI 3.0 (and Swagger v2) implementation for Go (parsing, converting, validation, and more)
The OpenAPI Specification Repository
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
📘 OpenAPI/Swagger-generated API Reference Documentation
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot