Skip to content
forked from swaggo/swag

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

License

Notifications You must be signed in to change notification settings

Bongsakorn/swag

 
 

Repository files navigation

swag

swaggo

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

Travis Status Coverage Status Go Report Card codebeat badge Go Doc

gopher image source is tenntenn/gopher-stickers. It has licenses creative commons licensing.

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

Documentation

For a comprehensive explanation of what swag can do, check out the swag documentation.

Getting started

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

  2. Download swag by using:

$ go get -u github.com/Bongsakorn/swag/cmd/swag
  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).
$ swag init
  1. 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 gets init'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.

  1. 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
  1. 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")
}
//...
  1. Add API Operation annotations in controller code
package controller

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/Bongsakorn/swag/example/celler/httputil"
	"github.com/Bongsakorn/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)
}

//...

4.Run it, and browse to http://localhost:8080/swagger/index.html. You will see Swagger 2.0 Api documents as shown below:

swagger_index.html

Examples

swaggo + gin

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

About the Project

This project was inspired by swagger but we simplified the usage and added support a variety of web frameworks.

About

Automatically generate RESTful API documentation with Swagger 2.0 for Go.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 99.6%
  • Makefile 0.4%