Logo

dev-resources.site

for different kinds of informations.

Go: CRUD API using Gin Framework

Published at
6/5/2023
Categories
go
programming
gin
tutorial
Author
ankitmalikg
Categories
4 categories in total
go
open
programming
open
gin
open
tutorial
open
Author
11 person written this
ankitmalikg
open
Go: CRUD API using Gin Framework

Introduction:

Building APIs that perform CRUD (Create, Read, Update, and Delete) operations is a common requirement for many web applications. The Gin framework is a popular choice for building APIs in Go, as it provides a robust set of features and is easy to use. In this article, we'll walk through how to create a basic CRUD API using the Gin framework and the Go programming language.

Installation

To install the Gin framework. We can do this by running the following command in the terminal:

go get -u github.com/gin-gonic/gin

Enter fullscreen mode Exit fullscreen mode

Example

Let's look at an example using a User object for CRUD api with the help of Gin framework.

package main

import (
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
)

type User struct {
    ID       int    `json:"id"`
    Username string `json:"username"`
    Email    string `json:"email"`
}

var users []User

func main() {
    r := gin.Default()

    // Initialize the users variable
    users = []User{
        {ID: 1, Username: "user1", Email: "[email protected]"},
        {ID: 2, Username: "user2", Email: "[email protected]"},
    }

    // Define routes for user API
    r.GET("/users", GetUsers)
    r.GET("/users/:id", GetUserByID)
    r.POST("/users", CreateUser)
    r.PUT("/users/:id", UpdateUser)
    r.DELETE("/users/:id", DeleteUser)

    r.Run(":8080")
}

// Get all users
func GetUsers(c *gin.Context) {
    c.JSON(http.StatusOK, users)
}

// Get a single user by ID
func GetUserByID(c *gin.Context) {
    id := c.Param("id")

    for _, user := range users {
        if strconv.Itoa(user.ID) == id {
            c.JSON(http.StatusOK, user)
            return
        }
    }

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

// Create a new user
func CreateUser(c *gin.Context) {
    var user User

    if err := c.BindJSON(&user); err != nil {
        c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    user.ID = len(users) + 1
    users = append(users, user)

    c.JSON(http.StatusCreated, user)
}

// Update an existing user
func UpdateUser(c *gin.Context) {
    id := c.Param("id")

    for i, user := range users {
        if strconv.Itoa(user.ID) == id {
            var updatedUser User

            if err := c.BindJSON(&updatedUser); err != nil {
                c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
                return
            }

            updatedUser.ID = user.ID
            users[i] = updatedUser

            c.JSON(http.StatusOK, updatedUser)
            return
        }
    }

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

// Delete a user
func DeleteUser(c *gin.Context) {
    id := c.Param("id")

    for i, user := range users {
        if strconv.Itoa(user.ID) == id {
            users = append(users[:i], users[i+1:]...)
            c.JSON(http.StatusOK, gin.H{"message": "User deleted successfully"})
            return
        }
    }

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


Enter fullscreen mode Exit fullscreen mode

In this example, the User struct has three fields: ID, Username, and Email. The HTTP handlers for the CRUD operations are very similar to the ones in the previous example, except they operate on the users slice instead of the books slice.

Benefits of Using Gin framework

There are several benefits to using the Gin framework for building web applications and APIs in Go:

  • Fast and Lightweight: Gin is designed to be lightweight and performant, making it an excellent choice for building high-performance web applications and APIs.
  • Easy to Use: Gin's simple and intuitive API makes it easy to get started with, even if you're new to Go or web development.
  • Robust Routing: Gin provides a powerful and flexible routing engine that allows you to define your routes using a variety of HTTP methods, URL patterns, and middleware functions.
  • Middleware Support: Gin comes with a built-in middleware stack that provides support for things like logging, error handling, authentication, and more.
  • Scalable: Gin is designed to be scalable and can handle large volumes of traffic with ease. It's also highly customizable, making it easy to add additional features and functionality as your application grows.

Conclusion:

The Gin framework is a powerful tool for building APIs in Go, and it makes it easy to create CRUD APIs that perform the basic operations required by most web applications. In this article, we've demonstrated how to use Gin to create a basic CRUD API for managing users. With the code examples provided, you should have a good starting point for building your own APIs using the Gin framework.

gin Article's
30 articles in total
Favicon
Developing a Simple RESTful API with Gin, ginvalidator, and validatorgo
Favicon
Go's Concurrency Decoded: Goroutine Scheduling
Favicon
🚀 Building a RESTful API in Go: A Practical Guide
Favicon
A Deep Dive into Gin: Golang's Leading Framework
Favicon
Building a Blog API with Gin, FerretDB, and oapi-codegen
Favicon
How to enable hot reload in your Gin project
Favicon
Implementing an Order Processing System: Part 1 - Setting Up the Foundation
Favicon
Gin and router example
Favicon
How to Upload Images to AWS S3 with Golang
Favicon
Basic CRUD Operations Using Golang, Gin Gonic, and GORM
Favicon
Simplifying User Management with GIN and MongoDB
Favicon
Gin + Gorm Practical Guide, Implementing a Simple Q&A Community Backend Service in One Hour
Favicon
A Beginner-friendly Approach to Developing a REST API with Go, Gin and MSQL
Favicon
Cara menggunakan Cobra untuk menjalankan server Golang Gin
Favicon
A Beginner-friendly Approach to Developing a REST API with Go and Gin
Favicon
Easily build a simple and reliable ordering system in an hour using go efficiency tools
Favicon
Example 5, Automatically generate grpc gateway service project code, easy to achieve cross-service grpc calls
Favicon
Example 3, Automatically generate generic web service (gin) project code, increasing development efficiency by at least 1x
Favicon
Example 6, Build a simple golang e-commerce microservices framework step by step using tool
Favicon
Building a simple API with Golang using Gin-gonic
Favicon
Golang Web API: Project configuration management using Viper
Favicon
Golang Web API Course: Create starter project with a simple health check endpoint
Favicon
API validation in Gin: Ensuring Data Integrity in Your API
Favicon
Using the tool to complete the conversion of a community back-end single service to a microservice cluster in one day
Favicon
A secret weapon to improve the efficiency of golang development, a community backend service was developed in one day
Favicon
Play Microservices: Api-gateway service
Favicon
Set up a Stripe Checkout REST API (+ metadata) using Go and Gin Framework.
Favicon
Go: CRUD API using Gin Framework
Favicon
Example 1, Automatically generate a complete gin+gorm+redis+CRUD web service project without writing a line of Go code
Favicon
Not a Go LiveView developer yet? Try to guess what this code is doing, though.

Featured ones: