The Supreme Guide to Understand the Golang Rest API

Go is a compiled language and has developed technologies like Docker and Kubernetes. This tutorial will illustrate the implementation of CRUD in Golang REST API with Gorilla Mux for routing requests, GORM as the ORM to access the database, and MySQL as the database provider.

First, you will go through the Prerequisites.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Prerequisites

  • Ensure you have basic familiarity and have installed the latest version of Go and MySQL Database.
  • Get an IDE for developing Go. Here, you will be using VSCode with the Go extension installed for tooling.
  • Have a basic understanding of RESTful API.
  • You need to visit inside your GOPATH (The directory where all your Go projects will be kept). The GOPATH was established with the installation of Go. Inside, you will find three folders bin, pkg, and src. In the src folder, create a new folder called github.com. Now create a folder inside github.com with your GitHub username. In this folder, all your Go projects will be saved.
  • You should be in $ GOPATH/src/github.com/<Github username> as your current working directory.
  • Setup the MySQL Workbench, and create a new schema. We will be using a schema with the name go db.

Implementing CRUD in GoLang REST API

We will be working on CRUD Operations over employees. We will build an employee management API and perform Create and Update operations on the data.

Getting Started

  • Open up the folder where you want to create your project. In this tutorial, we will choose $ GOPATH/src/github.com/<Github username> as the following directory. 
  • Using the CLI/ Terminal command, we will create a new directory named rest_api and navigate into the directory. Now, we will write the command to open VSCode.

mkdir rest_api

cd rest_api

code .

Golang_Rest_API_1.

  • You will be navigated to the VSCode. Now, open the terminal of VSCode and write commands to download the Gorilla mux, GORM, and MySQL driver. You can find the commands to install Gorilla mux and GORM on their respective official website.

To install Gorilla mux, write the command:

go get -u github.com/gorilla/mux

To install GORM, write the command:

go get -u gorm.io/gorm

To install the MySQL driver, write the command:

go get -u gorm.io/driver/mysql

We will have a little understanding of the Gorilla mux and GORM package.

  • gorilla/mux will be used to route the incoming HTTP request to the correct method that handles the specific operation. For instance, when a client initiates a POST request to the endpoint, routing makes the machine recognize where the request should be routed.
  • GORM is an ORM with helper functions that carry queries or execute commands over a specific database.
  • Now, we will create the main.go file in the rest_api directory and write the basic syntax in the main.go file.

Golang_Rest_API_2

  • In the main.go file, you must initialize the router with the mux and initialize the database connection using GORM.

This is the code of the main.go file.

Golang_Rest_API_3

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

  • You will create a method initializeRouter() and you must create the router r := mux.NewRouter() in the variable r and the mux package "github.com/gorilla/mux" will be imported while writing mux and pressing enter.

Now, we will define the different APIs that we want to use. 

func initializeRouter() {

    r := mux.NewRouter()

    r.HandleFunc("/employees", GetEmployees).Methods("GET")

    r.HandleFunc("/employees/{id}", GetEmployees).Methods("GET")

    r.HandleFunc("/employees", CreateEmployees).Methods("POST")

    r.HandleFunc("/employees/{id}", UpdateEmployees).Methods("PUT")

    r.HandleFunc("/employees/{id}", DeleteEmployees).Methods("DELETE")

    log.Fatal(http.ListenAndServe(":9000", r))

}

  • Here, we will implement different routes. Inside the HandleFunc(), we must provide the route information.
  • Our route is /employees and when we call the GET method on the /employees, we will get the list of the employees available.
  • We will declare various routes with methods GetEmployees, GetEmployees using id, CreateEmployees, UpdateEmployees using id and DeleteEmployees using id.
  • Now, we will use the log package to print the logs. Here, we will use log.Fatal and pass the port information and the route handler r into it.

log.Fatal(http.ListenAndServe(":9000", r))

  • We will call the initializeRouter() method in the func main().

Now, we will create another file employees.go and define all the functions. 

Following is the code of the employees.go file.

Code_1.Code_2newcode_3

type Employees struct {

    gorm.Model

    Name      string    `json:"name"`

    Address   string    `json:"address"`

    Email     string    `json:"email"`

}

  • In this file, you will create the struct of type employees and inside the struct, you must then define the different properties of an employee.  
  • While working with the REST API, you should send and receive the data through JSON.
  • You have to convert the struct into an ORM model, which will help to store the data and get the data from the database. You will do this with the following command:

gorm.Model 

  • Here, we will use the MySQL local database. We can choose any supported database and install the database driver accordingly. We will create a method to initialize the database and enable the automigration. First, we must define the variables. 

var DB *gorm.DB

  • This is a database variable. You will declare a variable for error as well.

var err error

  • You must declare a constant variable for the database URL. Here, the root is the username following with the password after a colon. It is connecting to tcp (127.0.0.1:3306) and running on port number 3306 and your schema name is godb.

const DNS = "root:Abhis@r07@tcp(127.0.0.1:3306)/godb?charset=utf8mb4&parseTime=True&loc=Local"

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Now, we will declare the InitialMigration function and define the properties. 

First, we  will initialize the database and enable the automigration. Here, automigration means whether the struct defined as a model is available in the database. If not, it will create the table over here and if it's already available, it won’t create the table. 

Golang_Rest_API_5

  • We will write a command for GORM to open the database and pass the DNS constant and &gorm.config.
  • Now, we will check the errors. If any error occurs, panic would be raised. And if there is no error, we will enable the Automigrate with command.

DB.AutoMigrate(&Employees{})

The InitialMigration() will be called in the main() function in the main.go file.

Now, we will create the handler methods andl give the name accordingly. And they will take the http.ResponseWriter and pointer of the http.Request as input parameters. 

These are part of the net/http package.

First, you must define the function CreateEmployees. 

Create Operation

Golang_Rest_API_6

  • For this ResponseWriter, you must set the content type to application/json. You should create the variable employees of type Employees.
  • Using the json module, you must decode the data we are getting from the request body.

json.NewDecoder(r.Body).Decode(&employees)

  • With the NewDecoder, we will be taking the data from the body of Postman. We have used JSON here, so it's been added to the import list.
  • Now, we will use the create method to save the data and pass the employees' reference.
  • As the data gets saved, you will pass the data back to the browser using the command NewEncoder and passing the ResposeWriter.

json.NewEncoder(w).Encode(employees)

Similarly, you can run the different functions declared.

Building the Application

  • Now, to run the application; we will open the terminal and build the RestApi application with the command:

go build

  • You will notice the rest_api.exe file is created on the left column. You will run the executable file by executing the command  .\rest_api.exe. The application has started now.
  • Now, you need Postman to run the application. You must install Postman and launch it. You will create a new request and pass the URL in the URL section to run the application.

http://localhost:9000/employees 

  • You will choose the type as POST, choose Body, then raw and in the drop-down section select the type JSON.

Golang_Rest_API_7.

  • Now, pass the JSON data, name, address, and email. And click the Send button. This creates the table in the database with the various fields.

Golang_Rest_API_8

  • Now, switch to Postman and use the same API. Now, run the struct data again by clicking on the Send button. This will allow you to save the data in the table. 

Golang_Rest_API_9.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

We can check the data in the database. Data will be inserted into the database. We will pass another json struct into the body and click the Send button.

Golang_Rest_API_10

We have got two rows in the database.

Golang_Rest_API_11

Now, we will see how we can update the data with our declared function UpdateEmployees().

Update Operation

Golang_Rest_API_12

  • We will perform the update operation on a particular id, so we will use params here. From the mux router, we will pass the request r, this will give us params.
  • We will declare the variable employees of type Employees.
  • Now, we will write the command to find the data of the particular employee, that would be stored in the variable employees. 

DB.First(&employees, params["id"])

  • Get the data from the body, decode that information and update the reference of the same user.

json.NewDecoder(r.Body).Decode(&employees)

  • Now, we will save the data in the database with the command.

DB.Save(&employees)

  • As the data is saved, we will encode data back to the browser. 

json.NewEncoder(w).Encode(employees)

Here, in the Postman, we have prefixed the id with /1. It specifies that the update action will be performed on the table row with id = 1. And the update operation is of type PUT. We will pass the JSON data in the body to update the row with id = 1.

Golang_Rest_API_13.

Here, we get our updated data in the database.

Golang_Rest_API_14.

Conclusion

You have learned the implementation of CRUD Operations in Golang REST API using Gorilla Mux routing and GORM Database Access using the MySQL Driver. 

If you aim to build a software development career, you can check the Post Graduate Program in Full Stack Development by Simplilearn. It can be the ideal solution to help you build your career in the right direction.

In case you have queries or would like to provide your inputs to our editorial team regarding this “The Supreme Guide to Golang Rest API” tutorial, feel free to use the comments section below. Our team of SMEs will get back to you soon!

About the Author

Abhisar AhujaAbhisar Ahuja

Abhisar Ahuja is a computer science engineering graduate, he is well versed in multiple coding languages such as C/C++, Java, and Python.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.