Your First Golang REST API Client

shridhargv

Shridhar G Vatharkar

Posted on October 18, 2022

Your First Golang REST API Client

In this tutorial, we will help you set up your environment and write a program to request data from a REST API, parse the data, and output it to the console. If you have already installed Golang then you can skip the first section of this tutorial and jump to the coding section.

This tutorial covers getting live forex data of a RESTful API but could be adapted to work for any API that provides JSON Data.

For WebSocket implementation read Your First Golang Websocket: FX Data

First, Download and install Golang

First up, download and install GoLang from https://golang.org/doc/install, once you have run the Golang you can open a command window and type the following command you should get the version output.

go -version
go version go1.17.1 windows/amd64
Enter fullscreen mode Exit fullscreen mode

The last thing you need for this program is your TraderMade API Key if you don’t have one you can sign up for free then you can copy it from your dashboard.

Ok, Let’s write some code.

First, we need to add some a package name for this I am just going to use “main” and then we will import some packages we are going to use, encoding/json that will help with parsing JSON, fmt will help with the print statement, io/ioutil will allow the program basic read-write command, log this is used to log message to the console so we can see what the program is doing, and net/http this will allow us to make a get call to the REST Service.

package main
  import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
  )
Enter fullscreen mode Exit fullscreen mode

We then add the main function. it will be the entry point for the program, in this main function we will first define the currencies parameter, the api_key parameter and the URL. The api_key below has a string “your_api_key” where you should insert your api_key.

func main(){
    currencies := "EURUSD,GBPUSD"
    api_key := "your_api_key"
    url := "https://marketdata.tradermade.com/api/v1/live?currency=" + currencies + "&api_key=" + api_key
  }
Enter fullscreen mode Exit fullscreen mode

Now we are going to add a http.Get request using url we defined in the previous step. We will also add some error-catching code that will check the getErr variable that is set when we make the Get call, if this is nil we continue on if not we log an error.

resp, getErr := http.Get(url)
  if getErr != nil {
        log.Fatal(getErr)
  }
Enter fullscreen mode Exit fullscreen mode

Next, we have checked that we received some data back from the Get call we will retrieve the request body using the ioutil.ReadAll function. Again we check for the error in res.Body.

body, readErr := ioutil.ReadAll(res.Body)
  if readErr != nil {
      log.Fatal(readErr)
    }
Enter fullscreen mode Exit fullscreen mode

Now we will need to parse the JSON body but before we could do that we will need to understand what it’s composed of. To do that simply print the string of the body we received inside the main function.

func main(){
    currencies := "EURUSD,GBPUSD"
    api_key := "your_api_key"
    url := "https://marketdata.tradermade.com/api/v1/live?currency=" + currencies + "&api_key=" + api_key
    resp, getErr := http.Get(url)
    if getErr != nil {
      log.Fatal(getErr)
    }
    body, readErr := ioutil.ReadAll(res.Body)
    if readErr != nil {
      log.Fatal(readErr)
    }
    fmt.Println(string(body)) 
   }
Enter fullscreen mode Exit fullscreen mode

and run the file with the command go run “main.go” in the command terminal (we have saved our file as main.go).

{
   "endpoint": "live",
   "quotes": [
    {
     "ask": 1.15537,
     "base_currency": "EUR",
     "bid": 1.15536,
     "mid": 1.15536,
     "quote_currency": "USD"
    },
    {
     "ask": 1.3621,
     "base_currency": "GBP",
     "bid": 1.36208,
     "mid": 1.36209,
     "quote_currency": "USD"
    }
   ],
   "requested_time": "Tue, 12 Oct 2021 11:34:26 GMT",
   "timestamp": 1634038467
}
Enter fullscreen mode Exit fullscreen mode

You can now see above the JSON body we received. However, this is just a string and not very useful if you are working with objects. As Golang is a strongly typed language we will need to do a bit of work before we can parse the data received. We will first have to define the data structure that we want to write our response body to. As you can see the below data struct matches the data we printed above

type data struct {
      Endpoint       string                   `json:'endpoint'`
      Quotes         []map[string]interface{} `json:'quotes'`
      Requested_time string                   `json:'requested_time'`
      Timestamp      int32                    `json:'timestamp'`
  }
Enter fullscreen mode Exit fullscreen mode

Though most of it is straight forward it will be helpful to understand how Quotes inside the data struct is defined.

We have defined Quotes as []map[string]interface{} which in simple language means an array of maps with keys as string type and values as an unknown type. A map is simply a JSON object with keys and values (similar to the dictionary in Python) but in Golang we have to define it. The interface is a slightly different concept but is normally used in parsing JSON when value types are unknown.

Now that we have defined our data structure which was the important bit we simply need to unmarshal it into an object in memory. We will do that by assigning the data struct a variable called data_obj and then the unmarshalling body of data we received into it.

data_obj := data{}
  jsonErr := json.Unmarshal(body, &data_obj)
  if jsonErr != nil {
     log.Fatal(jsonErr)
  }
Enter fullscreen mode Exit fullscreen mode

Now we will print the parsed value and can use them as we need. We will simply print all the values and iterate over the Quotes we defined earlier.

fmt.Println("endpoint", data_obj.Endpoint, "requested time", data_obj.Requested_time, "timestamp", data_obj.Timestamp)
  for key, value := range data_obj.Quotes {
     fmt.Println(key)
     fmt.Println("symbol", value["base_currency"]+value["quote_currency"], "bid", value["bid"], "ask", value["ask"],
"mid", value["mid"])
  }
Enter fullscreen mode Exit fullscreen mode

We can now see we have printed all the values we defined in our data struct. It should be fairly simple to now use these keys and values.

endpoint live requested time Tue, 12 Oct 2021 17:40:05 GMT timestamp 1634060405
0
symbol EUR USD bid 1.15256 ask 1.15256 mid 1.15256
1
  symbol GBP USD bid 1.35834 ask 1.35836 mid 1.35835
Enter fullscreen mode Exit fullscreen mode

Below is the entire code for the Golang that can be copy-pasted to start getting live Forex and CFD data. Do remember to add your API key from your dashboard. Hope this article helps with parsing JSON REST API in Golang. If you like our work or have a suggestion for a future article please leave a comment and clap, we would like to hear from you.

package main
import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)
type data struct {
      Endpoint       string                   `json:'endpoint'`
      Quotes         []map[string]interface{} `json:'quotes'`
      Requested_time string               `json:'requested_time'`
      Timestamp      int32                    `json:'timestamp'`
  }
func main(){
      currencies := "EURUSD,GBPUSD"
      api_key := "your_api_key"
      url := "https://marketdata.tradermade.com/api/v1/live?currency=" + currencies + "&api_key=" + api_key
      resp, getErr := http.Get(url)
      if getErr != nil {
        log.Fatal(getErr)
      }
      body, readErr := ioutil.ReadAll(res.Body)
      if readErr != nil {
        log.Fatal(readErr)
      }
      fmt.Println(string(body)) 
      data_obj := data{}
      jsonErr := json.Unmarshal(body, &data_obj)
      if jsonErr != nil {
         log.Fatal(jsonErr)
      }
      fmt.Println("endpoint", data_obj.Endpoint, "requested time", data_obj.Requested_time, "timestamp", data_obj.Timestamp)
      for key, value := range data_obj.Quotes {
           fmt.Println(key)
           fmt.Println("symbol", value["base_currency"]+value["quote_currency"], "bid", value["bid"], "ask", value["ask"],
      "mid", value["mid"])
      }
 }
Enter fullscreen mode Exit fullscreen mode

TraderMade provides reliable and accurate Forex data via Forex API. You can sign up for a free API key and start exploring real-time and historical data at your fingertips.

Please go through the originally published tutorial on the TraderMade website for Golang REST Client.

Along with that, you can also learn fetching real-time forex data via WebSockets using Golang.

💖 💪 🙅 🚩
shridhargv
Shridhar G Vatharkar

Posted on October 18, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related