Skip to content
iris-contribPublic

About

Iris middleware to automatically generate RESTful API documentation with Swagger 2.0

Topics

Resources

Stars

120 stars

Watchers

3 watching

Forks

Repository files navigation

Swagger for the Iris web framework

Iris middleware to automatically generate RESTful API documentation with Swagger 2.0 as requested at #1231.

build status

It serves the Swagger UI page and the API definition that Swag generates from the comments of your Go code. Handler functions and the methods of a controller are documented the same way.

Iris version

The master branch is for Iris v14 (github.com/kataras/iris/v14) and its module path ends in /v14. It needs Go 1.27 or newer, as Iris v14 does. The framework's migration guide covers the upgrade from v12, and Upgrading from v12 lists what is different in this module.

$ go get github.com/iris-contrib/swagger/v14@latest

For Iris v12, see the v12 branch. Its README has the install command for that version.

Usage

Start using it

  1. Add comments to your API source code, See Declarative Comments Format.
  2. Download Swag for Go by using:
$ go install github.com/swaggo/swag/cmd/swag@latest
  1. Run the Swag in your Go project root folder which contains main.go file, Swag will parse comments and generate required files(docs folder and docs/docs.go). Run it again every time a comment changes.
$ swag init
  1. Download swagger for Iris by using:
$ go get github.com/iris-contrib/swagger/v14@latest

And import following in your code:

import "github.com/iris-contrib/swagger/v14" // swagger middleware for Iris
import "github.com/iris-contrib/swagger/v14/swaggerFiles" // swagger embed files

Example Code:

package main

import (
	"github.com/kataras/iris/v14"

	"github.com/iris-contrib/swagger/v14"
	"github.com/iris-contrib/swagger/v14/swaggerFiles"

	_ "github.com/your_username/your_project/docs"
	// docs folder should be generated by Swag CLI (swag init),
	// you have to import it.
)

// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore 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 /v2
func main() {
	app := iris.New()

	swaggerUI := swagger.Handler(swaggerFiles.Handler,
		swagger.URL("/swagger/swagger.json"),
		swagger.DeepLinking(true),
		swagger.Prefix("/swagger"),
	)

	// Register on http://localhost:8080/swagger
	app.Get("/swagger", swaggerUI)
	// And the wildcard one for index.html, *.js, *.css and e.t.c.
	app.Get("/swagger/{any:path}", swaggerUI)

	app.Listen(":8080")
}
  1. Run it, and navigate through http://localhost:8080/swagger/index.html, you should see the Swagger 2.0 API documentation page.

  2. If you want to disable swagger when some environment variable is set, use DisablingHandler instead of Handler. With the variable set to any value, every route of the page answers 404.

swaggerUI := swagger.DisablingHandler(swaggerFiles.Handler, "THE_OS_VARIABLE_NAME_HERE",
	swagger.URL("/swagger/swagger.json"),
	swagger.Prefix("/swagger"),
)
  1. If you want to change swagger-ui theme, you can add swagger.SetTheme(swagger.Monokai) when init swaggerUI
swaggerUI := swagger.Handler(swaggerFiles.Handler,
	swagger.URL("/swagger/swagger.json"),
	swagger.DeepLinking(true),
	swagger.Prefix("/swagger"),
	// ref: https://github.com/ostranme/swagger-ui-themes
	// current we support 7 themes
	// theme is a optional config, if you not set, it will use default theme
	swagger.SetTheme(swagger.Monokai),
)

The basic example is the program above with two documented handlers.

Controllers

Swag does not run your application and it knows nothing about Iris routes. It reads comments. A route is on the page only when the function or method behind it has a comment block with a @Router line, and a controller is no exception: the comments go on the methods of the controller, one block for each method. A comment on the controller type, on its constructor or next to app.Router documents nothing.

The mvc example is a complete program with a controller, its generated docs and tests. The snippets below are taken from it.

A controller of the controller/mvc package

mvc.UseController makes five routes out of the five methods of a controller. Write the comments of each route above its method:

import (
	"github.com/kataras/iris/v14"
	"github.com/kataras/iris/v14/controller/mvc"
)

func main() {
	app := iris.New()
	app.Router("/stores", mvc.UseController[*StoreController]())
	// ...
}

type StoreController struct {
	Repository *StoreRepository
}

// Create adds a store.
//
// @Summary Create a store
// @Tags stores
// @Accept json
// @Produce json
// @Param store body Store true "The new store. The server sets its id."
// @Success 201 {object} Store
// @Failure 400 "The body is not a JSON object"
// @Router /stores [post]
func (c *StoreController) Create(ctx iris.Context, in Store) (Store, error) {
	return c.Repository.Create(in), nil
}

// Get returns a store.
//
// @Summary Get a store
// @Tags stores
// @Produce json
// @Param store_id path string true "The id of the store"
// @Success 200 {object} Store
// @Failure 404 "There is no store with this id"
// @Router /stores/{store_id} [get]
func (c *StoreController) Get(ctx iris.Context, id string) (Store, error) {
	// ...
}

Swag cannot work out the @Router line by itself, so that is the line to get right. It has the path of the route, without the @BasePath, and the HTTP method:

Method of the controller Route that Iris makes Its comment
Create POST /stores // @Router /stores [post]
Get GET /stores/{store_id:string} // @Router /stores/{store_id} [get]
Update PUT /stores/{store_id:string} // @Router /stores/{store_id} [put]
Delete DELETE /stores/{store_id:string} // @Router /stores/{store_id} [delete]
List POST /stores/list // @Router /stores/list [post]
  • Iris names the path parameter after the model of the controller: store_id for a Store with an id field. The mvc.IDParam option gives it another name. A comment has the name alone, {store_id}, and the same name is in its @Param line. The type that an Iris path has after the colon stays out.
  • List reads the page and the size from the URL query and the filter from the JSON body, so its comments have two query parameters and a body one. The route answers the QUERY method too. Swagger 2.0 cannot describe that method, which leaves [post].
  • List responds with an iris.Page[Store]. Swag reads the types of your own module, so {object} iris.Page[Store] fails with "cannot find type definition". There are two ways out. The example describes the body with a type of its own, StorePage, and a test keeps its fields the same as the real ones. Or keep the framework type in the comment and run swag init --parseDependency: Swag then reads the source of every dependency as well, and the run that takes one second for the example takes 15 or more.

A controller with a Routing method

A controller that registers its routes by hand does it in a Routing method. The comments are on the method that each route runs, exported or not. This one adds a sixth route to the controller above:

func (c *StoreController) Routing(r iris.Router) {
	r.Get("/count", c.count)
}

// @Summary Count the stores
// @Tags stores
// @Produce json
// @Success 200 {object} StoreCount
// @Router /stores/count [get]
func (c *StoreController) count(ctx iris.Context) {
	ctx.JSON(StoreCount{Total: c.Repository.Count()})
}

The page is there but it has no operations

  • Run swag init again. The page shows the docs package as it was generated last, not the comments as they are now.
  • Run it in the directory of main.go. Swag reads that directory and the ones below it. Controllers that live somewhere else are named with -d, and a general information block that is not in main.go with -g.
  • Import the generated docs package, as the example code does. Without the import nothing registers the definition: the page says it failed to load it and the application logs swagger: no swag named "swagger" was registered.
  • Look for a method without a @Router line, or with the path of another route in it.
  • Open http://localhost:8080/swagger/swagger.json. What is in its paths is what the page can show.

What the handler serves

With the /swagger prefix:

Path Response
/swagger, /swagger/index.html The Swagger UI page
/swagger/swagger.json The API definition
/swagger/doc.json The same definition, under the name it had up to v12.2.0
/swagger/<name>.json The definition generated with swag init --instanceName <name>
/swagger/*.js, *.css, *.png The files of the page, embedded in the swaggerFiles package

Register the handler twice, as the example code does: once on the prefix and once on {any:path} below it. It answers GET and HEAD only. On a route that lets other methods reach it, one registered with app.Any for example, they get a 405.

Options

Option Default Description
swagger.URL(string) swagger.json under the prefix The address the page loads the API definition from
swagger.Prefix(string) "/swagger" The path the handler is registered on. With "." every link of the page is relative
swagger.DeepLinking(bool) true The page keeps the open tag and operation in the address
swagger.DocExpansion(string) "list" What is open when the page loads: "list", "full" or "none"
swagger.FontCDN(string) "https://fonts.googleapis.com" Where the fonts of the page come from
swagger.SetTheme(swagger.Theme) none One of FeelingBlue, Material, Muted, Outline, Flattop, Monokai, Newspaper
swagger.DomID(string) "#swagger-ui" The element the UI is drawn in. The page has only this one, so leave it

A swagger.Config value is an option as well:

swaggerUI := swagger.Handler(swaggerFiles.Handler, swagger.Config{
	URL:         "/swagger/swagger.json",
	Prefix:      "/swagger",
	DeepLinking: true,
	Filter:      true,
})

It sets URL, Prefix, DeepLinking, DocExpansion, DomID and Filter as they are written, so a literal without DeepLinking or Filter turns that one off. An empty URL, DocExpansion or DomID gets its default, and FontCDN and Theme are applied when they are set. Filter is the box of the page that filters the operations by tag. It is on by default and only a Config value turns it off.

More than one definition

swag init --instanceName internal writes a docs package that registers its definition under the name internal, and the handler serves it at /swagger/internal.json. Give each definition a page of its own by registering a second handler under another prefix:

internal := swagger.Handler(swaggerFiles.Handler,
	swagger.Prefix("/internal/docs"),
	swagger.URL("/internal/docs/internal.json"),
)
app.Get("/internal/docs", internal)
app.Get("/internal/docs/{any:path}", internal)

An application made by iris.NewBuilder

The page is one more API of the builder. The builder puts its prefix in front of every API, so the Prefix option has the whole path:

swaggerUI := swagger.Handler(swaggerFiles.Handler,
	swagger.URL("/api/swagger/swagger.json"),
	swagger.Prefix("/api/swagger"),
)

app := iris.NewBuilder().
	Prefix("/api").
	AllowOrigin("*").
	Compression(false).
	LogRequests(false).
	NoHealth().
	Services(NewStoreRepository()).
	RouterMiddlewares().
	Middlewares().
	API("/stores", mvc.UseController[*StoreController]()).
	API("/swagger", func(r iris.Router) {
		r.Get("/", swaggerUI)
		r.Get("/{any:path}", swaggerUI)
	}).
	Build()

Write // @BasePath /api in the general information of such an application and leave the prefix out of the @Router lines.

Upgrading from v12

Change the two import paths from /v12 to /v14 and build with Go 1.27. No exported name has changed: swagger.Handler, swagger.DisablingHandler, the options and swagger.Config are called as before.

What behaves differently:

  • The default URL is swagger.json under the prefix, /swagger/swagger.json. It was the relative swagger/swagger.json, which the page could not find when it was opened as /swagger/index.html.
  • /swagger/doc.json serves the definition again, as it did up to v12.2.0. v12.2.11 answers it with a 500 unless a definition is named doc.
  • The handler answers GET and HEAD only. Before, a route registered with app.Any let a client replace or delete the files of the page.
  • swagger.Handler no longer changes the Prefix of the handler it is given. Two pages under two prefixes work in one application.
  • A swagger.Config value applies its FontCDN and Theme, which were ignored, and an empty URL, DocExpansion or DomID gets its default.
  • Importing swaggerFiles no longer prints init /theme-feeling-blue.css when the program starts.

About

Iris middleware to automatically generate RESTful API documentation with Swagger 2.0

Topics

Resources

Stars

120 stars

Watchers

3 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages