Implementing Swagger in Go Projects

Andhika Megantara
julotech
Published in
8 min readAug 12, 2023

--

When it comes to documenting & testing APIs in our App, it could be a messy and troublesome task for developers or QAs. Here, I will talk about why by simply utilizing Swagger, we could overcome this trouble!

Why we need Swagger in JULO?

We do know that when we’re working in a fast paced software development cycle, sometimes maintaining the API documentation is a messy & time consuming task to do. In JULO we mainly use Postman for our API documentation & testing tool, but we saw we’ve documented on Postman often quickly get left behind as we’re developing software features and evolving them.

We also know that as developers, we need faster testing tools for us to test our features that we built, because we do need to fill up almost everything (URLs, headers, and the payloads) when we’re doing testing using Postman.

This is why in our J360 project, JULO’s first microservices architecture approach, we implement Swagger integrated within our App with the help of Swaggo. With this strategy, we can easily build a Swagger documentation with just using annotation in our app and we can test and document our APIs with ease, fast, heavy customization and in tidy manners.

So implementing Swgger has solved two problems for us:

  • Standardized Interactive API Documentation
  • Easy API testing tools for Developers and QA Engineers

What is Swagger?

Swagger is a powerful yet easy-to-use suite of API developer tools for teams and individuals, enabling development across the entire API life cycle, from design and documentation to testing and deployment.

The idea of using a swagger is to:

  1. Standardized Documentation Format: Swagger (OpenAPI) provides a widely adopted and standardized format for documenting APIs. By using Swaggo to generate Swagger documentation, you ensure that your API documentation follows industry best practices and can be easily consumed by developers. Swagger’s structured format allows for clear and consistent documentation, making it easier for developers to understand and interact with your API.
  2. Interactive Documentation Experience: Swagger UI, which can be integrated with Swaggo, offers an interactive and user-friendly interface for exploring and testing APIs. It provides an automatically generated interface that allows developers to navigate through endpoints, view request/response examples, and even execute API requests directly from the documentation. This interactive experience improves developer productivity and accelerates API adoption.
  3. Automatic and Up-to-Date Documentation: Swaggo automates the process of generating API documentation from your Go code. This automation saves time and effort, as you don’t need to manually maintain separate documentation files. Swaggo extracts information directly from your codebase, including endpoint details, request/response models, and annotations. This approach ensures that your documentation stays up to date as your code evolves, reducing the chances of inconsistencies between your code and documentation.

How to Integrate Swagger with Go Projects

There is actually many ways to integrate swagger into our Go projects, the most popular way is by using go-swagger or swag. In this read, I will use Swag because in my opinion it’s the simplest way to integrate swag into our projects.

First thing first, we need to download & install the Swag in our local machine. Oh BTW, we do need a Go version 1.17 or newer.

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

After all of the packages installed successfully, now we can run

swag init

That command will generate 1 directory named docs, that is consisting of 3 files.

So what is actually that 3 files for?

That 3 files can be used with Swagger UI or other Swagger-compatible tools to visualize and explore your API documentation. They allow developers to understand your API’s structure, endpoints, request/response formats, and any additional details you’ve provided.

To generate these files, you typically use Swaggo’s command-line interface (CLI) or integrate it into your build process. Swaggo provides various annotations and tags that you add to your Go code to specify how your API should be documented. The CLI tool then parses your code, extracts the relevant information, and generates the documentation files based on that information.

  1. docs.go: This file contains the generated documentation in Go code format. It includes structs and functions that describe your API endpoints, their parameters, response models, and other relevant information.
  2. swagger.json: This file is a JSON representation of your API documentation in the Swagger format (also known as OpenAPI specification). It provides a standardized way to describe your API endpoints, their inputs, outputs, and other metadata.
  3. swagger.yaml: This file is similar to swagger.json but is written in YAML format instead of JSON. It serves the same purpose of documenting your API in the Swagger format, but in a human-readable format.

So how does this works basically?

Swaggo provides a set of annotations and tags that you can add to your Go code to customize and fine-tune your API documentation. These annotations allow you to provide additional information, such as descriptions, example values, validation rules, and more.

Then, the annotations you add to your Go code will be parsed by Swaggo, which then writes the relevant information into the three files it generates:

Here’s how the annotations are written into each file:

  1. docs.go:
  • Swaggo extracts the annotations from your Go code and generates Go code in the docs.go file. The generated Go code typically includes structs and functions that describe your API endpoints, request/response models, and other metadata.
  • Annotations such as @Summary, @Description, @Tags, @Param, @Success, and @Failure are used to provide descriptions, summary information, tags, parameter details, success/failure responses, and other relevant information for each API endpoint.
  • The generated Go code serves as self-documenting code that can be compiled and used within your Go project.

2. swagger.json:

  • Swaggo converts the information extracted from your code, including annotations, into the Swagger JSON format.
  • Each API endpoint is represented as an object within the paths section of the JSON file. The annotations are mapped to corresponding properties in the Swagger JSON structure.
  • For example, the @Summary annotation becomes the summary field, the @Description annotation becomes the description field, and so on.
  • The generated swagger.json file includes information about API endpoints, their methods, paths, parameters, responses, models, and other relevant metadata.

3. swagger.yaml:

  • Similar to swagger.json, Swaggo converts the extracted information and annotations into the Swagger YAML format.
  • The annotations are mapped to corresponding properties in the YAML structure.
  • The generated swagger.yaml file includes the same information as swagger.json but in a human-readable YAML format.

Both the `swagger.json` and `swagger.yaml` files can be used with Swagger UI or other Swagger-compatible tools to visualize and explore your API documentation.

By leveraging the annotations in your Go code, Swaggo automates the process of generating accurate and up-to-date API documentation in multiple formats, providing developers with clear and consistent documentation for your API.

Here is the full declarative comment format used in Swaggo.

https://github.com/swaggo/swag#declarative-comments-format

So what is the output?

That generated documentation files will be compiled and will be served a html file when our app is running and we can access it directly within our app just like this:

As you can see, we will have an up-to-date API Documentations of our app.

not only that!

we can also hit our API with dedicated header, request body, etc that we have pre-configured before in our annotations.

And also not only that!

we can also add a basic customizable authorization for our API

Basic authentication is a simple authentication scheme where the client sends its credentials (username and password) in the HTTP header using base64 encoding. However, it's essential to note that basic authentication is generally considered less secure compared to other authentication mechanisms like OAuth2.

To fully enable basic authentication in our Go application using Swaggo, we need to take additional steps beyond just adding this comment. We will need to implement the authentication logic in our API handlers to check the incoming credentials and authorize access to the requested resource.

This will come in handy when we want to smoke test the functionality and even the performance of our APIs.

Conclusion:

  • Swaggo provides interactive API explorer that allows developers and QAs to try out API endpoints directly from the Swagger documentation. This feature enables quick testing and debugging of endpoints, making it easier for developers experiment with your API without having to write code from scratch, and QAs to do testing of the APIs.
  • But note that using swagger will not be equally customizable as postman / insomnia when being used to test APIs. Because on the other hand, Postman is a comprehensive API development platform that offers a wider range of features, including API testing, request and response customization, automated testing, and team collaboration.
  • Postman is designed to provide a powerful and flexible environment for API development, testing, and monitoring, while Swagger main focus is on API documentation and providing an interactive API explorer.

--

--

Andhika Megantara
julotech

I am a full-time Software Engineer who likes to travel