Go-Swagger : Structuring & Implementing APIs

Shashank Vivek
3 min readJul 20, 2020

In my previous article, I have provided an introduction to go-swagger. I covered on how to setup a project and create an endpoint using swagger.yaml file.

In this article, I’ll explain the necessary files that we should know about and implementation of /categories endpoint. Before we proceed, I’ll suggest you to take a look sequentially at below swagger generated files:

  1. e_food_api.go

This file contains url path and its handler under initHandlerCache() function

2. configure_e_food.go

In this file, we need to focus on configureAPI(api *operations.EFoodAPI) which contains the assignment of API handler with our own business implementation

3. category_list.go

It contains CategoryListHandler interface, that has Handler(CatergoryParams) middleware.Responder which will be implemented by the developer

Take your time and get familiar with these files, some of these files will be overwritten every time you’ll run swagger command for swagger.yaml . The swagger adds below comments in such files:

// Code generated by go-swagger; DO NOT EDIT.

Step 1:

Create a folder named “handlers” and a file named get_categories.go as shown below

Step 2:

In our next step, we’ll write below code into the file named get_categories.go

So, what all things happened here ?

  1. We created a struct menuListImpl which implements CategoryListHandler by implementing Handler() function. The Handler() function will be called with all params as defined using swagger generated code.
  2. We created NewMenuCategoryListHandler() which returns an instance of menuListImpl (that has implemented the interface)
  3. As defined in swagger.yaml file, we have access to the models.Categories and its associated attributes. We use this models.Categories to create a return object , which is what we defined as return type in yaml file:
responses: 
200:
description: 'List of Categories'
schema:
$ref: '#/definitions/Categories'
200 response

4. We return a success (200) response WithPayload() . Please note that the responseVal is the same object structure that we defined in yaml file. We can also return 500 (server error) as below:

It’ll contain string because as response because that’s what we wrote in swagger.yaml

500:  
description: Server Error
schema:
type: string

Step 3:

In the last step, we want to integrate this handler so that it’ll be called when the endpoint is hit. To do that, we need to go back to configure_e_food.go file and below code in configureAPI() function:

api.MenuCategoryListHandler = handlers.NewMenuCategoryListHandler()

The final code should look like:

That’s it !! GO ahead and run the app using below command and make a GET request to /categories .

go run cmd\e-food-server\main.go --scheme http --port=8080

If you find this article helpful, please 👏 clap 👏 few times to encourage me 🐼 to write more.

--

--