"Namaste everyone". REST API is the common web service mechanism that we can find on any system. Using a web service, applications can talk with each other without directly asking for data from database. So in this article we are trying to make an attempt to build a basic RESTful API with Golang and MySQL. I here use an HTTP framework called Gin for creating an API server. Gin is faster because it is built on top of httprouter.
By the end of this article, you will be comfortable in exploring various things in the process of developing a REST API.
Setup & Dependencies
We need Go compiler for running and building our API. So we hope Go, MySQL server are installed in your system. If not on Ubuntu14.04 machine you can do this.
$ sudo add-apt-repository ppa:gophers/go $ sudo apt-get update $ sudo apt-get install golang-stable $ sudo apt-get install mysql-server
Now set the $GOPATH variable creating a new folder in your home. $GOPATH is where your external packages and libraries are stored. My ~/.bashrc looks like this.
export GOPATH=/home/naren/mygo export PATH=$PATH::/usr/local/go/bin export PATH=$PATH:$GOPATH/bin
Now we are ready with setup. Let us install dependencies.
$ go get "github.com/go-sql-driver/mysql" $ go get "github.com/gin-gonic/gin"
Now we have everything to proceed. For development chose your favorite text editor. My favorites are both Atom and Sublime Text 3. Both have very good tooling for Go.
source code & build for this API is available at Source code
A basic REST API has these four important methods.
In the below section, we are going to create an API for Person details.
Imports on line no's 3, 5, 7, 8 are functional requirements. Remaining imports are utilities which are helpful in course of time. sql-driver and martini are essential for our API.
First create a database called "gotest" in your MySQL shell.
CREATE DATABASE gotest
Creating Person Table in DB
Now let us write a migration file in Go to create Person table in gotest.
Here only line no's 10, 21 and 25 are interesting. Others are just error handling statements. One notable point here is we are actually pinging server using db.Ping() to find out whether DB is reachable. "sql.Open" do not give any error if the machine is not accessible. So we should ping and confirm it.
Now person table looks like this
Gin is a very simple HTTP framework for writing application servers.
Now we can jump into the actual development of API server. We can first create a bare structure of our main program.
In every gin app, we should create a Default or New gin router
router := gin.Default()
We can specify :port on which our Gin applications run using
router.Run(":3000") // server runs on 3000 port
We are creating a struct called Person to map with Person table in DB. We actually use these structs to receive data at the time of fetching records from DB.
In Gin, we can attach handler functions to a particular URL. It is called URL routing. So let me add a simple GET handler to the main function.
Every Gin handler takes two arguments
- Function handler with a gin.Context object
This gin.Context object consists of information about headers, passed parameters, data posted, cookies, etc. It is also responsible in sending a response back to the client. In the above example, we are querying MySQL DB to get a person detail. We are using QueryRow which only returns one record if exists. Since id is a primary key, it only returns one record.
gin.H is a map which actually has methods to serialize custom data we supply to it. It should be passed to c.JSON response instead of marshalling data. Gin will take care of that.
Now in the similar way add one more GET for fetching all persons.
Here we are applying Query method to fetch a cursor and iterating over it. Then we are storing them in a slice and returning back to the client in JSON form.
Now let us defined the POST handler which is intersting.
This code draws two points.
- Why Prepare & Exec are used instead of Query?
- Why Buffers are used for concatenating strings?
For the actions like writing to DB where result is not cared, using Prepare and Execute is considered as the best practise. Using buffer instead of cancatenation operation gives performance boost. Now let us defined the other two handlers to complete our REST API.
The code is self explanatory here. These two are same as POST handler with few changes in DB queries. Sprintf is commonly used to interpolate values into strings.
The complete API server source looks like this.
REST API in action
Now build the program and run it.
$ go build gitter.go $ ./gitter
API server will be running on http://localhost:3000
- Get all persons
- Get user with id = 28
- Change name from "Sagar Juthuga" to "Sagar Kumar"
- Delete user Vinay from persons list
You can actually observe the terminal where API server is running to get time taken by requests, type of request etc.
There are more things we need to implement to make it usable.
Gin provides out of box solutions for all these scenarios.
This is a result of my understanding about Gin and SQL driver. I know the way here mentioned is pretty naive. Hope it will help you. Send your comments to narenarya@live . If you really like this article, please share it and spread the word.
Thank You :)