swag

repository·master·Indexed 12 days ago

https://github.com/swaggo/swag

A tool that converts Go annotations in comments into Swagger 2.0 documentation. It allows developers to maintain API documentation within Go source code to automatically generate JSON/YAML specifications and Swagger UI integration. Features include a CLI for documentation initialization via `swag init`, support for Gin web application integration, and a comprehensive set of declarative annotations for API operations, security definitions, and parameter attributes.

Tokens
32.1K
Snippets
116
Records
150
Agent score
91%

What's inside swag

  1. Supported Web Frameworks

    master

    Swag provides plugins and integrations for various Go web frameworks to facilitate Swagger UI integration. Supported frameworks include:

    • Gin: via github.com/swaggo/gin-swagger
    • Echo: via github.com/swaggo/echo-swagger
    • Buffalo: via github.com/swaggo/buffalo-swagger
    • net/http, gorilla/mux, go-chi/chi: via github.com/swaggo/http-swagger
    • Fiber: via github.com/gofiber/swagger
    • Hertz: via github.com/hertz-contrib/swagger
    • others: flamingo, atreugo
  2. Compose models in responses (Overriding fields)

    master

    You can override specific fields of a generic response object using the {field=type} syntax. This is useful for wrapping a standard response struct with a specific data type.

    ```go
    // 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"`
    }

    Supported variations:

    • Nested arrays: @success 200 {object} jsonresult.JSONResult{data=[]proto.Order} "desc"
    • Primitive types: @success 200 {object} jsonresult.JSONResult{data=string} "desc"
    • Multiple overlapping fields: @success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order} "desc"
    • Deep-level overriding: @success 200 {object} jsonresult.JSONResult{data1=proto.Order{data=proto.DeepObject}} "desc"
  3. Perform model composition and field overriding in responses

    master

    You can override specific fields of a response object using the {baseType}{field=overrideType} syntax. This is useful for generic wrappers where the data field changes based on the endpoint.

    Supported patterns:

    • Single field override: {data=proto.Order}
    • Array field override: {data=[]proto.Order}
    • Primitive field override: {data=string}
    • Multiple field overrides: {data1=string,data2=[]string}
    • Deep-level overrides: {data1=proto.Order{data=proto.DeepObject}}
    // JSONResult's data field will be overridden by the specific type proto.Order
    @success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
  4. Configure Security Definitions and Operations

    master

    Swagger security can be defined globally and then applied to specific API operations.

    Global Definitions:

    • Basic Auth: // @securityDefinitions.basic BasicAuth
    • OAuth2: // @securitydefinitions.oauth2.application OAuth2Application (requires @tokenUrl and @scope annotations).

    Operation-level Application:

    • Apply a single security requirement: // @Security ApiKeyAuth
    • Apply OR condition: // @Security ApiKeyAuth || OAuth2Application[write, admin]
    • Apply AND condition: // @Security ApiKeyAuth && firebase
    // @securityDefinitions.basic BasicAuth
    
    // @securitydefinitions.oauth2.application OAuth2Application
    // @tokenUrl https://example.com/oauth/token
    // @scope.write Grants write access
    
    // @Security ApiKeyAuth && firebase
  5. Use Markdown for API Descriptions

    master

    If standard strings are insufficient for descriptions (e.g., you need to include images or code blocks), you can use Markdown files. swag will parse these files to populate the documentation.

    • Use @description.markdown to parse the application description from an api.md file.
    • Use @tag.description.markdown to parse a tag's description from a file named <tagname>.md.
    // @description.markdown No value needed, this parses the description from api.md
    // @tag.description.markdown
  6. Use custom structs and model combinations in responses

    master

    You can specify user-defined structs as response types. For complex scenarios, you can use a syntax to replace specific fields within a generic wrapper (like a JSON result object) with a specific model type. This supports nested arrays and primitive types.

    Supported patterns:

    • {object} Package.Struct{field=Other.Struct}: Replaces field with Other.Struct.
    • {object} Package.Struct{field=[]Other.Struct}: Replaces field with an array of Other.Struct.
    • {object} Package.Struct{field=string}: Replaces field with a primitive type.
    // Replaces the 'data' field of JSONResult with proto.Order
    // @success 200 {object} jsonresult.JSONResult{data=proto.Order} "desc"
    
    // Replaces multiple fields
    // @success 200 {object} jsonresult.JSONResult{data1=string,data2=[]string,data3=proto.Order} "desc"
  7. Configure struct field metadata (examples and descriptions)

    master

    You can enrich your Swagger documentation by adding metadata directly to your Go struct fields:

    • Examples: Use the example JSON tag to provide sample values.
    • Descriptions: Use standard Go comments on the field line to provide descriptions.
    type Account struct {
        ID   int    `json:"id" example:"1"` // ID this is userid
        Name string `json:"name" example:"account name"` // This is Name
    }
  8. Add custom extensions to struct fields

    master

    You can add custom vendor extensions to Swagger fields using the extensions tag. Extension keys must start with x-.

    type Account struct {
        ID string `json:"id" extensions:"x-nullable,x-abc=def,!x-omitempty"` 
    }
  9. Use multiple path parameters in routes

    master

    When defining routes with multiple path parameters, use the @Param tag with the path type for each parameter, and ensure the @Router path matches the parameter names in curly braces.

    // @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]
  10. Generate Swagger documentation with `swag init`

    master

    Run swag init in your project's root folder (the one containing your main.go file). This parses your Go annotations and generates a docs folder containing docs.go, swagger.json, and swagger.yaml.

    Important: You must import the generated docs package in your application so that the configuration is initialized.

    If your General API annotations are not located in main.go, use the -g flag to specify the correct file path.

    # Standard initialization
    swag init
    
    # Initialize specifying a different entry point for General API Info
    swag init -g http/api.go
  11. Annotate API Operations

    master

    Use declarative comments above your controller methods to define API endpoints. Required annotations include @Summary, @Description, @Tags, and @Router.

    Common annotations:

    • @Summary: Short summary of the operation.
    • @Description: Detailed description.
    • @Tags: Grouping for the operation.
    • @Accept: MIME types the API consumes (e.g., json).
    • @Produce: MIME types the API produces (e.g., json).
    • @Param: Defines parameters (path, query, body, header).
    • @Success: Defines successful response (e.g., 200 {object} model.Account).
    • @Failure: Defines error responses.
    • @Router: The endpoint path and HTTP method (e.g., /accounts/{id} [get]).

    Example:

    // 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      404  {object}  httputil.HTTPError
    // @Router       /accounts/{id} [get]
    func (c *Controller) ShowAccount(ctx *gin.Context) {
        // ... implementation
    }
    // 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      404  {object}  httputil.HTTPError
    // @Router       /accounts/{id} [get]
    func (c *Controller) ShowAccount(ctx *gin.Context) {
      id := ctx.Param("id")
      // ...
    }
  12. Integrate swag with Gin web framework

    master

    To serve Swagger 2.0 documentation in a Gin application, follow these steps:

    1. Generate documentation: Run swag init to generate the docs package.
    2. Install dependencies: Import github.com/swaggo/gin-swagger and github.com/swaggo/files.
    3. Configure General API Info: Add declarative comments in your main.go (e.g., @title, @version, @host) or set them programmatically using the docs.SwaggerInfo object exported by the generated docs package.
    4. Register the Swagger handler: Add a route to your Gin engine to serve the documentation, typically at /swagger/*any.

    Example of programmatic configuration:

    import (
        "github.com/gin-gonic/gin"
        "github.com/swaggo/files"
        "github.com/swaggo/gin-swagger"
        "./docs" // Generated by Swag CLI
    )
    
    func main() {
        docs.SwaggerInfo.Title = "Swagger Example API"
        docs.SwaggerInfo.Description = "This is a sample 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()
        r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
        r.Run()
    }
    r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))