Create REST API With Gin Framework And Golang

Introduction

Let's keep C# & .Net Core aside for a moment and today we will be learning and implementing the most widely used language and currently trending in the market Go. Let's discuss in-depth about Go and its importance and we will build the CRUD operations using the Gin Framework.

Also, I would recommend using Visual Studio Code mainly for tooling and built-in terminal which makes things much easier.

Topics to be covered

  1. What is Go and Gin Framework
  2. How Go is different from other programming languages
  3. Project Setup
  4. Packages installation
  5. Configuration Setup
  6. Implementing Get API
  7. Testing the Output

What is Go and Gin Framework

Go is an open-source programming language used to build the APIs and Microservices and it's a completely server-side programming language. There are multiple names for it as people used to call it Golang or Go language. It was initially developed by fellow google engineers and later they made it available as open source to create dependable and also to make efficient software. It was first released its version 1.0 in March 2012 and now Go is one of the widely used programming language in the big tech industries and for open-source projects which are out there in the market.

Gin Framework

Gin is an HTTP web framework written in Golang. It allows us to build web applications and microservices as well as APIs in Go. It makes it simple to build a request handling pipeline from modular and reusable pieces. It also contains a set of commonly used functionalities i.e routing, middleware support, rendering, and many more. Gin framework has the most ability and it's pretty straightforward to use.

How Go is different from other languages

It's not that Go is better than other programming languages, the primary thing to focus on here is it reduces development time considerably through error checking, concurrency handling, simplifying threads, and go routines that are scalable. It allows concurrent programming and that makes a big draw for companies who wants to save time and resources in building up things.

Project Setup

Before setting up the project we first need to have the go package in our machine/pc download it from here. After the complete installation creates a folder named Go_API and open the folder in the visual studio code.

To play around with it we need to install the from the extensions section in the visual studio code, check the below

Create REST API With Gin Framework And Golang

  • Right-click on the same folder and create a file named main.go in which we will perform all our operations.

Packages to be installed

In order to create a restful API we are utilizing a library known as Gin, but we need to get the dependency inside this project first to do that. 

  •  Right, Click on the main.go file.
  • Select Open in Integrated Terminal.

Let's Install the core package of the go language like we install the npm in angular its like the same way. 

Command 

go mod init

Create REST API With Gin Framework And Golang

Before we install the Gin framework, we first need version 1.15+ required, Now use the below command to install Gin in our project.

Command

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

Project Structure

Create REST API With Gin Framework And Golang

Configuration Setup

To implement APIs we just need to import the gin library and along with that we also need to add an HTTP package in the same file.

Let's create an Employee model in the main.go file and define the JSON structure for each of the elements in it.

type Employee struct {
	EmployeeId   string `json:"employeeid"`
	EmployeeName string `json:"employeename"`
	Company      string `json:"company"`
	Salary       int    `json:"salary"`
}

Since We are not pointing to any database in this project and here i am mocking the response object for the employees to test the API response.

var employees = [] Employee {
    {
        EmployeeId: "001",
        EmployeeName: "Jay",
        Company: "Xyz",
        Salary: 2400,
    }, {
        EmployeeId: "002",
        EmployeeName: "Krishna",
        Company: "zey",
        Salary: 2800,
    }, {
        EmployeeId: "003",
        EmployeeName: "Reddy",
        Company: "zwd",
        Salary: 3400,
    },
}

As mentioned earlier, the Gin package handles the HTTP routing for this particular project. This means that any kind of HTTP request sent to the Golang API Server will be routed to the appropriate method handlers.

Open up the main.go file and add the following function. This basically takes care of all routing concerns related to Employees.

Implementing Get API

Next, Get Employee all the details. For this firstly we will need to have a function that will fetch the data but here in our case, we suppose to get the mock response.

func createEmployee(c *gin.Context) {
	var newEmployee Employee
	if err := c.BindJSON(&newEmployee); err != nil {
		return
	}
}

Below are the complete changes that we can see in the main.go file.

main.go

package main

import("net/http"
    "github.com/gin-gonic/gin")
type Employee struct {
    EmployeeId string `json:"employeeid"`
    EmployeeName string `json:"employeename"`
    Company string `json:"company"`
    Salary int `json:"salary"`
}
var employees = [] Employee {
    {
        EmployeeId: "001",
        EmployeeName: "Jay",
        Company: "Xyz",
        Salary: 2400,
    }, {
        EmployeeId: "002",
        EmployeeName: "Krishna",
        Company: "zey",
        Salary: 2800,
    }, {
        EmployeeId: "003",
        EmployeeName: "Reddy",
        Company: "zwd",
        Salary: 3400,
    },
}
// Fetch all Employes Data
func getEmployees(c * gin.Context) {
    c.IndentedJSON(http.StatusOK, employees)
}
// Create Employee with Data
func createEmployee(c * gin.Context) {
    var newEmployee Employee
    if err: = c.BindJSON( & newEmployee);
    err != nil {
        return
    }
}
func main() {
    router: = gin.Default()
    router.GET("/employees", getEmployees)
    router.POST("/employees", createEmployee)
    router.Run("localhost:8080")
}

Testing the Output

To run and test our Get API we just need to run the project on the defined port number which is localhost:8080, Run the below command 

--   go run main.go

Create REST API With Gin Framework And Golang

Here I am using Thunder Client vs code extension which is pretty simple to use as an extension that exists within our ide.

Create REST API With Gin Framework And Golang

Open the thunder client extension and paste the GetEmployee API Url and hit the send button. On the next right-hand side, you can see the status code with the API success response.

Create REST API With Gin Framework And Golang

Source Code - Click here

Conclusion

Thank you for reading, I hope this article gives you a brief idea about Rest API implementation with Go lang and GIN framework with code samples.

Please let me know your questions, thoughts, or feedback in the comments section. I appreciate your feedback and encouragement.

Keep learning ...!