Creating an API with Golang Gin Framework

Recently I made a blog post on how to create an API with only the Golang standard library. After doing that I thought it would be nice to make a more practical API with a Golang framework, I will be creating a to-do list API using Gin. All the code below, and more which didn’t make it into this post will be here Over the next few weeks I will be trying out all the hot frameworks and create a sample project in each, so subscribe to my mailing list if you want to be notified about those!


I decided to give Gin a shot because of how minimal it is, other frameworks like Revel have so much to it, I wanted to start with something less opinionated and more lightweight. Although it is lightweight, it has all the features you need when creating an API such as middleware, route grouping, panic recovery, and json validation.

Getting Started

The first step which I like to take when starting a new API in Golang is to define how the main.go should look. I always find this to be a natural place to start, and really clarify what needs to be built.

A large part of the setup is already handled since we’re using Gin but there is still a bit to setup. All we really need to do is:

  1. Initialize Gin
  2. Setup our database connection
  3. Initialize our controller
  4. Bind routes
  5. Run the server
  1. db, err := database.Connect(os.Getenv("PGUSER"), os.Getenv("PGPASS"), os.Getenv("PGDB"), os.Getenv("PGHOST"), os.Getenv("PGPORT"))if err != nil { log.Fatal("err", err)
  2. }
  3. todoController := controllers.NewTodoController(db)
  4. r := gin.Default()
  5. routes.CreateRoutes(r, todoController)
  6. r.Run()

It should look something like this! Now that we have defined our main.go file lets move on to the interesting stuff.

Database Connection

I created a small database connection function to keep the main.go file clean. I placed the file in utils/database/database.go which you can find here.

  1. connStr := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s",
  2. user, password, dbname, host, port)return sql.Open("postgres", connStr)

Todo Item Model

Before we start with the actual controller, we should figure out what our todo list item should look like. Most to do lists allow for items to have a title and description. You can also set them to be completed or not. Create models/item.go and make a struct like:

  1. type Item struct {
  2. ID int `json:"id"`
  3. Title string `json:"title"`
  4. Description string `json:"description"`
  5. Completed bool `json:"status"`
  6. }

The json:”id” is important for encoding items into JSON responses. It allows the object to be serialized in a friendly format.

Todo Controller

Okay, so now we need to create our todo controller. If we look back at main.go you will see we need a function NewTodoController(db) so lets start with that. All the function will do is return a pointer to a TodoController.

  1. func NewTodoController(db *sql.DB) *TodoController { return &TodoController{DB: db}
  2. }
  3. type TodoController struct {
  4. DB *sql.DB
  5. }

Notice the TodoController has a database, that is so we can access the database from inside our controllers via dependency injection.

Now let’s figure out what we want functions we want the TodoController to have. To make a todo list, you need a couple things:

  1. Create items
  2. Get items
  3. Update items
  4. Delete items
  5. Get individual item

So we need functions for each of these. I will not write them all out in this post, but to check out the other functions click here.

Creating the get items function is worth writing out here because it is the most complicated function, and it is located at controllers/todo_controller.go. There are a couple things to think about before you start this function. Most to-do lists allow you to see all your items or just the outstanding items. I believe that is an important feature to add, so let’s do that.

The first step when building this file out is to have a get parameter to specify if you want all the items or just the ones which aren’t completed.

  1. func (tc *TodoController) Items(c *gin.Context) { allStr := c.Query("all")
  2. all, err := strconv.ParseBool(allStr)
  3. if err != nil {
  4. all = true
  5. }

Once that is retrieved and validated, we want to get the items. We will make a repository in the next step, but for the time being, we’ll pretend we have a repository with the GetItems function. If there is an error when retrieving the items, we will log it, and return an empty internal server error. Gin has a couple functions for returning data to the client, you can pass strings, json, yaml, xml, etc… But for this project, I am just using strings and json. Strings are just used for empty responses (404, 500 status codes).

  1. items, err := repositories.GetItems(tc.DB, all) if err != nil { log.Println("err", err)
  2. c.String(http.StatusInternalServerError, "") return
  3. }

The last step is to return the todo list items. Gin makes this super easy with their JSON function. All we need to do is pass in the HTTP status code and an object for them to serialize. Under the hood they use the encoding/json package.

  1. c.JSON(http.StatusOK, items)
  2. }


In the controller we made an assumption about a repository, we are going to create that now. The file is located repositories/todo_repository.go. There are many more functions on the Github project, here.

First, we have to initialize some variables we will use later in the function and write the query. All we’re doing in this query is grabbing the data for our item model. There is no pagination here, but it would be simple to add.

  1. func GetItems(db *sql.DB, all bool) ([]*models.Item, error) { var rows *sql.Rows var err error
  2. query := ` select
  3. id,
  4. title,
  5. description,
  6. completed from
  7. items
  8. `

Next, we need to make an if else statement for the case that they only want outstanding items. If they don’t, we just get all the items in the database.

  1. if !all {
  2. query += "where completed = $1"
  3. rows, err = db.Query(query, all)
  4. } else {
  5. rows, err = db.Query(query)
  6. } if err != nil { return nil, err
  7. }

The final step in the function is to create the item list. We make an empty slice of items and then append an item for each row in the database. If there are any errors along the way, we return the error.

  1. items := make([]*models.Item, 0) for rows.Next() {
  2. var item models.Item
  3. err = rows.Scan(&item.ID, &item.Title, &item.Description, &item.Completed) if err != nil { return nil, err
  4. }
  5. items = append(items, &item)
  6. } return items, err
  7. }


The final and most important thing we need to do to finish off this API is to bind the controller to the API routes. Luckily, Gin makes this super easy. All we do is create a routes/routes.go file and bind them.

  1. func CreateRoutes(r *gin.Engine, tc *controllers.TodoController) {
  2. r.GET("/items", tc.Items)
  3. r.POST("/item", tc.Create)
  4. r.GET("/item/:itemID", tc.Get)
  5. r.PUT("/item/:itemID", tc.Update)
  6. r.DELETE("/item/:itemID", tc.Delete)
  7. }

Final Thoughts

This is my first exposure to the Gin framework, using it was pleasant, and it is a nice, intuitive, lightweight alternative to the standard library. I would definitely consider using this over the standard library due to the fact it cuts down the amount of code you write significantly. I’m not sure if it is better than using the gorilla toolkit but for those who just “want it to work,” while not feeling like a massive framework, this is for you.

Share this article

About Ryan McCue

Hi, my name is Ryan! I am a Software Developer with experience in many web frameworks and libraries including NodeJS, Django, Golang, and Laravel.

ft_authoradmin  ft_create_time2018-03-20 14:59
 ft_update_time2018-03-20 15:02