Do you think IIT Guwahati certified course can help you in your career?
No
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).
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 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.
What is 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.
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.
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.
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.
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.\
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.