An image

Corporate Blogs

Building RESTful API Service In Golang using Gin-Gonic Framework

E-Commerce Businesses Need a Mobile App

Today, we will walk through a tutorial on how to build a RESTful API service with simple CRUD operations in the Golang using Gin-Gonic framework. Gin allows a high-level API to create RESTful services in a clean way. 

What is the RESTful API service?

Representations State Transfer (REST) is an architectural style that enables the communication between systems. The concept is defined by certain principles and rules. Certain things that satisfy those REST principles are called RESTful. Web services that follow the RESTful principles are RESTful services. It is used to build lightweight, maintainable, scalable WEB services. 

restful-web-services-api-architecture
Source: Phppot

There are so many popular web frameworks for Golang. Here some of the most popular frameworks. 

  1. Gin
  2. Beego
  3. Gorilla Mux
  4. Net/HTTP
  5. Buffalo

Now, let’s start building a RESTful API service using the GIN framework with Go modules. Here I’m using MangiDB for data storage in the objective format.

Prerequisites

  • Go 1.13( >= 1.11)
  • MongoDB 4.2 (or MongoDB Atlas)

Project Repository Structure

├── conn

│   └── mongo.go

├── controllers

│   └── users

│       └── users.go

├── models

│   └── user

│       └── user.go

├── routes

│   └── routes.go

├── go.mod

├── go.sum

├── main.go

└── .env

Create a folder called CRUD-Operations and check into the folder. Generate a module file using the below command.

Note*: To work with modules, we have to maintain the latest version or version go 1.11.

The above command will create a go.mod file in the working directory with the current version like,

Create a main.go file inside the root directory with the help of the below source.

After, we will be importing routes packages.  The routes package contains a StartService function.

Creating Routes

Let’s create a routes file with the below source under the name of routes.go inside the routes directory.

routes/routes.go

The above package function contains a list of API endpoints. I have grouped all endpoints with the API prefix. You must have noticed that I’ve Gin packages imported in the routes script. You can also do the same.

To get install this package in the system, use the below command.

To confirm the installation, check the go.mod and go.sum files.

Once the StartGin function called from the main.go file, Gin service will start with the 8000 port. For now, this service will fail with invalid package error. Since I did not create any user controller package. You can create one while you practice. 

Creating User Controller

Make sure to finish the coding part before you start with the service.  Create a controllers folder in the root directory to keep all the controller logic. And, also create a user.go file inside the users directory under the controllers directory. It is will easier if you are following the project structure just as we discussed in the beginning. 

controllers/users/users.go

In the above controller file, It will be handling requests and responses. For the database to work properly, you have to import a user model package.

Creating a User Model

Create a user.go file inside the user directory and keep the file inside models directory.

Database connection with MongoDB

To make a connection with the database, create a connection file inside the conn directory.

/conn/mongo.go

In this conn package, I have given the desirable environment variable values for MONGO_HOST and MONGO_DB_NAME. Follow the below steps to setup environment variables.

Setup environment variables

Create a .env file with the below key-pair values.

Run the below command to setup environment variables.

As I have completed the coding with the Gin-gonic package, Now, it’s time to test the service routes.

How to build and Run service?

Generate the executable file using the below command at the project root directory.

It will generate an executable file with the name of the project root directory name. Run the executable file to start the service.

Now, you can notice the log with the list of service routes. You can test APIs by using http://localhost:8000 host with the corresponding service route and method.

Conclusion

I hope you find this tutorial useful! In this blog, we have learned how to use the Gin-Gonic package to create RESTful API services in Golang. And also building  MongoDB connection and Database works with the help of mgo.v2 package. Find the full source code in this link.  

Loved this Tutorial? Read another interesting one! Golang Testing Using Ginkgo. 

Need some extra Golang vibes? Take a look at our other popular blogs on Golang development.  Don’t forget to subscribe to the newsletter!

Looking to start your next project? Without taking it any longer, get started by hiring Golang developers at Agira. As a top-notch Golang development company, we provide our clients with innovative technology solutions using Golang.  Talk to our experts today!

Turn your vision to magnificent reality With
Our Web and Mobile Solutions
Professional Life of an IT Consultant Interview with Valentin Crettaz
Written by
Young Senior Software Developer having 4+years of experience in Web development, skilled in Golang, NodeJS, Ruby, AngularJS, Ruby on Rails & AWS services. With a handful of skills, he keeps thriving through all the Edge of Web development to become a perfect back end developer. Besides, this young techie will always buzz up & surprise us with his beautiful Movie collections.

Thoughts on Building RESTful API Service In Golang using Gin-Gonic Framework



Yes, Giedrius you are right!

To avoid disconnection issues with MongoDB and avoid the leaking connections, we have to change the MongoDB connection approach based on application nature.

Hi,
great example!
But shouldn’t be there some MongoDB session close or disconnect in order to avoid connection leak?

Leave a Comment


Rate this Blog!