Skip to content

OpenAPI ​

Added: v1.1.0 - Rebuilt on swag in v1.5.0

A docs-serving layer built into zen serves swaggo-generated API documentation through the embedded Scalar UI - self-hosted in your binary, so it works with no internet connection or CDN. You annotate handlers with comment blocks, swag init generates an OpenAPI specification from them, and zen serves both the spec JSON and the interactive UI.

ConcernHandled byWhere
Spec content (endpoints, models, security)swag annotationscomments in your code
Spec generationswag init CLIbuild step
Serving JSON + Scalar UIzen.Engine.EnableAPIDocsruntime

Setup ​

1. Install the swag CLI ​

bash
go install github.com/swaggo/swag/cmd/swag@latest

This is a developer tool only - it never ships with your binary. The github.com/swaggo/swag library itself arrives transitively with zen.

2. Annotate your code ​

General API info goes above your entrypoint:

go
// @title        Users API
// @version      1.0.0
// @description  A simple user management API.
// @BasePath     /api/v1
func main() {

Each handler gets its own block:

go
// getUser godoc
//
// @Summary     Get user by ID
// @Description Returns a single user by their unique ID
// @Tags        Users
// @Produce     json
// @Param       id path int true "User ID"
// @Success     200 {object} UserResponse
// @Failure     404 {object} ErrorResponse
// @Router      /users/{id} [get]
func getUser(c *zen.Ctx) {
    // ...
}

:::note Paths are relative to @BasePath

With @BasePath /api/v1, annotate the handler route as /users/{id} - swag composes the full documented path. Models referenced in {object} resolve to any Go struct with json tags in your package.

:::

3. Generate ​

bash
swag init -g main.go -o docs

This produces docs/docs.go, docs/swagger.json, and docs/swagger.yaml. Re-run whenever annotations change. To automate, add a directive next to main:

go
//go:generate swag init -g main.go -o docs

and run go generate ./....

4. Import the generated package ​

go
import _ "myapp/docs"

The blank import is what registers the document at runtime. Forgetting it is the most common setup mistake - see Troubleshooting.

5. Enable it ​

Enable it on the engine in one call:

go
r.EnableAPIDocs()

EnableAPIDocs is a method on *zen.Engine — no blank import or linking step is needed. By default:

  • GET /openapi.json - the generated spec
  • GET /docs - Scalar UI pointing at that spec

Configuration ​

Pass an OpenAPIConfig to adjust the endpoints or swag instance:

go
r.EnableAPIDocs(zen.OpenAPIConfig{
    SpecPath:     "/api/openapi.json", // default "/openapi.json"
    DocPath:      "/api/docs",         // default "/docs"
    DisableUI:    false,               // true = spec only, no UI
    SwagInstance: "swagger",           // default swag.Name; matches "swag init --instanceName"
})

A func(*zen.OpenAPIConfig) modifier tweaks the config on top of the struct:

go
r.EnableAPIDocs(zen.OpenAPIConfig{SpecPath: "/spec.json"}, func(c *zen.OpenAPIConfig) {
    c.DisableUI = true
})

EnableAPIDocs mounts endpoints via HandleRaw, so they bypass middleware chains. For manual mounting, SpecHandler and DocHandler return http.Handlers you can attach yourself:

go
doc := zen.NewOpenAPI(zen.OpenAPIConfig{})
r.GET("/openapi.json", doc.SpecHandler())
r.GET("/docs", doc.DocHandler())

UI Options ​

OpenAPIConfig.SwaggerUIOptions (name kept for compatibility) forwards entries to Scalar.createApiReference as init options - values are serialized as JSON literals, so strings, booleans, numbers, arrays, and nested objects all work:

go
r.EnableAPIDocs(zen.OpenAPIConfig{
    SwaggerUIOptions: map[string]any{
        "persistAuth":           true,
        "hideTestRequestButton": false,
        "layout":                "modern",
    },
})

The UI ships inside your binary (about 3.6 MB added) and renders fully offline. A zen topbar with a link to the docs site is rendered above it.

Security Schemes ​

Security is declared with annotations, keeping the documented spec aligned with your auth middleware.

Define schemes once near your entrypoint annotations:

go
// @title                      Users API
// @version                    1.0.0
// @securityDefinitions.apikey ApiKeyAuth
// @in                         header
// @name                       X-API-Key
// @securityDefinitions.http   BearerAuth
// @scheme                     bearer
// @bearerFormat               JWT
func main() {

Apply per operation with @Security above the handler:

go
// @Security ApiKeyAuth
// @Router   /admin/stats [get]

Supported definition types mirror the OpenAPI spec: apikey, http (basic/bearer), oauth2 (implicit, password, clientCredentials, and authorizationCode flows), and openIdConnect.

Multiple Instances ​

Serving more than one document in one binary (e.g. public vs admin):

bash
swag init -g cmd/public/main.go -o docs/public --instanceName public
swag init -g cmd/admin/main.go  -o docs/admin  --instanceName admin
go
r.EnableAPIDocs(zen.OpenAPIConfig{
    SwagInstance: "public",
    SpecPath:     "/public/openapi.json",
    DocPath:      "/public/docs",
})

r.EnableAPIDocs(zen.OpenAPIConfig{
    SwagInstance: "admin",
    SpecPath:     "/admin/openapi.json",
    DocPath:      "/admin/docs",
})

Each instance needs distinct paths - duplicate route registration is not detected.

Troubleshooting ​

GET /openapi.json returns 503 {"error":"..."}

No swag documentation is registered under the configured instance name. Either the generated docs package is not imported (add _ "myapp/docs"), or OpenAPIConfig.SwagInstance does not match the --instanceName used at generation time.

Docs look stale

The spec is embedded at generation time and cached after the first request - regenerate with swag init and rebuild. Nothing is parsed from source at runtime.

Spec version

Stable swag (v1.16.x) emits Swagger 2.0 documents; the embedded UI renders them fine. OpenAPI 3 support lives in swag's v2 branch (release candidates) - the serving layer is format-agnostic, so switching later requires no zen changes.

Full Example ​

A complete runnable version lives in the repository under examples/api.

go
package main

import (
    _ "myapp/docs"

    "github.com/Pavan-Silva/go-zen"
    "github.com/Pavan-Silva/go-zen/middleware"
)

type CreateUserRequest struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
}

type UserResponse struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

type ErrorResponse struct {
    Error string `json:"error"`
}

// @title        Users API
// @version      1.0.0
// @description  A simple user management API.
// @BasePath     /api/v1
func main() {
    r := zen.New(":8080")
    r.Use(middleware.Recover)
    r.Use(middleware.Logger)

    api := r.Group("/api")
    v1 := api.Group("/v1")

    v1.GET("/users", listUsers)
    v1.POST("/users", createUser)
    v1.GET("/health", healthCheck)

    r.EnableAPIDocs()
    r.Run()
}

// listUsers godoc
//
// @Summary List all users
// @Tags    Users
// @Produce json
// @Success 200 {object} ListUsersResponse
// @Router  /users [get]
func listUsers(c *zen.Ctx) {
    c.JSON(200, ListUsersResponse{Users: []UserResponse{}, Total: 0})
}

// createUser godoc
//
// @Summary Create a user
// @Tags    Users
// @Accept  json
// @Produce json
// @Param   user body CreateUserRequest true "User to create"
// @Success 201 {object} UserResponse
// @Failure 400 {object} ErrorResponse
// @Router  /users [post]
func createUser(c *zen.Ctx) {
    var req CreateUserRequest
    if err := c.BindJSON(&req); err != nil {
        c.JSON(400, ErrorResponse{Error: err.Error()})
        return
    }
    c.JSON(201, UserResponse{ID: 1, Name: req.Name, Email: req.Email})
}

// healthCheck godoc
//
// @Summary Health check
// @Produce json
// @Success 200 {string} string "ok"
// @Router  /health [get]
func healthCheck(c *zen.Ctx) {
    c.JSON(200, map[string]string{"status": "ok"})
}

Released under the MIT License.