Golang CRUD Rest API with Echo

Golang-CRUD-Rest-API-with-Echo

This Golang tutorial will show you how to make a CRUD operation API using the PostgreSQL database. To add, update, and delete records from a PostgreSQL table, we’ll construct a REST API.

Using the ECHO web framework is really basic and straightforward. Using the Echo framework, this ‘todo’ application helps to create employee records, edit employee records, and delete employee records from the database.

What’s Echo Framework

Echo is a PHP micro-framework similar to Lumen. It has a lot of capabilities and is well documented for making quick and easy web applications with GO. You can design a restful API without using a framework. however, frameworks have their own set of features that make web development more secure and faster.

postgreSQL Database Table

Let’s create a table into postgreSQL database, the employees table will have the following column:

  • name
  • salary
  • age

Rest end points

We will create the following rest endpoints into this golang rest api tutorial:

Route Method Type Posted JSON Description
/employee GET JSON Get all employees data
/employee/{id} GET JSON Get a single employee data
/employee POST JSON {"Name": "Adam", "Salary": "4500", "Age" : "53"} Insert new employee record into the database.
/employee PUT/{id} JSON {"Name": "Adam", "Salary": "4500", "Age" : "53", "Id" : "16"} Update a customer record into the database.
/employee DELETE JSON {"Id" : 16} Delete particular a employee record from the database.

Create Rest API Framework

To construct a restful API, we’ll use the GO programming language. Go is a lightweight, easy-to-learn, and quick programming language. Google invented the Go programming language. The information is kept in a PostgreSQL database. PostgreSQL, like MySQL and SQLite, is a lightweight database.

Simple GoLang API Using Echo and postgreSQL

We’ll create the main server’s main.go file and populate it with all of the necessary functionality. The main file will contain information about database connections and routes. I’m not going to make a separate file handler, env, or model class. This golang tutorial will teach you the fundamentals of routing and how to use the echo framework in Golang.

Step 1: Let’s create a main.go file. To import the required package for this application, open the main.go file and add the following code.

package main
 
import (
            "net/http"
            "database/sql"
            "github.com/labstack/echo"
            "fmt"
            "log"
            _"github.com/lib/pq"
)

The GO standard library includes packages SQL, HTTP, etc, but the PostgreSQL driver must be downloaded from the Github repository.

We have used "_" with the import package, that’s telling the compiler that we’re not utilizing it yet.

Step 2: Install package
We will run the below command to get all the packages:

$ go get github.com/labstack/echo
$ go get github.com/lib/pq

Step 3: In the main.go file, create a “main()” function, which is the entrance method for any Go application.

var err error
db, err = sql.Open("postgres", "user=postgres password=root dbname=books_database sslmode=disable")
if err != nil {
        log.Fatal(err)
}

if err = db.Ping(); err != nil {
        panic(err)
} else {
        fmt.Println("DB Connected...")
}

e := echo.New()

type Employee struct {
        Id     string `json:"id"`
        Name   string `json:"name"`
        Salary string `json: "salary"`
        Age    string `json : "age"`
}
type Employees struct {
        Employees []Employee `json:"employees"`
        }

in the above code, We have created employee struct as JSON type and employees results set.

Get All Records Using Rest API

To access all employees’ data from the table, we’ll use a GET request. To get all data from a PostgreSQL table, we constructed a select query.

e.GET("/employee", func(c echo.Context) error {
        sqlStatement := "SELECT id, name, salary, age FROM employees order by id"
        rows, err := db.Query(sqlStatement)
        if err != nil {
                fmt.Println(err)
                //return c.JSON(http.StatusCreated, u);
        }
        defer rows.Close()
        result := Employees{}

        for rows.Next() {
                employee := Employees{}
                err2 := rows.Scan(&employee.Id, &employee.Name, &employee.Salary, &employee.Age)
                // Exit if we get an error
                if err2 != nil {
                        return err2
                }
                result.Employees = append(result.Employees, Employee)
        }
        return c.JSON(http.StatusCreated, result)

        //return c.String(http.StatusOK, "ok")
})

Add a record Using API

To add employee data to the PostgreSQL table, we’ll make a POST request. We gave JSON data to the c.Bind() method, which maps it to an Employee struct.

e.POST("/employee", func(c echo.Context) error {
                u := new(Employee)
                if err := c.Bind(u); err != nil {
                        return err
                }
                sqlStatement := "INSERT INTO employees (name, salry,age)VALUES ($1, $2, $3)"
                res, err := db.Query(sqlStatement, u.Name, u.Salary, u.Age)
                if err != nil {
                        fmt.Println(err)
                } else {
                        fmt.Println(res)
                        return c.JSON(http.StatusCreated, u)
                }
                return c.String(http.StatusOK, "ok")
        })

Update record Using Rest API

We’ll make a PUT request to update employee data in a table based on their id. We gave json data to the c.Bind() method, which maps it to an Employee struct.

e.PUT("/employee", func(c echo.Context) error {
        u := new(Employee)
        if err := c.Bind(u); err != nil {
                return err
        }
        sqlStatement := "UPDATE employees SET name=$1,salary=$2,age=$3 WHERE id=$5"
        res, err := db.Query(sqlStatement, u.Name, u.Salary, u.Age, u.Id)
        if err != nil {
                fmt.Println(err)
                //return c.JSON(http.StatusCreated, u);
        } else {
                fmt.Println(res)
                return c.JSON(http.StatusCreated, u)
        }
        return c.String(http.StatusOK, u.Id)
})

Delete a record Using Rest API

We’ll make an Erase request to delete employee data from the table based on their id. To delete specific employee data, we gave the employee id.

e.DELETE("/employee/:id", func(c echo.Context) error {
        id := c.Param("id")
        sqlStatement := "DELETE FROM employees WHERE id = $1"
        res, err := db.Query(sqlStatement, id)
        if err != nil {
                fmt.Println(err)
                //return c.JSON(http.StatusCreated, u);
        } else {
                fmt.Println(res)
                return c.JSON(http.StatusOK, "Deleted")
        }
        return c.String(http.StatusOK, id+"Deleted")
})

Conclusion:

We used the Golang Echo framework and the PostgreSQL database to create a RESTful API. Add a record using golang rest call, update data using rest API, retrieve all data using API, and delete rest API data are all items on the employee’s ‘todo’ list.