Golang

How to Add Swagger (OpenAPI) Documentation to Your Go Web API

Adding Swagger (OpenAPI) documentation to your Go Web API is an excellent idea for improving developer experience and enabling automatic API docs generation.

To integrate Swagger with your project, we’ll use:

Swaggo/swag

It’s the most popular library for generating Swagger docs in Go.

Step-by-Step: Add Swagger to Your Project

Step 1: Install swag CLI

You need to install swag to generate the Swagger docs from comments.

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

Make sure your $GOPATH/bin is in your PATH. You can check:

export PATH=$PATH:$(go env GOPATH)/bin

Verify with:

swag --version

Step 2: Add Dependencies to Your Project

Run the following to install Swagger HTTP handlers:

go get github.com/swaggo/http-swagger
go get github.com/alecthomas/template
go get github.com/swaggo/files

 

Step 3: Add Swagger Annotations

You add annotations in the main.go and your handler functions.

main.go — with Swagger setup

package main

import (
	"fmt"
	"log"
	"net/http"

	_ "go-web-api/docs"
	httpSwagger "github.com/swaggo/http-swagger"
)

// @title           Go Web API Example
// @version         1.0
// @description     This is a simple Go web API with Swagger.
// @host            localhost:8080

// @schemes http
func main() {
	// Swagger endpoint
	http.Handle("/swagger/", httpSwagger.WrapHandler)

	fmt.Println("Server started at :8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

controllers/message_controller.go — Add annotations

package controllers

import (
	"encoding/json"
	"net/http"

	"go-web-api/models"
)

// @Summary      Welcome endpoint
// @Description  Returns a welcome message
// @Tags         Home
// @Accept       json
// @Produce      json
// @Success      200  {object}  models.Message
// @Router       / [get]
func Home(w http.ResponseWriter, r *http.Request) {
	msg := models.Message{Status: "success", Message: "Welcome to Go Web API"}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(msg)
}

// @Summary      Create message
// @Description  Accepts a message and adds it to memory
// @Tags         Messages
// @Accept       json
// @Produce      json
// @Param        message  body      models.Message  true  "Message Body"
// @Success      201      {object}  models.Message
// @Failure      400      {string}  string "Bad Request"
// @Router       /messages [post]
func PostMessage(w http.ResponseWriter, r *http.Request) {
	var msg models.Message
	_ = json.NewDecoder(r.Body).Decode(&msg)
	messages = append(messages, msg)
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(msg)
}

Step 4: Generate Swagger Docs

Run this command from the root of your project:

swag init

if main.go is not in root directory it might throw an error in this case you  need to run the below command to generate the docs folder in the root directory.

Solution: Tell swag Where to Look

Use the --generalInfo and --dir flags to explicitly specify where main.go and your Go code live.

swag init --generalInfo cmd/main.go --dir ./cmd
FlagMeaning
--generalInfopath to your main.go file
--dirfolder to recursively scan for annotations

This will generate two folders:

go-web-api/
??? docs/
?   ??? docs.go
?   ??? swagger.json
?   ??? swagger.yaml

Step 5: Run Your Server

go run main.go

Now visit:
http://localhost:8080/swagger/index.html

You'll see an interactive Swagger UI with your endpoints.

 


About author

author image

Amrit panta

Fullstack developer, content creator



Scroll to Top