#Go Swagger Tutorial

Elliot Forbes Elliot Forbes · Mar 1, 2020 · 2 min read

In this tutorial, we are going to look at how we can integrate Swagger on top of our Go REST APIs!

What Is Swagger?

Swagger (now known as OpenAPI) is an industry-standard tool for documenting and visualizing REST APIs. It automatically generates interactive API documentation that allows developers to explore and test your endpoints directly from a web interface.

Why Use Swagger/OpenAPI?

Using Swagger/OpenAPI provides several key benefits:

  • Interactive Documentation: Developers can explore your API endpoints and parameters in an interactive web UI
  • API Testing: Built-in tools for testing endpoints without external tools like Postman
  • Code Generation: Automatically generate client libraries and server stubs from your OpenAPI specification
  • Standardization: Uses a widely-adopted industry standard for API documentation
  • Reduced Documentation Burden: Annotations in your code automatically generate documentation

Getting Started with Swaggo

The most popular way to add Swagger/OpenAPI documentation to Go REST APIs is using the swaggo package. Let’s get started:

go get -u github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/http-swagger/v2

Annotating Your API

Add Swagger annotations to your Go code using structured comments:

package main

import (
	"net/http"
	"github.com/swaggo/http-swagger/v2"
	_ "your-module/docs"
)

// @Summary Get all users
// @Description Get a list of all users
// @Tags users
// @Accept json
// @Produce json
// @Success 200 {array} User
// @Router /users [get]
func getUsers(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(`[{"id":1,"name":"Alice"}]`))
}

func main() {
	http.HandleFunc("GET /users", getUsers)
	http.Handle("/swagger/", httpSwagger.Handler)
	http.ListenAndServe(":8080", nil)
}

Generating Documentation

Run the swag CLI to generate your Swagger documentation:

swag init

This creates a docs/ directory containing your OpenAPI specification. Access your documentation at http://localhost:8080/swagger/index.html.

Conclusion

Swagger/OpenAPI is essential for professional API development. By integrating it into your Go projects, you provide clear documentation and interactive testing capabilities for your APIs, significantly improving the developer experience.

Further Reading: