Create Golang API Doc with Swag

Aditya Rama
5 min readJan 31, 2021

--

We’re going to create a simple API doc with the help of https://github.com/swaggo/swag library. It supports several golang framework such as gin, echo, fiber, flamingo, net/http, etc. In a nutshell you need to install it first (for generating via CLI), write some comments metadata in your API / handler / controller, generate and done!

Image example from the github documentation

Creating the API

First let us create some simple API using gin framework. We’re initiating an API group of “/api/v1/user” in which consists of two endpoint

  1. Get user detail based on id
  2. Post and create new user based on JSON body sent by request

After that, we’re going to write some code in the handler package.

The GetUser handler will get id from url param and fetch the user detail from DB for example, for simplification in this writing, we’ll simulate to return a user object except for id 456 that will return an error message of failed to connect to DB (just an example). Please take a note that we have another package of models that contains all of our “entity” struct.

The second handler is CreateUser in which will get user parameter data from JSON body request and saving it while returning “new inserted id” and the error, in which we mock it as nil for simplification.

In Addition, you might be wondering what response.FailResponse and SuccessResponse are doing. Both are basically just a wrapper of returning JSON response with unified response struct object.

We separate the bad request and internal server error response struct for different “example” tag, in which for the swagger example later

The models package consists of two structs.

We create the UserCreateParam differently and not using User model for the Create API request param is for the API documentation to omit the ID from the example request (will be shown later).

Integrating with Swaggo

Following the instruction on the github page (the documentation is pretty good), first we need to install it by using:

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

Then we’re going to add some annotation and import the swaggo library in the main.go file.

Mostly the annotation in here is a link of documentation related on like Title, description, link of your email or website or contact support, etc. Two important thing is the host and BasePath that will show your host and API base path.

You can try to generate the file using swag init command. Then run the app, and open your browser to http://localhost:8080/swagger/index.html and you will see something like this.

Now, we’re going to add annotation in our handler files.

Summary and Description are just a brief explanation of what the API does. ID is a unique identifier and up to you, Accept and Produce are the MIME type like json,xml,html,png,x-www-form-urlencoded, etc (more complete list on the github documentation). Param is the list of parameter it accepts with the format of `@Param name type data_type is_mandatory? comment attribute(optional)`. Param types supported path, query, header, body, and FormData. Success and Failure tag determine success / failure example response, both format are the same `@Success/@Failure returnCode {param_type} data_type comment`. For example we can use “object” as the param_type and we’re pointing the data_type for both API to use JSONResult struct on our response package. We can also identify the field “data” to use User models, or UserCreateParam models. In a nutshell, you can use any defined struct for the data_type. Router tag is self explanatory for the API route with the http method.

Try to do “swag init” again and re-run your application.

As we can see, both our API are created, let see the detail of your GET user detail.

It’s not just a documentation, we can use “try it out” our API real time, try to put the id of 9999 then hit execute. It will hit our API and show the response.

Now, let try our error mocking for id 456, by using that as an account ID

It shows as we expected from our code that if we’re using id 456 we will throw an example of error DB. Last, let us try with the Create User API and try it out too.

It works like a charm, it returned the user we created a long side with “the new created id”.

So if you’re searching for simple API doc for golang, I recommend to use this one for its simplicity.

--

--