Golang is a very good language to create web api servers. I like gofiber framework for creating web api servers. In this article, we will see how to use Swagger in Go especially with gofiber framework.

Install swaggo/swag

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

Create a new project

go mod init github.com/username/projectname

Setup Gofiber and Swagger

In the code below, we have created a simple API using gofiber framework.

The annotations are used to generate the swagger documentation.

package main

import (
    "github.com/gofiber/fiber/v2"
)

// @title ProjectName API
// @version 1.0
// @description This is a sample server ProjectName server.
// @host localhost:3000
// @BasePath /
func main() {
    app := fiber.New()

    setupRoutes(app)

    app.Listen(":3000")
}

Generate Swagger Documentation

swag init

This will generate a docs folder with the swagger documentation.

Update server to serve Swagger UI

Add import for swagger, which will call the init function in the docs package. which is required to serve the swagger documentation.

import _ "github.com/username/projectname/docs"

Add handler to serve the swagger documentation, with default handler.

app.Get("/swagger/*", swagger.Handler)

Run the server

go run main.go

Add more routes with annotations

type RegisterRequest struct {
    Email    string `json:"email"`
    Password string `json:"password"`
}

// @Summary Register an account
// @Success 200 {string} string "OK"
// @Failure 400 {string} string "Bad Request"
// @Accept json
// @Produce json
// @Router /api/auth/register [post]
// @Param RegisterRequest body RegisterRequest true "Register Request"
func RegisterHandler(c *fiber.Ctx) error {
    return c.JSON(fiber.Map{
        "message": "Hello, World!",
    })
}

When adding annotations to the routes, make sure to run swag init to update the swagger documentation.

Following Annotations are used in the comment:

  • @Summary - Summary of the route
  • @Success - Success response of the route, syntax: @Success <status_code> <response_type> <description>
  • @Failure - Failure response of the route, syntax: @Failure <status_code> <response_type> <description>
  • @Accept - Accept mime-type of the route
  • @Produce - Produce mime-type of the route
  • @Router - Route of the API, syntax: @Router <path> <http_method>
    • path - Path of the route: /{id} for path parameters
    • http_method - HTTP method of the route: get, post, put, delete, patch
  • @Param - Parameters of the route, syntax: @Param <name> <in> <type> <required> <description>
    • name - Name of the parameter
    • in - Location of the parameter: path, query, header, body, formData
    • type - Type of the parameter: string, integer, boolean, custom
    • required - Required or not
    • description - Description of the parameter