Table of Contents

Seamlessly Add Live Currency Rates to Your GoLang Projects

Excited to dive into GoLang? Our dedicated GoLang SDK for CurrencyApi.net is here to accelerate your development process. Whether you're building financial applications, data analytics tools, or backend services, our SDK seamlessly integrates live currency rates into your GoLang projects. Follow along, and you'll master fetching and utilizing real-time currency data in no time!

Installing the GoLang SDK

To begin using the CurrencyApi.net GoLang SDK, ensure you have Go installed (version 1.13 or higher). Install the SDK by running the following command:

go get github.com/houseofapis/currencyapi-go

This command downloads the SDK and adds it to your project's dependencies.

Importing the Golang SDK for live currency rates

After installation, import the SDK into your Go project:

import (
  "fmt"
  "encoding/json"
  "github.com/houseofapis/currencyapi-go"
)

Let's add fmt for logging and encoding/json to be able to parse the JSON response from our Currency API.

Instantiating the Golang Client

To start using the package, create a new client instance by providing your API key:

client := currencyapi.Client('YOUR_API_KEY')

Need an API Key?

Start building your next project with our GoLang SDK. Get started with a free API key and start building your next project.

Fetching Live Currency Rates Using Go

Our most common endpoint for developers is our Rates endpoint. Here's how you can retrieve live currency rates using our Go SDK

Firstly, let's create a Struct to handle our JSON response:

type JsonResponse struct {
  Valid bool
  Result map[string]interface{}
  Error *struct {
      Code    int
      Message string
  }
}

Then let's setup some parameters and get some live currency API data using Go.

package main

import (
  "fmt"
  "encoding/json"
  "github.com/houseofapis/currencyapi-go"
)

type JsonResponse struct {
  Valid bool
  Result map[string]interface{}
  Error *struct {
      Code    int
      Message string
  }
}

func main() {
  client := currencyapi.Client("YOUR_API_KEY")

  ratesParams := map[string]string{
      "output": "JSON",
      "base":   "USD",
  }

  body, err := client.Rates(ratesParams)
  var response JsonResponse
  if nil != json.Unmarshal(body, &response) {
      fmt.Println("Error parsing JSON: ", err)
      return
  }

  if response.Valid {
      fmt.Printf("1 USD  = %f EUR\n", response.Result["EUR"])
  } else {
      fmt.Printf("API returned error: Code: %d, Message: %s\n", response.Error.Code, response.Error.Message)
  }
}

Fantastic. Our first live currency rates using Go. The above code fetches the latest exchange rates with USD as the base currency and outputs what the value in EUR is today.

Available Parameters for Rates Endpoint - Go SDK

Method Description
base Sets the base currency for conversions. This will output all currency conversions for that currency. Default is USD.
output Specifies the response format: JSON or XML. Default is JSON.

Currency Conversion with GoLang SDK

With our API and Go SDK you can convert currency amounts from one currency to another. This is great for just converting the currencies you need.

The response of the Convert endpoint is slightly different to the Rates endpoint, so we should create a new Struct.

type JsonResponse struct {
  Valid bool
  Conversion map[string]interface{}
  Error *struct {
      Code    int
      Message string
  }
}

This Struct targets the conversion key inside the JSON response.

// ... use the same imports from above

type JsonResponse struct {
  Valid bool
  Conversion map[string]interface{}
  Error *struct {
      Code    int
      Message string
  }
}

func main() {
  client := currencyapi.Client("YOUR_API_KEY")

  convertParams := map[string]string{
      "output": "JSON",
      "from":   "USD",
      "to":     "GBP",
      "amount": "15.99",
  }

  body, err := client.Convert(convertParams)
  var response JsonResponse
  if nil != json.Unmarshal(body, &response) {
      fmt.Println("Error parsing JSON: ", err)
      return
  }

  if response.Valid {
      fmt.Printf("%f %s  = %f %s\n", response.Conversion["amount"], response.Conversion["from"], response.Conversion["result"], response.Conversion["to"])
  } else {
      fmt.Printf("API returned error: Code: %d, Message: %s\n", response.Error.Code, response.Error.Message)
  }
}

And there you have it, converted from USD to GBP on the fly using our currency API SDK for Golang.

Available Methods for Convert Endpoint

Method Description
amount The value of the currency you want to convert from. This should be a number and can contain a decimal place. Required.
from The currency you want to convert from. This will be a three-letter ISO 4217 currency code. Required.
to The currency you want to convert to. This will be a three-letter ISO 4217 currency code. Required.
output Specifies the response format: JSON or XML. Default is JSON.

Accessing Historical Currency Rates in GoLang

Retrieve historical currency rates can be a super useful for tracking the history of various currency conversions.

With each request you supply a given date, in the example format 2019-01-01, and all currency conversions of a given currency are returned.

We can use the same style Struct as our Rates endpoint, but with a small tweak to include the historical date.

// ... use the same imports from above

type JsonResponse struct {
  Valid bool
  Date string // added Date here
  HistoricalRates map[string]interface{}
  Error *struct {
      Code    int
      Message string
  }
}

func main() {
  client := currencyapi.Client("YOUR_API_KEY")

  historicalParams := map[string]string{
      "output": "JSON",
      "base":   "GBP",
      "date":   "2019-01-01",
  }

  body, err := client.History(historicalParams)
  var response JsonResponse
  if nil != json.Unmarshal(body, &response) {
      fmt.Println("Error parsing JSON: ", err)
      return
  }

  if response.Valid {
      fmt.Printf("1 GBP  = %f JPY on %s\n", response.HistoricalRates["JPY"], response.Date)
  } else {
      fmt.Printf("API returned error: Code: %d, Message: %s\n", response.Error.Code, response.Error.Message)
  }
}

It is as simple as that. We have historical data on a wide range of currencies going back to the year 2000!

Available Parameters for Historical Endpoint - Go SDK

Method Description
date The historical date you wish to receive the currency conversions for. This should be formatted as YYYY-MM-DD. Required.
base Sets the base currency for conversions. Default is USD.
output Specifies the response format: JSON or XML. Default is JSON.

Accessing Live Currency Rates Within a Timeframe

If you need to access currency rates between a specific time frame, you can use our timeframe endpoint. This timeframe can be up to a year long.

We are going to need a slightly different Struct as each day in between the start and end date will supply a different object.

// ... use the same imports from above

type JsonResponse struct {
  Valid     bool
  StartDate string
  EndDate   string
  TimeframeRates     map[string]map[string]float64
  Error     *struct {
      Code    int
      Message string
  }
}

func main() {
  client := currencyapi.Client("YOUR_API_KEY")

  timeframeParams := map[string]string{
      "output": "JSON",
      "base":   "GBP",
      "start_date": "2019-01-01",
      "end_date": "2019-01-02",
  }

  body, err := client.Timeframe(timeframeParams)
  var response JsonResponse
  if nil != json.Unmarshal(body, &response) {
      fmt.Println("Error parsing JSON: ", err)
      return
  }

  if response.Valid {
      for date, rates := range response.TimeframeRates {
          fmt.Printf("Date: %s\n", date)
          for currency, rate := range rates {
              fmt.Printf("Currency: %s, Rate: %f\n", currency, rate)
          }
      }
  } else {
      fmt.Printf("API returned error: Code: %d, Message: %s\n", response.Error.Code, response.Error.Message)
  }
}

The API returns multiple days of currency rates in a single response, making it easy to build applications that track currency rates over time.

Available Parameters for Timeframe Endpoint - Go SDK

Method Description
start_date The start date for the time frame. Format: YYYY-MM-DD. Required.
end_date The end date for the time frame. Format: YYYY-MM-DD. Required.
base Sets the base currency for conversions. Default is USD.
output Specifies the response format: JSON or XML. Default is JSON.

Error Handling In Golang

In Golang, we use the error type to handle errors. This allows us to gracefully handle errors and provide meaningful error messages to the user.

You can see from the examples above, it's not only important to check the error from the API, it's also important to handle JSON parsing errors and the request itself.

Best Practices using Golang SDK

To optimize your use of the CurrencyApi.net GoLang SDK, consider the following best practices:

  • Implement caching to minimize API calls and improve performance.
  • Validate API responses to ensure data integrity.
  • Store your API key securely using environment variables or a secure configuration file.
  • Stay updated with the SDK documentation for new features and updates.
  • Always check for errors after making API calls to handle any issues that may arise.

Handling Responses from the Golang SDK

JSON Response in Go

By default, the SDK returns responses in JSON format. You can parse the JSON response into Go structs for easier data manipulation.

XML Response in Go

To receive responses in XML format, specify the output parameter as 'XML':

params := map[string]string{
  "output": "XML", // or "JSON"
  "base":   "USD",
}

body, err := client.Rates(params)

You can then process the XML response using Go's XML parsing libraries.

Conclusion

The GoLang SDK for CurrencyApi.net provides a powerful and efficient way to integrate live currency rates into your Go applications. With straightforward methods and comprehensive support, you can enhance your financial applications with real-time data seamlessly.

Other Useful Links:

Explore Other SDKs

Not using GoLang? Check out our other SDKs below:

Python SDK

Integrate our Currency API into your Python applications with ease. Access live exchange rates and perform currency conversions effortlessly.

Explore the Python SDK →

NodeJs SDK

Enhance your NodeJs applications with real-time currency data. Our SDK offers seamless integration and powerful features.

Discover the NodeJs SDK →

PHP SDK

Connect to our Currency API from your PHP projects effortlessly. Stay updated with the latest currency rates and conversions.

Check out the PHP SDK →

Grab an API key and get coding with GoLang today!

Use our GoLang SDK to integrate live currency rates into your GoLang applications.

Meet the Author

Oli Girling

Founder & Senior Software Engineer

London, UK

Connect with Oli on LinkedIn