DEV Community

Maria Leitão
Maria Leitão

Posted on

Documentando uma API com Go Swagger

Passos para documentar uma RESTful API em Go com Swagger

  1. Instalar o Swagger Tools

go get -u github.com/swaggo/swag/cmd/swag

  1. Adicionar Swagger Annotations para descrever endpoints, parâmetros e respostas

Swagger Info Annotation:

No topo do arquivo main.go ou em um arquivo específico, adicione informações como versão, título e descrição.

// @title My API
// @version 1.0
// @description This is a RESTful API in Go using Swagger
// @contact.name API Support
// @contact.email support@example.com
// @host localhost:8000
// @BasePath /v1
Enter fullscreen mode Exit fullscreen mode

Operation Annotations:

Para cada endpoint, anote a function com os detalhes da requisição HTTP, path, e um resumo básico.

// @Summary Get a list of movies
// @Description Retrieves a list of movies
// @Tags movies
// @Accept json
// @Produce json
// @Success 200 {array} Movie
// @Router /movies [get]
func getMovies(w http.ResponseWriter, r *http.Request) {
    // code ...
}
Enter fullscreen mode Exit fullscreen mode

Parameter Annotations:

Descreva o path, a query, e o body da requisição.

// previous Operation Annotations...

// @Param id path string true "Movie ID"
// @Success 200 {object} Movie
// @Failure 404 {object} ErrorResponse
// @Router /movies/{id} [get]
func getMovie(w http.ResponseWriter, r *http.Request) {
    // code ...
}
Enter fullscreen mode Exit fullscreen mode

Response Annotations:

Defina a estrutura de responses retornadas pelos endpoints da API.

// Movie struct
// @Description structure of Movie
type Movie struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

// ErrorResponse struct
// @Description structure of ErrorResponse
type ErrorResponse struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
}
Enter fullscreen mode Exit fullscreen mode

Gerar a Documentação do Swagger:

Rode o comando swag init no diretório do projeto pra gerar o Swagger JSON e YAML baseados nas anotações. Se houverem mudanças nas anotações, esse comando deve ser rodado novamente.

swag init
Enter fullscreen mode Exit fullscreen mode

Suba a aplicação e entrar na Swagger UI (http://localhost:8000/swagger/index.html) pra interagir com a documentação.

Boas práticas de documentação:

  • Use linguagem descritiva e sucinta pra ajudar no entendimento da API.
  • Organize a ordem das anotações de forma lógica pra seguir um fluxo claro e padronizado, facilitando a manutenção.

Top comments (2)

Collapse
 
dvorlandi profile image
Davi Orlandi

Conteúdo muito interessante! Espero pelos próximos.

Collapse
 
lusqua profile image
Lucas Aguiar

Parabéns pelo primeiro artigo!! Esperando os próximos