Create a simple API with Gin

Danylo Bolshakov
4 min readApr 24, 2023

Gin is a high-performance HTTP web framework written in Golang (Go). Gin has a martini-like API and claims to be up to 40 times faster. Gin allows you to build web applications and microservices in Go. It contains a set of commonly used functionalities (e.g., routing, middleware support, rendering, etc.)

In this tutorial, we’ll create a simple Gin API for Albums. I took the idea from the official Gin tutorial from Go https://go.dev/doc/tutorial/web-service-gin, but I added PATCH and DELETE methods.

Step 1: Importing packages

Import Gin framework:

go get github.com/gin-gonic/gin

Import uuid for generate random ID:

go get github.com/google/uuid

So write this code at our main.go file:

package main

import (
"net/http"

"github.com/gin-gonic/gin"

"github.com/google/uuid"
)

Step 2: Create simple struct

Create album struct:

type album struct{}

Append to album struct, what’s we want get in json response:

type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}

Write data to album struct:

var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jere", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

Step 3: Routing

Routing in Gin it easy for understand

Create func main, where we’ll write our routing :

func main(){}

Create router :

func main() {
router := gin.Default()
}

Append router method and run server :

func main() {
// Create router
router := gin.Default()

// GET METHOD
router.GET("/albums", getAlbums)
router.GET("/albums/:id", getAlbumById)

// POST METHOD
router.POST("/albums", postAlbums)

// UPDATE METHOD
router.PATCH("/albums/:id", patchAlbumById)

// DELETE METHOD
router.DELETE("/albums/:id", deleteAlbumById)

// RUN SERVER
router.Run("localhost:8080")
}

Step 4 Get all albums

Create new func getAlbums, in this function we will get all albums from data :

func getAlbums(c *gin.Context) {
// Show list of albums
c.JSON(http.StatusOK, albums)
}

Its func take all data from albums and send in json format

Step 5: Post album

Create new func postAlbum, in this func we will create new album :

func postAlbum(c *gin.Context){
// Create new Variable
var newAlbum album

// Record the data that was transferred to us
if err := c.BindJSON(&newAlbum); err != nil{
return
}

// Generate random ID
newAlbum.ID = uuid.New().String()

// If the ID is already taken, generate a new one.
for _, a := range albums {
if a.ID == newAlbum.ID{
// Generate new random ID
newAlbum.ID = uuid.New().String()
return
}
}

// Append new Album to albums
albums = append(albums, newAlbum)

// Show new Album
c.JSON(http.StatusCreated, newAlbum)
}

Step 6: Get album by ID

Create new func getAlbumById, in this func we will create new album :

func getAlbumById(c *gin.Context){
// Get ID from param
id := c.Param("id")

// Find ID in struct
for _, a := range albums {
if a.ID == id{
// Response only album with request ID
c.JSON(http.StatusOK, a)
return
}
}

// Response if ID not found
c.JSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

Step 7: Patch album by ID

Create new func patchAlbumById, in this func we will patch album by ID :

func patchAlbumById(c *gin.Context){
// Get ID from param
id := c.Param("id")

// Find by ID
for i, a := range albums {
// Work only in we found ID in out struct
if a.ID == id {
// Create variable
var updatedAlbum album

// Bind updateAlbum ID albums struct
if err := c.BindJSON(&updatedAlbum);
err != nil{
// show error
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})

return
}

// Update the album fields that were included in the request body
if updatedAlbum.Title != "" {
albums[i].Title = updatedAlbum.Title
}

if updatedAlbum.Artist != "" {
albums[i].Artist = updatedAlbum.Artist
}

if updatedAlbum.Price != 0 {
albums[i].Price = updatedAlbum.Price
}

// Return the updated album
c.JSON(http.StatusOK, albums[i])
return
}
}

// If album not found
c.JSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

Step 8: Delete album by ID

Create new func deleteAlbumById, in this func we will delete album by ID :

func deleteAlbumById(c *gin.Context){
// Get album ID
id := c.Param("id")

// Range ID in struct
for i, a := range albums{
if a.ID == id {
// Delete album
albums = append(albums[:i], albums[i+1:]...)

// Show message for complete delete
c.JSON(http.StatusOK, gin.H{"message": "album deleted"})
return
}
}

c.JSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

Step 9: Run server

Lets try our api :

go run main.go

Just check API in Postman!

SUMMARY

We created a simple album API using Gin framework.

Thank you for the read that article!
You can buy me a coffee!

--

--

No responses yet