README
¶
swag
Automatically generate RESTful API documentation with Swagger 2.0 for Go.
gopher image source is tenntenn/gopher-stickers. It has licenses creative commons licensing.
Content
- Getting started
- Go web frameworks
- Supported Web Frameworks
- How to use it with
gin
? - Implementation Status
- swag cli
- General API Info
- Security
- API Operation
- TIPS
- About the Project
Summary
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).
Examples
Getting started
-
Add comments to your API source code, See Declarative Comments Format.
-
Download swag by using:
$ go get -u github.com/swaggo/swag/cmd/swag
- 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
- In order to serve these files, you can utilize one of our supported plugins. For go's core library, check out net/http.
- Make sure to import the generated
docs/docs.go
so that your specific configuration getsinit
'ed. - If your General API annotation do not live in
main.go
, you can let swag know with-g
.
swag init -g http/api.go
Supported Web Frameworks
How to use it with gin
?
Find the example source code here.
- 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/gin-swagger/swaggerFiles" // 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
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @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
// @securitydefinitions.oauth2.implicit OAuth2Implicit
// @authorizationurl https://example.com/oauth/authorize
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
// @securitydefinitions.oauth2.password OAuth2Password
// @tokenUrl https://example.com/oauth/token
// @scope.read Grants read access
// @scope.write Grants write access
// @scope.admin Grants read and write access to administrative information
// @securitydefinitions.oauth2.accessCode OAuth2AccessCode
// @tokenUrl https://example.com/oauth/token
// @authorizationurl https://example.com/oauth/authorize
// @scope.admin Grants read and write access to administrative information
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")
}
//...
- 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 a account
// @Description get string by ID
// @ID get-string-by-int
// @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
// @Accept json
// @Produce json
// @Param q query string false "name search by q"
// @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
4.Run your app, and browse to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:
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
swag cli
$ swag init -h
NAME:
swag init - Create docs.go
USAGE:
swag init [command options] [arguments...]
OPTIONS:
--generalInfo value, -g value Go file path in which 'swagger general API Info' is written (default: "main.go")
--dir value, -d value Directory you want to parse (default: "./")
--swagger value, -s value Output the swagger conf for json and yaml (default: "./docs/swagger")
--propertyStrategy value, -p value Property Naming Strategy like snakecase,camelcase,pascalcase (default: "camelcase")
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. |
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 |
Security
annotation | description | parameters | example |
---|---|---|---|
securitydefinitions.basic | Basic auth. | // @securityDefinitions.basic BasicAuth | |
securitydefinitions.apikey | API key auth. | in, name | // @securityDefinitions.apikey ApiKeyAuth |
securitydefinitions.oauth2.application | OAuth2 application auth. | tokenUrl, scope | // @securitydefinitions.oauth2.application OAuth2Application |
securitydefinitions.oauth2.implicit | OAuth2 implicit auth. | authorizationUrl, scope | // @securitydefinitions.oauth2.implicit OAuth2Implicit |
securitydefinitions.oauth2.password | OAuth2 password auth. | tokenUrl, scope | // @securitydefinitions.oauth2.password OAuth2Password |
securitydefinitions.oauth2.accessCode | OAuth2 access code auth. | tokenUrl, authorizationUrl, scope | // @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 |
API Operation
Example
celler/controller
annotation | description |
---|---|
description | A verbose explanation of the operation behavior. |
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. 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 ,{param type} ,data type ,comment |
failure | Failure response that separated by spaces. return code ,{param type} ,data type ,comment |
router | Path definition that separated by spaces. path ,[httpMethod] |
Mime Types
Mime Type | annotation |
---|---|
application/json | application/json, json |
text/xml | text/xml, xml |
text/plain | text/plain, plain |
html | text/html, html |
multipart/form-data | multipart/form-data, mpfd |
application/x-www-form-urlencoded | application/x-www-form-urlencoded, x-www-form-urlencoded |
application/vnd.api+json | application/vnd.api+json, json-api |
application/x-json-stream | application/x-json-stream, json-stream |
application/octet-stream | application/octet-stream, octet-stream |
image/png | image/png, png |
image/jpeg | image/jpeg, jpeg |
image/gif | image/gif, gif |
Security
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 AND condition
// @Security ApiKeyAuth
// @Security OAuth2Application[write, admin]
Param Type
- object (struct)
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- array
Data Type
- string (string)
- integer (int, uint, uint32, uint64)
- number (float32)
- boolean (bool)
- user defined struct
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" mininum(1) maxinum(10)
// @Param default query string false "string default" default(A)
Available
Field Name | Type | Description |
---|---|---|
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. |
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. |
Future
Field Name | Type | Description |
---|---|---|
format | string |
The extending format for the previously mentioned type . See Data Type Formats for further details. |
multipleOf | number |
See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.1.1. |
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. |
collectionFormat | string |
Determines the format of the array if type array is used. Possible values are:
csv . |
TIPS
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"`
}
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]
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"`
}
Description of struct
type Account struct {
// ID this is userid
ID int `json:"id"
}
About the Project
This project was inspired by yvasiyarov/swagger but we simplified the usage and added support a variety of web frameworks.
Documentation
¶
Overview ¶
Package swag converts Go annotations to Swagger Documentation 2.0. See https://github.com/swaggo/swag for more information about swag.
Index ¶
- Constants
- Variables
- func CheckSchemaType(typeName string)
- func GetSchemes(commentLine string) []string
- func IsGolangPrimitiveType(typeName string) bool
- func IsPrimitiveType(typeName string) bool
- func ReadDoc() (string, error)
- func Register(name string, swagger Swagger)
- func Skip(f os.FileInfo) error
- func TransToValidSchemeType(typeName string) string
- type Operation
- func (operation *Operation) ParseAcceptComment(commentLine string) error
- func (operation *Operation) ParseComment(comment string, astFile *ast.File) error
- func (operation *Operation) ParseEmptyResponseComment(commentLine string) error
- func (operation *Operation) ParseEmptyResponseOnly(commentLine string) error
- func (operation *Operation) ParseParamComment(commentLine string, astFile *ast.File) error
- func (operation *Operation) ParseProduceComment(commentLine string) error
- func (operation *Operation) ParseResponseComment(commentLine string, astFile *ast.File) error
- func (operation *Operation) ParseRouterComment(commentLine string) error
- func (operation *Operation) ParseSecurityComment(commentLine string) error
- func (operation *Operation) ParseTagsComment(commentLine string)
- type Parser
- func (parser *Parser) GetSwagger() *spec.Swagger
- func (parser *Parser) ParseAPI(searchDir string, mainAPIFile string)
- func (parser *Parser) ParseDefinition(pkgName string, typeSpec *ast.TypeSpec, typeName string)
- func (parser *Parser) ParseDefinitions()
- func (parser *Parser) ParseGeneralAPIInfo(mainAPIFile string)
- func (parser *Parser) ParseRouterAPIInfo(astFile *ast.File)
- func (parser *Parser) ParseType(astFile *ast.File)
- type Swagger
Constants ¶
const ( // CamelCase indicates using CamelCase strategy for struct field. CamelCase = "camelcase" // PascalCase indicates using PascalCase strategy for struct field. PascalCase = "pascalcase" // SnakeCase indicates using SnakeCase strategy for struct field. SnakeCase = "snakecase" )
const Name = "swagger"
Name is a unique name be used to register swag instance.
const Version = "v1.3.2"
Version of swag
Variables ¶
var ErrFailedConvertPrimitiveType = errors.New("swag property: failed convert primitive type")
ErrFailedConvertPrimitiveType Failed to convert for swag to interpretable type
Functions ¶
func CheckSchemaType ¶ added in v1.1.1
func CheckSchemaType(typeName string)
CheckSchemaType TODO: NEEDS COMMENT INFO
func GetSchemes ¶
GetSchemes parses swagger schemes for given commentLine
func IsGolangPrimitiveType ¶ added in v1.4.0
IsGolangPrimitiveType determine whether the type name is a golang primitive type
func IsPrimitiveType ¶ added in v1.4.0
IsPrimitiveType determine whether the type name is a primitive type
func TransToValidSchemeType ¶ added in v1.1.1
TransToValidSchemeType indicates type will transfer golang basic type to swagger supported type.
Types ¶
type Operation ¶
type Operation struct { HTTPMethod string Path string spec.Operation // contains filtered or unexported fields }
Operation describes a single API operation on a path. For more information: https://github.com/swaggo/swag#api-operation
func NewOperation ¶
func NewOperation() *Operation
NewOperation creates a new Operation with default properties. map[int]Response
func (*Operation) ParseAcceptComment ¶
ParseAcceptComment parses comment for given `accept` comment string.
func (*Operation) ParseComment ¶
ParseComment parses comment for given comment string and returns error if error occurs.
func (*Operation) ParseEmptyResponseComment ¶
ParseEmptyResponseComment parse only comment out status code and description,eg: @Success 200 "it's ok"
func (*Operation) ParseEmptyResponseOnly ¶ added in v1.4.0
ParseEmptyResponseOnly parse only comment out status code ,eg: @Success 200
func (*Operation) ParseParamComment ¶
ParseParamComment parses params return []string of param properties @Param queryText form string true "The email for login"
[param name] [paramType] [data type] [is mandatory?] [Comment]
@Param some_id path int true "Some ID"
func (*Operation) ParseProduceComment ¶
ParseProduceComment parses comment for gived `produce` comment string.
func (*Operation) ParseResponseComment ¶
ParseResponseComment parses comment for gived `response` comment string.
func (*Operation) ParseRouterComment ¶
ParseRouterComment parses comment for gived `router` comment string.
func (*Operation) ParseSecurityComment ¶ added in v1.3.2
ParseSecurityComment parses comment for gived `security` comment string.
func (*Operation) ParseTagsComment ¶ added in v1.1.0
ParseTagsComment parses comment for given `tag` comment string.
type Parser ¶
type Parser struct { // TypeDefinitions is a map that stores [package name][type name][*ast.TypeSpec] TypeDefinitions map[string]map[string]*ast.TypeSpec // CustomPrimitiveTypes is a map that stores custom primitive types to actual golang types [type name][string] CustomPrimitiveTypes map[string]string PropNamingStrategy string // contains filtered or unexported fields }
Parser implements a parser for Go source files.
func (*Parser) GetSwagger ¶
GetSwagger returns *spec.Swagger which is the root document object for the API specification.
func (*Parser) ParseAPI ¶ added in v1.3.2
ParseAPI parses general api info for gived searchDir and mainAPIFile
func (*Parser) ParseDefinition ¶ added in v1.1.1
ParseDefinition TODO: NEEDS COMMENT INFO
func (*Parser) ParseDefinitions ¶
func (parser *Parser) ParseDefinitions()
ParseDefinitions parses Swagger Api definitions.
func (*Parser) ParseGeneralAPIInfo ¶ added in v1.3.2
ParseGeneralAPIInfo parses general api info for gived mainAPIFile path
func (*Parser) ParseRouterAPIInfo ¶ added in v1.3.2
ParseRouterAPIInfo parses router api info for given astFile