Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Medium

Gin Getting Started with GORM (Golang's ORM library)

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Hey Ninjas, today we will use a speedy web framework (Gin) of a trendy procedural programming language (Go) along with GORM to build a RESTful API. Meaning combining a high-performance programming language with a fast web framework. So we can build a high-performance RESTful API. This way, we will help you understand GORM (Golang’s ORM library).

Introduction

Let's start with defining Gin, then we will define REST API and GORM. Then, we will read about the GORM Guides and learn the steps to start with GORM. After that, we will learn how to build a REST API with GORM.

What is Gin?

Gin

Gin is an HTTP-based web framework written in Golang or Go programming language. Generally, we use a web framework during development to simplify our code using standardized codes. Gin is a high-speed web framework, so we use it when we need high performance and productivity.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is RESTful API?

RESTful API

REST is the acronym for Representational State Transfer, and API stands for Application Programming Interface. REST is an architectural style that imposes conditions on how an API should work. An API is a set of rules on how applications can connect and communicate with each other. So, a RESTful API is an API that conforms to the design principles of the REST. We use RESTful APIs because of their three major benefits Scalability, flexibility, and independence. 

What is GORM? 

GORM stands for Golang’s ORM library. So, to understand GORM lets us first understand what ORM library is. ORM means Object-Relational Mapping. it is a technique through which we query and manipulate data from a relational database using Object-Oriented programming. A Relational Database stores information in a database in rows and columns. 

GORM

The Go language has types and methods and, thus, allows us to program in an Object-Oriented manner. Therefore, GORM uses Golang to query and manipulate the relational database.

The Golang uses types that can satisfy many interfaces at once. This also resolves the traditional complexities of multiple inheritance and ambiguity. The method dispatch is made much easier, and we can achieve dynamic dispatch just by the function's name.

GORM is developer friendly and supports

  • Composite primary keys
  • Polymorphism
  • SQL builder
  • Plugins and callbacks
  • Hooks (Before/After Create/Save/Update/Delete/Find)
  • CRUD (Create, Read, Update, Delete) interface
  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance)
  • Official support to MySQL, SQLLite, and PostGres.

Steps to quick-start with GORM

We follow the following steps to quick-start with GORM. First, we install the GORM and the driver for our database; after that, we can quick-start.

Installation

We need to install the GORM and the driver for the database we are using.

Command:

go get -u gorm.io/gorm
go get -u gorm.io/driver/sqlite

Quick Start

After installation of the GORM, we do a quick start to our project and check whether everything is working or not. We have to do the following things in the order written. 

  • Declare Models 
  • Connect to the database
  • Creating a record
  • Reading a record
  • Updating a record
  • Deleting a record

 

Let us see an example.

package main

import (
	"gorm.io/gorm"
	"gorm.io/driver/sqlite"
)

type TestModel struct {
	gorm.Model
  	Code  string
  	Price uint
}

func main() {
  	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
  	if err != nil {
    	panic("failed to connect database")
  	}

  	// Migrate the schema
  	db.AutoMigrate(&TestModel{})

  	// Create
  	db.Create(&TestModel{Code: "A1", Price: 500})

	// Read
  	var testModel TestModel
  	// find testModel with integer primary key
  	db.First(&testModel, 1) 
  	// find testModel with code A1
  	db.First(&testModel, "code = ?", "A1") 

  	// Update - update testModel's price to 1000
  	db.Model(&testModel).Update("Price", 100)
  	// Update - update multiple fields
  	db.Model(&testModel).Updates(TestModel{Price: 1000, Code: "B1"})
	
	// Delete - delete testModel
  	db.Delete(&testModel, 1)
}

Building REST API with GORM

In this section, we will learn how to build a RESTful API with Gin and GORM using an example of a library. 

Setting up the environment

Our first step will be to initialize a new Go module to manage our dependencies. After this, we will install Gin and GORM.

go mod init
go get github.com/gin-gonic/gin gorm.io/gorm

 

After the installation is complete, we get two files in our project folder, namely, “go.mod” and “go.sum”. These files contain all pieces of information about the packages we installed. 

Our desired file structure will be

ProjectLibrary

  • controllers
    • books.go
  • models
    • bookModel.go
    • database.go
  • main.go
  • go.mod
  • go.sum

Setting up the server

We will start setting up our server using the file main.go. First, we will create a hello world to test the server. Inside the file, we first need to declare the main function. This main function is triggered whenever we run our application.

Now we will initialize a new gin router. We need to specify two things, the endpoint, and the handler, for defining a route. We can send many different kinds of responses to the client, but it is a general practice to give responses in JSON format while using the RESTful APIs. So, to accomplish this, we require an HTTP status code. Let us see what our main.go code will look like.

package main

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

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

  	r.GET("/", func(c *gin.Context) {
    	c.JSON(http.StatusOK, gin.H{"data": "hello world"})    
  	})

  	r.Run()
}

Setting up the database

For setting up the database, the first thing we do is the creation of database models. So, we will create a model named BookModel. Each book will have a unique id (acting as the primary key), a title, and an author. 

// models/bookModel.go

package models

type BookModel struct {
  	ID     uint   `json:"id" gorm:"primary_key"`
  	Title  string `json:"title"`
  	Author string `json:"author"`
}

 

After making the database models, now our next step is connection. We need to connect the server to the database. So, we will create a function ConnectDatabase() for the same. Since we are using SQLite in this example, we need to import the respective driver for it.

We are checking if the connection is successful; if not successful, we will show the error message and terminate the program. 

After that, we will migrate the database schema. Then, we store the database instance in the DB variable. 

// models/database.go

package models

import (
  	"gorm.io/gorm"
  	_ "gorm.io/driver/sqlite"
)

var DB *gorm.DB

func ConnectDatabase() {
	database, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})

	if err != nil {
		panic("Failed to connect to database!")
	}

	database.AutoMigrate(&BookModel{})

	DB = database
}

 

After completing the connection function, we need to call this function in the main.go file.

Setting up the RESTful routes

After connecting to the database successfully, we need to set up the RESTful routes for the CRUD operations. 

Inside the “controllers” directory, we will create a file for the routes. Let us name it books.go; in this file, we have to create separate functions for creating, displaying, updating, and deleting records from the database.

Create book function

For this first we have to make a struct 

type CreateBookInput struct {
	Title  string `json:"title" binding:"required"`
	Author string `json:"author" binding:"required"`
}

 

Then we will use this struct in the function.

// POST /books
// Create new book
func CreateBook(c *gin.Context) {
	// Validating input
	var input CreateBookInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}


	// Creating book
	book := models.BookModel{Title: input.Title, Author: input.Author}
	models.DB.Create(&book)


	c.JSON(http.StatusOK, gin.H{"data": book})
}

 

In the same way, we can create functions for updation, deletion, and display.\

Check out this article - Compile Time Polymorphism

Frequently Asked Questions

What is Gin?

Gin is an HTTP-based web framework written in Golang or Go programming language. Gin is a high-speed web framework, so we use it when we need high performance and productivity.

What is GORM?

GORM stands for Golang’s ORM library. ORM means Object-Relational Mapping; it is a technique through which we query and manipulate data from a relational database using Object-Oriented programming.

What is RESTful API?

RESTful API is made up of two words REST and API. REST is the acronym for Representational State Transfer, and API stands for Application Programming Interface. A RESTful API is an API that conforms to the design principles of the REST.

What is GORM used for?

We primarily use GORM because it provides CRUD operations, and it can also be used for the initial migration and creation of the database schema.

Conclusion

In this article, you all learned about the GORM. We started with knowing what Gin is and then learned about RESTful API. After this, we learned what Gin-GORM is. Then, we learned how to quick-start with GORM. After this, we learn how to build RESTful APIs using GORM. Check out our articles if you think this blog has helped you enhance your knowledge and want to learn more. Visit our website to read more such blogs. 

  1. Introduction to Go 
  2. Functions, Packages, Recursion & Closure  
  3. Go HTTP Server  
  4. Go Interface Type
  5. Go | Full Library  


For placement preparations, you must look at the problemsinterview experiences, and interview bundles. Enroll in our courses and refer to the mock tests and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

Consider our paid courses, however, to give your career a competitive advantage!

Happy Coding!

Topics covered
1.
Introduction
2.
What is Gin?
3.
What is RESTful API?
4.
What is GORM? 
5.
Steps to quick-start with GORM
5.1.
Installation
5.2.
Quick Start
6.
Building REST API with GORM
6.1.
Setting up the environment
6.2.
Setting up the server
6.3.
Setting up the database
6.4.
Setting up the RESTful routes
7.
Frequently Asked Questions
7.1.
What is Gin?
7.2.
What is GORM?
7.3.
What is RESTful API?
7.4.
What is GORM used for?
8.
Conclusion