Build RESTful API service in golang using gin-gonic framework

Start to write your own Microservices today!

Today I’m going to build a simple API for todo application with the golang programming language. I’m going to use golang simplest/fastest framework gin-gonic and a beautiful ORM gorm for our database work. To install these packages go to your workspace $GOPATH/src and run these command below:

In generic crud application we need the API’s as follows:

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

Let’s start coding, go to your $GOPATH/src and make a directory todo. Inside the todo directory create a file main.go. Import the “gin framework” to our project and create the routes like below inside main function. I like to add a prefix of the apis like “api/v1/”, that’s why we’ll use the router Group method

We have created five routes and they handle some functions like createTodo, fetchAllTodo etc. We’ll discuss about them soon.

Now we need to setup a database connection. To use database pull the gorm package and mysql dialects in our code. Follow the code below:

In the above code “mysql” is our database driver, “root” is database username, “12345” password and “demo” is database name. Please change these information as your needs.

We’ll use the Database function to get the database connection. Lets make a todoModel and transformedTodo struct. The first struct will represent the original Todo and the second one will hold the transformed todo for response to the api. Here we transformed the todo response because we don’t expose some database fields (updated_at, created_at) to the consumer.

Todo struct has one field extra gorm.Model what does it mean? well, this field will embed a Model struct for us which contains four fields “ID, CreatedAt, UpdatedAt, DeletedAt”

Gorm has migration facilities, we already used it in init function. When we run the application first it’ll create a connection and then the migration.

Can you remember the five routes we wrote a minute earlier? Lets implement the five methods one by one.

When a user send a POST request to the path ‘api/v1/todos/’ with ‘title and completed’ field it’ll be handled by this route v1.POST(“/”, createTodo)

Lets Implement the createTodo function

In the above code we use gin Context to receive the posted data and gorm database connection to save the todo. After saving the resource we send the resource id with a good & meaningful response to the user.

Lets implement the rest of the functions

In the fetchAllTodo function we fetched all the todos and and build a transformed response with id, title, completed . We removed the CreatedAt, UpdatedAt, DeletedAt fields and cast the integer value to bool.

Well, we write enough code, let try to build the app and test it, I’m going test it using chrome extension Postman (you can use any REST client like curl to test).

To build the app open your terminal and go the the project directory

The command will build a binary file main and to run the file us this command $ ./main . Wow, our simple todo app is running on port: 8080. It’ll display the debug log, because by default gin run’s in debug mode and port 8080.

To test the api run postman and test the api sequentially

Need full source code?

Note: When you are using code production you must take care of the steps below:

  1. Do not fetch all the data select * from todos , use pagination
  2. Do not trust user input. You must validate the inputs, there are severals tools to validate input. Read the article for validation process
  3. Check every possible error
  4. You should use logging and authentication as your need

I am really sorry for my BAD English and Writing flow. If you notice any mistake in the article please feel free to write a comment.

If you find the article helpful please follow me in github/thedevsaddam

Love this article? Read another interesting article: How to access deeply nested JSON data using Go (lang)?

Help me to write more articles like this one

Software Engineer, Pathao Inc | Open Source Enthusiast | Love to write elegant code | Gopher by passion |