DEV Community

Cover image for Building API with Gin framework
Charles Otugeh
Charles Otugeh

Posted on

Building API with Gin framework

Building API with Gin Framework

Gin is one of the Golang framework. Procedure for create the framework.
on command line:
$ mkdir [directory name]* this the name of my backend repo.
$ cd to the directory
go mod init [directory]
add the following code into file main.go
...
package main // use pacage called main

import (
"net/http"
"github.com/gin-gonic/gin"
)

// Sample of items represents in the database model
// Item starts with uppercase so it is visible to other functions.
type Item struct {
ID string json:"id"
Name string json:"name" binding:"required"
Price double json:"price" binding:"required"
}

// In-memory data store
var items = []Item{
{ID: "1", Name: "Mechanical Keyboard", Price: 99.99},
{ID: "2", Name: "Wireless Mouse", Price: 49.99},
}

// Initialize the default Gin router with Logger and Recovery middleware
func main() {

router := gin.Default()

// Define routes retrieve(GET) and upload(POST)
router.GET("/items", getItems)
router.POST("/items", createItem)

// Start the server on port 8080
router.Run(":8080")
Enter fullscreen mode Exit fullscreen mode

}

// GET handler to fetch all items
func getItems(c *gin.Context) {
c.JSON(http.StatusOK, items)
}

// POST handler to add a new item with validation
func createItem(c *gin.Context) {
var newItem Item

// Bind JSON request body to newItem struct and validate
if err := c.ShouldBindJSON(&newItem); err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    return
}

items = append(items, newItem)
c.JSON(http.StatusCreated, newItem)
Enter fullscreen mode Exit fullscreen mode

}
NB: This is just the part of the Framework it not all the files.

Top comments (0)