Building a Golang RESTful API with Gin GORM and MySQL: Emphasizing Code Reusability

Building a Golang RESTful API with Gin GORM and MySQL: Emphasizing Code Reusability

Last updated on August 5th, 2023

Introduction Golang RESTful API with Gin GORM and MySQL

Golang RESTful API with Gin GORM and MySQL: Gin is a strong and compact web framework for Golang, and GORM is a well-known object-relational mapping package that makes it easier to connect with databases. In this tutorial, we’ll show you how to build a RESTful API with Gin, GORM, and a MySQL database. To make your programme more scalable and maintainable, we’ll also concentrate on preserving code reuse.

Prerequisites

Before we proceed, ensure you have the following installed on your machine:

  1. Go programming language: official website
  2. MySQL database: Official Website
  3. Gin and GORM packages: Open your terminal and run the following commands:
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql

Setup Steps

  1. Create a new Golang project

Open your terminal and create a new folder for your project. Inside the folder, create a new Go module:

mkdir my-gin-api
cd my-gin-api
go mod init my-gin-api
  1. Import required packages

Next, open your main.go file and import the necessary packages:

package main

import (
    "github.com/gin-gonic/gin"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)
  1. Create database connection

Now, let’s create a function to establish a connection to the MySQL database. Replace the connection details with your MySQL credentials:

func connectDB() (*gorm.DB, error) {
    dsn := "user:password@tcp(127.0.0.1:3306)/database_name?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
        return nil, err
    }
    return db, nil
}
  1. Define a reusable model structure

To ensure code reusability, let’s create a separate file called models.go to define the model structure. For example, if we’re building a simple user application, the structure could be:

package main

import "gorm.io/gorm"

type User struct {
    gorm.Model
    Name  string `json:"name"`
    Email string `json:"email"`
}
  1. Implement CRUD operations

Now, let’s create a file named crud.go where we’ll implement the CRUD operations:

package main

import (
    "github.com/gin-gonic/gin"
    "gorm.io/gorm"
)

// Function to create a new user
func createUser(c *gin.Context) {
    db, err := connectDB()
    if err != nil {
        c.JSON(500, gin.H{"error": "Database connection error"})
        return
    }
    defer db.Close()

    var user User
    if err := c.ShouldBindJSON(&user); err != nil {
        c.JSON(400, gin.H{"error": "Invalid data"})
        return
    }

    result := db.Create(&user)
    if result.Error != nil {
        c.JSON(500, gin.H{"error": "Failed to create user"})
        return
    }

    c.JSON(201, user)
}

// Function to get all users
func getUsers(c *gin.Context) {
    db, err := connectDB()
    if err != nil {
        c.JSON(500, gin.H{"error": "Database connection error"})
        return
    }
    defer db.Close()

    var users []User
    db.Find(&users)

    c.JSON(200, users)
}

// Function to update a user
func updateUser(c *gin.Context) {
    db, err := connectDB()
    if err != nil {
        c.JSON(500, gin.H{"error": "Database connection error"})
        return
    }
    defer db.Close()

    id := c.Param("id")
    var user User
    db.First(&user, id)

    if err := c.ShouldBindJSON(&user); err != nil {
        c.JSON(400, gin.H{"error": "Invalid data"})
        return
    }

    db.Save(&user)

    c.JSON(200, user)
}

// Function to delete a user
func deleteUser(c *gin.Context) {
    db, err := connectDB()
    if err != nil {
        c.JSON(500, gin.H{"error": "Database connection error"})
        return
    }
    defer db.Close()

    id := c.Param("id")
    var user User
    db.Delete(&user, id)

    c.JSON(200, gin.H{"message": "User successfully deleted"})
}
  1. Implement routing

Now, let’s define the routes in the main.go file to call the CRUD functions:

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

    // Routes
    app.POST("/users", createUser)
    app.GET("/users", getUsers)
    app.PUT("/users/:id", updateUser)
    app.DELETE("/users/:id", deleteUser)

    // Start server
    app.Run(":3000")
}
  1. Run the application

Finally, start the server by running:

go run .

Application Outputs and Descriptions

  1. Creating a New User:

To create a new user, make a POST request to the “/users” endpoint with a JSON payload containing the user details. For example:

Request:

POST /users
{
    "name": "John Doe",
    "email": "john.doe@example.com"
}

Response:

Status: 201 Created

{
    "ID": 1,
    "CreatedAt": "2023-07-25T10:00:00Z",
    "UpdatedAt": "2023-07-25T10:00:00Z",
    "DeletedAt": null,
    "name": "John Doe",
    "email": "john.doe@example.com"
}
  1. Retrieving All Users:

To retrieve all users, make a GET request to the “/users” endpoint. The server will respond with a JSON array containing all the users.

Request:

GET /users

Response:

Status: 200 OK

[
    {
        "ID": 1,
        "CreatedAt": "2023-07-25T10:00:00Z",
        "UpdatedAt": "2023-07-25T10:00:00Z",
        "DeletedAt": null,
        "name": "John Doe",
        "email": "john.doe@example.com"
    },
    {
        "ID": 2,
        "CreatedAt": "2023-07-26T08:30:00Z",
        "UpdatedAt": "2023-07-26T08:30:00Z",
        "DeletedAt": null,
        "name": "Jane Smith",
        "email": "jane.smith@example.com"
    }
]
  1. Updating a User:

To update a user, make a PUT request to the “/users/{id}” endpoint, where “{id}” is the ID of the user you want to update. Provide a JSON payload with the updated user details.

Request:

PUT /users/1
{
    "name": "John Doe Updated",
    "email": "john.updated@example.com"
}

Response:

Status: 200 OK

{
    "ID": 1,
    "CreatedAt": "2023-07-25T10:00:00Z",
    "UpdatedAt": "2023-07-27T15:45:00Z",
    "DeletedAt": null,
    "name": "John Doe Updated",
    "email": "john.updated@example.com"
}
  1. Deleting a User:

To delete a user, make a DELETE request to the “/users/{id}” endpoint, where “{id}” is the ID of the user you want to delete.

Request:

DELETE /users/2

Response:

Status: 200 OK

{
    "message": "User successfully deleted"
}

Conclusion

In this article, we demonstrated how to build a Golang RESTful API using Gin and GORM with a MySQL database. By creating a reusable model structure and separating the database logic, we emphasized code reusability, making your application more scalable and maintainable. The step-by-step setup instructions should help you easily set up the project on your own machine. Now you can build efficient and powerful APIs with Golang, Gin, and GORM. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *