Building a REST API with GORM, Gin Framework, and PostgreSQL in Go.

Building a REST API with GORM, Gin Framework, and PostgreSQL in Go.

ยท

3 min read

The combination of GORM, a powerful ORM library for Go, along with Gin, a high-performance web framework, and PostgreSQL, a robust relational database, forms a solid foundation for developing RESTful APIs in Go. In this detailed tutorial, we'll create a practical example showcasing the integration of GORM, Gin, and PostgreSQL to build a fully functional REST API in Go.

Prerequisites

Ensure you have the following prerequisites:

  • Go installed on your machine

  • PostgreSQL installed and running

  • Basic knowledge of Go, SQL, and RESTful APIs

Setting Up the Project

Initializing the Project

Start by initializing a new Go module:

go mod init your_project_name

Install the required dependencies:

go get -u github.com/gin-gonic/gin
go get -u github.com/jinzhu/gorm
go get -u github.com/jinzhu/gorm/dialects/postgres

Creating Database

Create a PostgreSQL database and define a users table with columns id, name, and email.

Building the REST API

Setting Up Gin Server

Create a new Go file, e.g., main.go, and set up the Gin server:

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

var (
    db *gorm.DB
)

func init() {
    var err error
    dsn := "postgresql://user:password@localhost/database_name?sslmode=disable" // Update with your database credentials
    db, err = gorm.Open("postgres", dsn)
    if err != nil {
        panic("failed to connect to database")
    }

    // Auto migrate the User model
    db.AutoMigrate(&User{})
}

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

func getUsers(c *gin.Context) {
    var users []User
    db.Find(&users)
    c.JSON(200, users)
}

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

    // Routes
    r.GET("/users", getUsers)

    // Start server
    r.Run(":8080")
}

Implementing API Endpoints

GET Users

The GET /users endpoint retrieves all users from the database:

func getUsers(c *gin.Context) {
    var users []User
    db.Find(&users)
    c.JSON(200, users)
}

POST User

The POST /users endpoint creates a new user:

func createUser(c *gin.Context) {
    var user User
    if err := c.BindJSON(&user); err != nil {
        c.AbortWithStatus(400)
        return
    }
    db.Create(&user)
    c.JSON(201, user)
}

GET User by ID

The GET /users/:id endpoint fetches a user by ID:

func getUserByID(c *gin.Context) {
    id := c.Param("id")
    var user User
    db.First(&user, id)
    c.JSON(200, user)
}

DELETE User by ID

The DELETE /users/:id endpoint deletes a user by ID:

func deleteUserByID(c *gin.Context) {
    id := c.Param("id")
    var user User
    db.Delete(&user, id)
    c.Status(204)
}

Registering API Endpoints

Add the new API endpoints to the Gin server:

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

    // Routes
    r.GET("/users", getUsers)
    r.POST("/users", createUser)
    r.GET("/users/:id", getUserByID)
    r.DELETE("/users/:id", deleteUserByID)

    // Start server
    r.Run(":8080")
}

Testing the API

Build and run the application:

go run main.go

Testing Endpoints

Conclusion

Combining GORM, Gin, and PostgreSQL enables the creation of efficient and scalable RESTful APIs in Go. This example demonstrates the integration of GORM with Gin and PostgreSQL to create a fully functional API with endpoints for user management.

Leveraging this example, developers can expand functionality, and implement authentication, validation, and additional endpoints, harnessing the capabilities of GORM and Gin to build robust and efficient APIs in Go.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/@maheshwarligade

https://techwasti.com/series/spring-boot-tutorials

https://techwasti.com/series/go-language

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

ย