How To Consume Restful APIs with Echo Golang

This is basic golang tutorials to access third party API using HTTP.I am using ECHO Golang framework, Its fast and popular web framework.We are processing data and sending response using Echo HTTP methods.

The HTTP help to send request to server and get response,The response could be as json, xml type, I am using JSON data format. I am using dummy rest api to demonstrate , how to consume RESTful JSON API using Go http module.

Lets start accessing rest API into golang application.We will access employee list using HTTP get request of http://dummy.restapiexample.com/api/v1/employees. The JSON data response format is,

[{"id":"1","employee_name":"test","employee_salary":"11110","employee_age":"20","profile_image":""},{"id":"2","employee_name":"adam","employee_salary":"22220","employee_age":"30","profile_image":""}]

We will import all required golang packages,

 "encoding/json"
	"fmt"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"net/http"
 

Where :

  • json: Use to parse json data.
  • fmt: Use to print data in command window.
  • echo: The Echo web framework libs.
  • echo/middleware: This package contains middleware of ECHO framework like Logger,BasicAuth, JWT etc.
  • net/http: Use to send HTTP request.

Create ECHO instance into mail method,

func main() {
	e := echo.New()
	//CORS
	e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
		AllowOrigins: []string{"*"},
		AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
	}))
}

echo.New() method is used to create ECHO instance and assigned to e variable. CORSWithConfig middleware help to enable CORS with in this golang application.

We will create Employee Struct as per response JSON data,

type Employee []struct {
	ID             string `json:"id"`
	EmployeeName   string `json:"employee_name"`
	EmployeeSalary string `json:"employee_salary"`
	EmployeeAge    string `json:"employee_age"`
	ProfileImage   string `json:"profile_image"`
}

I will create HTTP request with help of third party end points,

e.GET("/employee", func(c echo.Context) error {
		// Build the request
		req, err := http.NewRequest("GET", "http://dummy.restapiexample.com/api/v1/employees", nil)
		if err != nil {
			fmt.Println("Error is req: ", err)
		}

		// create a Client
		client := &http.Client{}

		// Do sends an HTTP request and
		resp, err := client.Do(req)
		if err != nil {
			fmt.Println("error in send req: ", err)
		}

		// Defer the closing of the body
		defer resp.Body.Close()

		// Fill the data with the data from the JSON
		var data Employee

		// Use json.Decode for reading streams of JSON data
		if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
			fmt.Println(err)
		}

		return c.JSON(http.StatusOK, data)
	})

we have created '/employee' end point that will access from browser like 'http://localhost:8080/employee'. Created new GO HTTP request using NewRequest() method. NewRequest() method takes three parameters HTTP request type, HTTP request URL and request body if any.

Created HTTP client using &http.Client{}, send HTTP request using .Do() method that takes HTTP Request as param, after successful HTTP request closed the request body.We are using GO json package to decode and read json response.

Finally send json data with http status code to requester.