Building RESTful web API service using Golang, chi, and MySQL

Shaon Shaonty
ITNEXT
Published in
4 min readJul 10, 2018

--

create your very first REST API using go

In my current office, I am working using microservice architecture, and Golang is most popular for creating a microservice. Today I'm going to build a simple crud API web service for blog posts. The reason behind writing this article is to help beginners to build their own REST API.

source: google

In this API, We’ll use dep for dependency manager, Mysql as database work and chi package for routing. It’s a good practice to add a package manager to your project. We’ll use chi package for routing because of its middleware and some good features. You can go through their doc.

In generic CRUD application, API as follows:

  1. POST /posts
  2. GET /posts
  3. GET /posts/{id}
  4. PUT /posts/{id}
  5. DELETE /posts/{id}

Before starting, make sure your $GOPATH works fine. Then go to $GOPATH/src and make a directory named wiki. If dep package is not installed previously in your machine then install using -

$ go get -u github.com/golang/dep/cmd/dep

After successfully installed dep, go to wiki directory and initialize dep and also install another package over there.

$ dep init
$ dep ensure -add github.com/go-chi/chi github.com/go-sql-driver/mysql

Now create main.go inside wiki directory. Import chi and SQL package in main.go like bellow. Create all router and DB connection credential. I’ve put my own you can change it according to yours.

Pretty neat ahh !. Well, Let’s set up a connection with DB and initialise router and middleware. here, We’ll use recover middleware. Because if any request fails, your app won’t die, you can request again without restarting your app.

Don’t panic about catch function I’ll define this function later. dbSource fullest form is username:password@protocol(address)/dbname?param=value

Now we’ll create a basic POST model which is used for send and retrieve data. In go, a struct can typically serve as your model schema.

By adding json tag we can marshalled our struct to JSON. This minute, we will create go-mysql-crud database and posts table on MySQL DB from terminal or third-party app. I mostly use sequel pro.

db create

Can you remember about the routes and handle function we created earlier? It’s time to implement those. When someone request /posts by using POST method with title and content json data, It’ll be executed CreatePost function.

In the above code, we’ve used json.NewDecoder to catch POST data from parameter `r ` and decoded it into our struct post model. Then prepare our insert query and execute the query after that.

title=? means we have dynamic title data to execute which we will retrieve from post variable. Don’t forget to close your query. Lastly we send our message in JSON format to the client using respondwithJSON func. We’ll implement it shortly.

Let’s implement the UpdatePost and DeletePost function.

To catch id I use chi.URLParam . Try to implement AllPost and DetailPost. If you need help then visit my github repo. You can find full code over there.

Now it’s time to write main function and some helper function.

Running this example will spin up a server on port 8005 and can be accessed at http://localhost:8005. (Logger function print the log in your every request on the terminal and it is implemented on helper.go file below.)

We will split main.go to helper.go for including our helper function. You can also split the router and move the router function to router.go.

helper.go

I think you are pretty smart to understand the above code ;) .

Okay, Can we run our code now? In my github repo I’ve included a makefile which can help us to save our time for every time building the app.

If you include makefile in your code directory then run

make run

If you don’t then build the main.go

go build .

It’ll create a binary file in your directory and to run this command $./wiki as our directory name is wiki. So far, Our app is running and serve 8005 port.

To test the API open postman and run those route sequentially. For instance -

for creating post

Yee! We’ve finished our mundane tasks. Again, you can find full source code from github repo. I also added docker and docker-compose file over there.

In my next tutorial, I’ll discuss how to beautify our code.

If you notice any mistake shoot me at the comment box below.

If you find this article helpful follow me on github/s1s1ty

--

--

Data Scientist | Software Engineer | Computer Science Graduate @TU Dresden