This blog will teach you how to create an API in Golang (Go). Moving ahead, you will understand the basic concept of API, and how you can create it in Golang. Before proceeding, you should have the postman application installed and an account created in it since at the end of the project you need to check whether your API is functioning properly or not. I will create three functions in my code to initialize the program i.e., “Create User”, “Get User” and “Delete User”. After writing down the code I will also explain how to check whether your program is initialized correctly. I have mentioned the prerequisites below,
For this project, I will use Gin Web Framework. Several web frameworks can be imported to perform API creation. For Example
Here, net/http is the default package through which we can initialize our program. Net/http provides HTTP client and server implementations. Other than net/http, Gorilla Mux and Gin are the two frameworks that you can use to create an API in Golang. Here, I am using the Gin Framework since it is fast, the codes are short, and more than that I feel comfortable with this framework.
As known, API stands for Application Programming Interface. Here, API is a method through which the front end or the client communicates with the backend server, and it's a one-way conversation. This conversation follows some protocols or methods known as HTTP Methods or Protocols.
If there's two-way traffic/conversation then it is known as Web Socket. This topic is not useful in our project, therefore we will discuss this in some other blog. For now, There are four types of HTTP Methods i.e., "golang development company" you can consider for your project.
Before proceeding you need to understand what packages you need to import. Therefore let's list the packages that are required for our project. Below are the package links,
There are other packages as well that you need to execute your program which I will discuss later in this blog.
To begin with we need to create the directory for our project therefore we will input some commands in the command prompt (windows) that will create a directory for your project.
After entering the last command i.e.,
“code .” the IDE will pop up on your screen. For this blog, I am using VS Code Editor as I have mentioned above. After the creation of your workspace, you need to install the go mod file through your VS Code Terminal. for which the command is
“go mod init github.com/(Your Github Username)/(Directory Name)” in my case, it is “go mod init github.com/golangcompany/RestfulAPI”. Then following this you need to input
“go mod tidy”. After all the basic imports, you need to import the packages that I have discussed above i.e, Gin Framework and Mongo Driver by giving the command
“go get (Package Link)”
In this section, I will begin with my explanation of the code on IDE i.e., on VS Code Editor. Here you need to begin by creating three folders i.e., controllers, database, and models.
In controllers basically, you will define your 3 functions for CreateUser, GetUser, and Delete User. The database will store the string for the database in which you want to push your data and handle the database functions. For this tutorial, I have already mentioned that it is going to be MongoDB. The final folder i.e., models will carry out the struct “User”. Apart from these folders, we will begin with the “main.go” file which will be placed in your main directory.
You need to begin with “package main” and import the packages mentioned in the image above.
Here you will define the func main and mention the port for the establishment of the connection with the server. To understand further you need to get an idea of what a router is in Golang and what is the use case of a router.
Here in func main, you have to get the env method to fetch a port that is available in the dev system. Following that, I have also mentioned that if the program is unable to fetch any port then it will use 8080 as its port to establish the connection to the server.
In my code, I have used gin as the HTTP Web Framework. Here we are defining gin.New()as a variable router and asking it to use
gin.Logger to log the process for records.
In simple words, a router is present in the application and whenever a request is sent or asked to fetch from the front end, it connects with the router and then the router delivers back or returns the data. The process itself is known as routing. As you can see in the above code, I have created 3 routes i.e., POST, GET, and DELETE.
Now, let's see how you can create a Struct.
Struct, also known as the structure, is the main field where different fields are stored in a single place. To make it more simple, let me give you an example.
Suppose you have a travel agency that offers rental cars to tourists with a chauffeur, so you will need different fields like vehicle registration number, vehicle model, seating capacity, vehicle chauffeur name, vehicle legal documents, etc, for your database, therefore, you can prepare a struct for it. In Golang, these are crucial integrations for simplifying the task of both the developer and the organization. Other languages have a different approach to these kinds of proceedings.
Grasping a concept in programming gets difficult without a sample code. Right? So, let’s understand the concept of building a Struct with a sample code syntax, given below.
This will make you learn about its convenience and capacity.
You can notice that I have entered different fields in a single place. This becomes convenient from a developer's perspective.
Hope this was helpful! Now, let us move toward our current project again.
I have not created a lengthy struct, In my code, I have included only four fields i.e., ID, Name, Gender, and Age. First, have a look at my struct before proceeding further.
Here, I will begin by writing package models and importing “go.mongo.org/mongo-driver/bson/primitive”. I have imported the “primitive” package since I want the id to be unique every time we post user data in our database. Next, you need to mention the fields and the data type.
Now, let us proceed toward our database.go file where we will set up our database and mention the MongoDB Clusters string.
If you don’t know about it you can visit this page to get an idea about how to connect your Golang App with MongoDB Atlas.
Here, in this section, you will learn about the three main functions through which the client will hit the API.
First, get used to the basic imports like context, fmt, net/http, and time. Further for program initialization, you need to add gin framework, mongo-driver, and gopackage-bson.
Now you need to focus on the three main functions of our API i.e., CreateUser, GetUser, and DeleteUser. But before that,
We will write a variable named UserCollection. It instructs the program to create a database named User2.
Then, you need to begin with the first function in controllers i.e., CreateUser.
This is a function that returns a gin handler function. This means it can be used as an HTTP handler in the Gin framework. In the next line, you will take two variables, i.e., ctx and cancel. This line creates a context with a timeout of 100 seconds. This is used to prevent the function from running forever if there's an error.
As you can see in my code, I have also mentioned primitive when a new user is created, it will always get stored in the database with a unique object ID.
Now let's proceed toward GetUser Function and DeleteUser Function,
With GetUser Function, you can fetch the user details from the database. Also with DeleteUser Function, you can command the program to delete the user details from the database.
The initial steps of the GetUser Function and the DeleteUser Function will be the same as the CreateUser function. With the DeleteUser function, you can return a gin handler function which is used as an HTTP handler in the Gin framework. I have created a context with a timeout of 100 seconds.
Following that, you need to take the variable id where the query method is implemented and if there's no id matching in the database it will show you an error. On the other hand, if it succeeds, then using the ObjectIDFromHex method the id will be converted from hex to object id. The FindOne method will find the user id in the database and decode it and if the error is nil, it will provide the user data to the client.
Here, as you can see in my code, for DeleteUser, the overall process is similar to GetUser. The difference lies in where I used the FindOne method to find the user id in our database and decoded it. Rather than using the FindOne Method, you need to use DeleteOne Method. The decode method is not necessary in this case since I don’t want to fetch the body of the data.
In this section, I will show the output through the Postman application with the help of some screenshots. First, let’s run the program with the command “go run main.go”.
Here you may encounter a dialog that may ask your permission for access. After approval the permission, you need to get on the postman application to verify whether the API is working properly.
Here in the postman application, first I will check the POST API. For this, you have to enter the address as http://localhost:8080/createuse and select ‘raw’.
Next, I entered the data that I want to post in my database and select the form as JSON and click on send which gives us the message ‘user created successfully’. This is the confirmation that our data is posted in our database.
Now let’s check our data in our MongoDB Cluster.
As you can see, the data we have tried to insert is present in our cluster with a unique object id.
Now, I need to check the GET API. For that, you have to select GET and enter the URL, http://localhost:8080/getuser?id=639b262c6270e18412a48001 (we have entered the id), and click on send.
As you can observe from the image above that it fetched and showed the data against the particular id which I have entered along with the URL.
Finally, I will check the DELETE API. For that, you have to select DELETE and enter the URL with the ID in it. When I click on send, it returns a message “Successfully deleted”.
To confirm let’s check the database. Refer to image 6 where the data is not present. Therefore, The DELETE API is also working perfectly and the program has been executed as expected. As you can experience after following the blog how strict this language is, and strictness in the sense it doesn’t tolerate unused code in its syntax. This itself makes it fast and reliable among all other similar languages. This is why I believe organizations should hire golang developer because this language is going to make its space sooner or later in the IT Industry.