DEV Community

Cover image for DevPill #5 - Basic steps to document your REST API with Swagger
Raul Paes Silva
Raul Paes Silva

Posted on

DevPill #5 - Basic steps to document your REST API with Swagger

Install

go install github.com/swaggo/swag/cmd/swag@latest
go get github.com/swaggo/http-swagger
go get github.com/swaggo/swag
go get -u github.com/swaggo/http-swagger
Enter fullscreen mode Exit fullscreen mode

Add the comments on the following sections of your code

(reference):

  • main function on main.go
  • webserver handlers
  • dtos

Tip: you can send your code to A.I. and ask to create the Swagger comments based on it.


Add the following "imports" in main.go:

import(
    _ "github.com/raulsilva-tech/devices-api/internal/docs" 
    httpSwagger "github.com/swaggo/http-swagger"
)
Enter fullscreen mode Exit fullscreen mode

Add a new handler to serve the documentation on the API

Example:

mux.Handle("/swagger/", httpSwagger.WrapHandler)
Enter fullscreen mode Exit fullscreen mode

The following command create de json docs in the path "internal/docs":

swag init -g cmd/api/main.go -o internal/docs
Enter fullscreen mode Exit fullscreen mode

Top comments (0)