Go-Swagger : Structuring & Implementing APIs
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:
e_food_api.go
This file contains url path and its
handler
underinitHandlerCache()
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 hasHandler(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 ?
- We created a struct
menuListImpl
which implementsCategoryListHandler
by implementingHandler()
function. TheHandler()
function will be called with allparams
as defined using swagger generated code. - We created
NewMenuCategoryListHandler()
which returns an instance ofmenuListImpl
(that has implemented the interface) - As defined in
swagger.yaml
file, we have access to themodels.Categories
and its associated attributes. We use thismodels.Categories
to create a return object , which is what we defined as return type inyaml
file:
responses:
200:
description: 'List of Categories'
schema:
$ref: '#/definitions/Categories'
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.