Tutorial: Generate Swagger Specification and SwaggerUI for Go Fiber Web Framework

Rizal Widyarta Gowandy
Geek Culture
Published in
5 min readApr 16, 2021

--

Why Fiber Web Framework?

Fiber popularity rank is on the rise. Based on the latest benchmark it’s way faster than Echo. The biggest difference with Echo, that it uses fasthttp router instead of net/http.

Go Framework Benchmark

The benchmark graph above means the higher the value the better. It means that our HTTP router can process more request per seconds. Fiber is basically much faster compares to Echo.

Why Swagger Specification?

Writing a specification is a meticulous process in Software Engineering. Regardless, it’s necessary if we want our API being used by others. It helps others to integrate without API with more ease. The better the documentation the easier others will integrate it into their system. In order to tackle this problem, we should follow a standardized way to create API documentation in the industry, the OpenAPI Specification or formerly known as the Swagger Specification.

The OpenAPI Specification, formerly known as the Swagger Specification, is the world’s standard for defining RESTful interfaces. The OAS enables developers to design a technology-agnostic API interface that forms the basis of their API development and consumption.

Prerequisite

You need to install Go version ≥1.14 in your machine.

Steps

  1. Create folders for development, we will call the app fibersimple.
$ mkdir fibersimple
$ mkdir docs
$ mkdir docs/fibersimple

2. Initialize go mod for go vendor system.

$ go mod init

3. Pull the Fiber library.

$ go get -u github.com/gofiber/fiber/v2

4. Inside fibersimple folder, create a new file main.go and copy the code below.

package main

import (
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2"
"log"
)

func main() {
// Fiber instance
app := fiber.New()

// Middleware
app.Use(recover.New())
app.Use(cors.New())

// Routes
app.Get("/", HealthCheck)

// Start Server
if err := app.Listen(":3000"); err != nil {
log.Fatal(err)
}
}

func HealthCheck(c *fiber.Ctx) error {
res := map[string]interface{}{
"data": "Server is up and running",
}

if err := c.JSON(res); err != nil {
return err
}

return nil
}

5. Run the app.

$ go run fibersimple/main.go

You should see an output like below.

 ┌───────────────────────────────────────────────────┐  
│ Fiber v2.7.1 │
│ http://127.0.0.1:3000 │
│ (bound on host 0.0.0.0 and port 3000) │
│ │
│ Handlers ............. 3 Processes ........... 1 │
│ Prefork ....... Disabled PID ............. 36364 │
└───────────────────────────────────────────────────┘

It means our server is up and running on port 3000.

6. Update our main.go by adding declarative comments format. These comments will be used later to automatically generate Swagger Specification. You can learn more about the declarative comments format using the link in the reference.

package main

import (
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2"
"log"
)

// @title Fiber Swagger Example API
// @version 2.0
// @description This is a sample server 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:3000
// @BasePath /
// @schemes http
func main() {
// Fiber instance
app := fiber.New()

// Middleware
app.Use(recover.New())
app.Use(cors.New())

// Routes
app.Get("/", HealthCheck)

// Start Server
if err := app.Listen(":3000"); err != nil {
log.Fatal(err)
}
}

// HealthCheck godoc
// @Summary Show the status of server.
// @Description get the status of server.
// @Tags root
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router / [get]
func HealthCheck(c *fiber.Ctx) error {
res := map[string]interface{}{
"data": "Server is up and running",
}

if err := c.JSON(res); err != nil {
return err
}

return nil
}

7. Pull swagger libraries.

$ go get -v github.com/swaggo/swag/cmd/swag
$ go get -u github.com/arsmn/fiber-swagger/v2
$ go mod vendor -v

8. Generate the Swagger Specification.

$ swag init -g fibersimple/main.go --output docs/fibersimple

If the operation is successful, you should see 3 new files inside folder docs/fibersimple. These files are:

  • docs.go => Requires to generate SwaggerUI.
  • swagger.json => The Swagger Specification in json file format.
  • swagger.yaml => The Swagger Specification in yaml file format.

If you use Confluence to distribute your documentation, you could create a new file inside Confluence and choose to add OpenAPI Specification. Then copy and paste the swagger.yaml content inside.

9. Update main.go to add SwaggerUI.

package mainimport (
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2"
"log"
_ "github.com/rizalgowandy/go-swag-sample/docs/fibersimple" // you need to update github.com/rizalgowandy/go-swag-sample with your own project path
swagger "github.com/arsmn/fiber-swagger/v2"
)

// @title Fiber Swagger Example API
// @version 2.0
// @description This is a sample server 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:3000
// @BasePath /
// @schemes http
func main() {
// Fiber instance
app := fiber.New()

// Middleware
app.Use(recover.New())
app.Use(cors.New())

// Routes
app.Get("/", HealthCheck)
app.Get("/swagger/*", swagger.Handler) // default

// Start Server
if err := app.Listen(":3000"); err != nil {
log.Fatal(err)
}
}

// HealthCheck godoc
// @Summary Show the status of server.
// @Description get the status of server.
// @Tags root
// @Accept */*
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Router / [get]
func HealthCheck(c *fiber.Ctx) error {
res := map[string]interface{}{
"data": "Server is up and running",
}

if err := c.JSON(res); err != nil {
return err
}

return nil
}

As you can see, there are 2 important things we add on our main.go.

  • A new route for SwaggerUI.
app.Get("/swagger/*", swagger.Handler) // default
  • New imports for the generated docs.go and swag library. Don’t forget to replace the github.com/rizalgowandy/go-swag-sample path with your project path.
import (
...
_ "github.com/rizalgowandy/go-swag-sample/docs/fibersimple" // you need to update github.com/rizalgowandy/go-swag-sample with your own project path
swagger "github.com/arsmn/fiber-swagger/v2"
)

10. Finally, run the app again.

$ go mod vendor -v
$ go run fibersimple/main.go

11. Now try, the call the new added route.

$ curl localhost:3000/swagger/doc.json

You should see output like.

{
"schemes": [
"http"
],
"swagger": "2.0",
"info": {
"description": "This is a sample server server.",
"title": "Fiber Swagger Example API",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "support@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "2.0"
},
"host": "localhost:3000",
"basePath": "/",
"paths": {
"/": {
"get": {
"description": "get the status of server.",
"consumes": [
"*/*"
],
"produces": [
"application/json"
],
"tags": [
"root"
],
"summary": "Show the status of server.",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "object",
"additionalProperties": true
}
}
}
}
}
}
}

12. Open the SwaggerUI in the browser using this URL.

http://localhost:3000/swagger/index.html

You should see output like.

Voilà, and we are done. We successfully created a simple Go web server using Fiber framework, and generate the Swagger Specification and SwaggerUI.

References

--

--

Rizal Widyarta Gowandy
Geek Culture

Software Engineer | INTJ | Choleric | The Questioner (CD) | Creator & Advisor