Tech News

Creating a RESTful API Using Gin-Gonic

So, you are looking forward to creating a REST API using the Gin framework? That’s great! You have arrived at the right place. This blog will teach you how to create a basic REST API. And no, you can create an API without the help of any Golang developers. So, let us delve right into it.

Prerequisite

You should know about the theoretical aspect of the gin framework before you start creating the API.

Preliminary Task

  • You have some work cut out for you. First, you have to create a directory in your go-workspace. If you are using a Windows system, then you will use the Command Prompt. And if you work on macOS or Linux, you should use the Terminal.
  • In this case, I’ll be using the Command Prompt

cd go-workspace

mkdir banking

cd banking

code.

  • When we type code ., the editor or the IDE opens up. In this case, it will be the VS Code.

Start with the VS Code

  • As the VS Code is launched, we must create a file. Let’s name this banking.go.
  • Before we proceed, we have to install the gin framework. However, there is one more task that we have to accomplish. We have to create a go.mod file. Now how is this possible? We type:

go mod init golang.com/banking

  • Following the creation of the go.mod file, we will type:

get github.com/gin-gonic/gin

  • This will download all the required packages associated with the gin framework and lead to the formation of the go.sum file.

Starting with a Simple GET API

Let’s start by writing down the code.
package main
import (
“fmt”
“net/HTTP”
“github.com/gin-gonic/gin”
)

func main()
{s :=gin.Default()
s.GET (“”, func (c *gin.Context){
c.String(HTTP.StatusOK, “How much should you invest in a year?”)
})
s.Run (“localhost: 8000”)
}

  • As you can see, we have imported all the necessary packages we need for the program. Following this, we go straight to the main function. We are creating a default module for gin that comprises recovery or logger middlewares.
  • The ‘s’ variable consists of the default settings. And this variable will help us create the GET API. The API’s URL is the first argument I’ve supplied in this case.
  • They will host the API at localhost:8000, the base URL indicated by s.Run (“localhost:8000”). Additionally, the first argument indicates the API’s relative route.
  • The func (c *gin.Context) is a handler function, which refers to the function sequence you can pass.
  • The function’s parameter represents the pointer to the variable *gin.Context. So, in this case, the ‘c’ stands for the context.
  • The value that the context delivers must be either c.String or c.JSON. There are two criteria at play here. The first parameter is a simple integer that refers to the status (HTTP.StatusOK). Since we imported the net/HTTP package, we can utilize this.
  • Following this, I’m just sending a sample string “How much should you invest in a year?”

Time to Run the Program

Now it is time to run the program, and we will use go run main.go.

RESTful API
  • There is a GET request on a blank URL, as you can see. Additionally, it includes a configurable function. Furthermore, you can see that the engine is operating in release mode. Finally, there is one endpoint, which is active on localhost 8000.
  • When we type localhost:8000 on a web browser, we get:
RESTful API
  • Meanwhile, in the VS Code, you will get to see:
RESTful API

As you can see, the gin framework keeps track of the response time of code execution.

Focusing on GET API where the URL Handles Parameter Passing

Now, we type the following program where you assume that the API where you will be receiving a value, preferably a string, from the URL.

s.GET(“/:parameter”, func (c *gin.Context){
var val = c.Param(“parameter”)
c.JSON(HTTP.StatusOK, gin.H{
“parameter”:Val,
})
})
//2nd section

  • By separating each variable name with a colon, we may pass it in the GET request. Therefore, everything entered after the base URL will be interpreted as a “parameter.”
  • We will specify the context of Param and the name of the variable we have mentioned to obtain the value of the ‘parameter.’ Then, gin will get the news update and deliver the outcome to val.
  • Next, we notice that the value is contained in a JSON that I am transmitting.

Meanwhile, if you are working on something intricate and cannot find your way out, you should not hesitate to contact a Golang developer.

Run the Program Above

  • Now, we will try to run the program we wrote above. Thus, we have to type go run main.go.

If you get a message ‘tcp 127.0.0.1: 8000: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.’, then you have to perform the following steps on Command Prompt.
nestat -and | findstr :8000
Check for the value of LISTENING (for instance, 964), and then you have to type
taskkill / pid 964 /F

This will terminate the pid process.

  • Then on the browser, we perform:

Why we wrote ‘what is SIP?’? This is because the API is expecting a value from the URL. As you can see, the ‘?’ is not registered.

Testing a POST API

  • Here, we’ll try to connect to a POST API. In addition, we are aware that the Body will contain data. The struct will be helpful in this regard.
  • Do you remember the following section?

package main
import (
“fmt”
“net/HTTP”
“github.com/gin-gonic/gin”
)

  • Here we will be creating a struct with two different data fields.

type Bank struct {
Salary int json:"salary" binding: "required"
Alcohol string json:"acchol" binding: "required"
}

  • As you can see, the JSON:”salary” and JSON:”acchol” are different keys, and it has been mentioned that the binding is essential.
  • Following the //2nd section, we will type:

s.POST(“/highlight”, func (c *gin.Context){
var data Bank
if err := c.ShouldBind(&data); err != nil{
ft.Println (err)
c.JSON(http.StatusBadRequest, gin.H{
“error”: fmt.Sprintf(“%v”, err),
})
} else{
c.JSON(http.StatusOK, gin.H{
“data” : data,
})
}
})

  • Let’s examine this section of code. We will build the object for the Bank in the s.POST. Following that, the context “c” ought to bind to the data model. It would notify the API of the error if c.ShouldBind(&data) throws an error.
  • I submitted a bad request that highlights the error that was received in “error”:fmt.Sprintf(“%v”, err) in c.JSON(http.StatusBadRequest).
  • We will use the “data” key to send the data back to the API response if there are no errors.

Time to Run the Program

  • Now let us check out the last step of the program. For this, we have to type go run main.go. And I will be using Postman to demonstrate the code and the function of the API. Then, finally, you have to install the desktop version.
  • Just check the snapshot below, and you will see that I have included two data fields in the Body. For the Body, I’ve chosen raw and JSON.
  • As we click on Send, you can see that we are getting the result.

{
“data”: {
“Salary”: 23000,
“acchol”: “Jackson Drews”
}
}

Hopefully, you have understood the program I typed above and how the API works. If you cannot understand, you should go through the steps again and organize the program on the screen.

Read More:-

How to Drive Down SOC (Security Operation Center) Costs Without Losing Value

How to Enable full URL in Google chrome

Arcade1up Infinity Game Table, the gaming coffee table that is a digital board game console

How to Download Videos without any Softwares, from any Browser

How to Clean C Drive In Windows 10

Awais Mahmood

Awais is a freelancer, creative writer, and also SEO Expert. He has good experience in writing news articles. Additionally, he is also a researcher of Blogging, SEO, Social Media, premium accounts tips and tricks, etc

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button