Build a REST API Application Using Golang

Introduction

In this blog, you will get to learn about RestAPI and how to Create RestAPI in Golang. For this tutorial, I will be using Gin Web Framework, about which an explanation will be there in the blog as well. There are a few concepts that you need to be prepared with to have a better understanding of the project that I have mentioned in the prerequisites part below. Now, Let’s proceed to build our project.

Prerequisites

  • You should have clarity on concepts like structs, slices, and packages.
  • You need to download the Postman Application to check whether your API is working properly or not. 
  • You need an active account in MongoDB Atlas.
  • Go Program installed in your system.
  • An IDE like VS Code Editor

Understanding RestAPI

Before writing the code, you need to understand what RestAPI is. API stands for Application Programming Interface. In simple words, let us understand the concept through an example. Suppose you want to buy Insurance for your vehicle from an Insurer named “ABG Corporation”, To issue a policy, ABG Corp wants to have your car's real-time info and your info as well to check your credibility. Therefore, he will request data from the server of your car registration authority, credit agencies, banks, and other organizations as required. This all happens in real-time to conclude whether ABG corp can issue you the policy or not. Therefore here API acts as a messenger in these scenarios and helps in communicating between the internal and external parties in a consistent way.


Gin Web Framework

As it is known, you can create a web application with GoLang. In a web application, the Client (Front-End) makes an HTTP request, and then the server (Back-End) returns the information in response. The response could be of any type like XML, JSON, HTML, etc. This process of requesting and responding is a very crucial part of maintaining the whole system, and for this, we use the “net/http” package in our Golang Program. This package is useful but not for complex programs. Here comes the role of Gin Web FrameWork. The gin framework is very popular among developers and it is widely used for Golang Web Development.  

Let’s Begin with the Code


Packages
The first step for coding includes the creation of a directory and importing the packages required to run the program. I have mentioned the packages below for your reference,

“github.com/gin-gonic/gin”
“go.mongodb.org/mongo-driver”
“go.mongodb.org/mongo-driver/bson/primitive”
“go.mongodb.org/mongo-driver/options”

These are the basic external packages for the project, there are other packages as well that you need to import, some of them are internal and some of them are external, which you get to know further in this blog.

[Image 1]

Main Function
Let us start with the main.go file, where we will define our main function that includes a conditional statement that checks if the port variable is empty. If it's empty, then it assigns the value of 8080 to the port variable. router := gin.New() is a new router that we are creating. It will be used to handle incoming requests and send them to the handler. The next steps state a simple REST API that allows you to create, get and delete users. It uses the Gin framework, The first-line router.POST(“/createuser”, controllers.Createuser()) is a function call to the POST method of the router object. It takes two parameters:       
  • A string that represents the path of the URL. In this case, it's /createuser. 
  • A function that will be called when a POST request is made to /createuser. In this case, it's controllers.CreateUser().
  • The next line defines a function call to the GET method of the router object. It takes two parameters:
  • The first parameter is a string that represents the URL path. In this case, it's /getuser. This means that when you make a GET request to your server at localhost:8080/getuser, this function will be called.
  • The second parameter is another function call to the GetUser() method of the controllers package. This means that when you make a GET request to your server at localhost:8080/getuser, this function will be called and its return value will be used as an argument for the first parameter's function call (the one with a router).
The third line is a route handler for the DELETE method. It will handle requests to the /deleteuser. Finally, I have mentioned starting the server and listening for requests.

My next steps include database setup, for that, you can visit my previous blog. This will give you a brief idea about database connection and setup. I have shared the code below for this project as well, please refer to Image 2.

[Image 2]

Building Struct
Now, you need to create the struct that represents a user in our application. It has 4 fields: ID, Name, Gender, and Age. Here, the struct is used to create new users and store them in the database. The set of code doesn’t contain any functions, methods, or constants.

[Image 3]

Establishing Controllers
This is the last section of this project where I will write code for the controller file. Let's begin with the packages that you need to import before proceeding, please refer to Image 4 for reference,

[Image 4]

[Image 5]

Then, I created a variable, that declares a variable named UserCollection of type *mongo.Collection. The value assigned to the variable is the result of calling the function database.UserData(database.Client, "User").

After declaring the variable, we will create three functions for the controller i.e., CreateUser, GetUser, and DeleteUser.

First, let's begin with the CreateUser Function. Please refer to Image 5 before proceeding,

[Image 6]

Here, CreateUser Function takes in the request body and binds it to the User struct. Then, it inserts the user into the database.

Next, I have mentioned GetUser Function, whose purpose is to get the user with the id specified in the query string. (Refer to Image 7)

[Image 7]

Lastly, I have created the DeleteUser function that deletes an object from the database. It takes in an id as a parameter and uses it to find the object in the database. Once found, it deletes the object and returns a success message. (Refer to Image 8)

[Image 8]

This is how you can establish controllers and build a RestAPI in Golang. Hope it was helpful for you, Happy Coding!! 

Post a Comment

0 Comments