1
votes

I have an OpenAPI specification and I have used openapi-generator to generate Golang gin server.

What is the conventional way to generate Swagger documentation server from the OpenAPI specification?

I have already tried swag: it generates documentation on http://localhost:8080/swagger/index.html endpoint. But this requires API to be described in code annotations. I am looking for a Swagger UI generator from the OpenAPI specification that I already have.

Thanks.

3
What do you mean "swagger interface from the open API spec"? Swagger is the old 2.0 name for OpenAPI. OpenAPI is used for version 3.0 onward. - Software2

3 Answers

0
votes

You can run swagger editor in a docker container. Pull it from https://hub.docker.com/r/swaggerapi/swagger-editor, run it, point your browser at http://localhost:8080, then load your api.yaml file. You can also run swagger ui https://hub.docker.com/r/swaggerapi/swagger-ui.

0
votes

I am not sure about Gin, but I am happy to share my solution (based upon go-server):

  1. Create a directory in your project root dir called ./swagger-ui
  2. Copy the files under dist/* of swagger-ui (https://github.com/swagger-api/swagger-ui/tree/master/dist) here
  3. Update in swagger-ui/index.html the location of the api spec to url: "/api/openapi.yaml"
  4. In main.go create a new variable annotated with //go:embed swagger-ui/* api/openapi.yaml (the latter directory was created by openapi-generator CLI)
  5. Add below the (generated) router in main.go: router.PathPrefix("/").Handler(http.FileServer(http.FS(staticFiles)))

That's it - you will have the Swagger UI available under /swagger-ui and the api definition loaded automatically from /api/openapi.yaml

package main

import (
    "context"
    ...
)

//go:embed swagger-ui/* api/openapi.yaml
var staticFiles embed.FS

func main() {
    router := ....

    // Embed the Swagger UI within Go binary
    router.PathPrefix("/").Handler(http.FileServer(http.FS(staticFiles)))

    ...
0
votes

There is a library that packages Swagger UI as Go http.Handler: https://github.com/swaggest/swgui.

package main

import (
    "net/http"

    "github.com/swaggest/swgui/v3emb" // For go1.16 or later.
    // "github.com/swaggest/swgui/v3" // For go1.15 and below.
)

func main() {
    http.Handle("/", v3.NewHandler("My API", "/swagger.json", "/"))
    http.ListenAndServe(":8080", nil)
}

"/swagger.json" in this example is an URL to the OpenAPI spec file.