1 year ago
5 min read
Integrating CurrencyApi in Golang: A Comprehensive Guide to using our API with Go
Whether you’re a finance enthusiast building a personal project or a professional developer integrating global transactions, accessing live currency rates is paramount. In the ocean of APIs available, CurrencyAPI.net stands out as a reliable beacon, offering up-to-date rates, historical data, and more. But how do you seamlessly incorporate this into your Go applications? That’s where our guide dives in! Join us as we unravel the art of using the GoLang wrapper for CurrencyAPI, diving deep into the realms of JSON and XML parsing. Trust me, by the end of this, you’ll be converting currencies in your Go applications like a pro!
Today we are going to cover:
- Getting Started with the Go Wrapper for CurrencyAPI
- A Detailed Look at Each Endpoint
- Parsing and Handling Responses in Go
- Final Thoughts
Getting Started with the Go Wrapper for CurrencyAPI
To get started, you will need a paid or free currency api account with us. Then grab your unique API key which can be found in the account section.
Installation
Before diving into the methods provided by our wrapper, you need to have it in your Go environment. Installing it is a breeze:
go get github.com/houseofapis/currencyapi
Initialisation
To use the wrapper, initialise a new client using your API key:
import "github.com/houseofapis/currencyapi" client := currencyapi.Client("YOUR_API_KEY")
A Detailed Look at Each Endpoint
Rates()
Fetch the latest currency rates with this method:
params := map[string]string{ "output": "JSON", // or "XML" "base": "USD", } body, err := client.Rates(params)
Currencies()
Retrieve a list of all supported currencies:
params := map[string]string{"output": "XML"} // or "JSON" body, err := client.Currencies(params)
Convert()
Convert one currency to another:
params := map[string]string{ "output": "JSON" "from": "USD", "to": "GBP", "amount": 15.99", } body, err := client.Convert(params)
History()
Get the exchange rate for a specific date:
params := map[string]string{ "output": "JSON" "base": "GBP", "date": "2019-01-01", } body, err := client.History(params)
Timeframe()
Extract rates within a specific timeframe:
params := map[string]string{ "output": "JSON" "base": "GBP", "start_date": "2019-01-01", "end_date": "2019-01-05", } body, err := client.Timeframe(params)
Parsing and Handling Responses in Go
The wrapper conveniently returns the body of the response, making it easy for you to parse it according to your needs.
Handling JSON Responses
To parse JSON responses, make use of Go’s encoding/json
.
import ( ... "encoding/json" ... )
And we can use the json.Unmarshal()
method to turn it into a struct. So next, we need that struct.
Here are some examples of what the response data looks like. For a successful response in JSON, we would get:
{ "valid": true, "updated": 1696527122, "base": "USD", "rates": { "AED": 3.673, "AFN": 77, "ALL": 100.65, "AMD": 418.52, "ANG": 1.802957, "AOA": 827.5, .... } }
For an api error, we might get:
{ "valid": false, "error": { "code": 401, "message": "Your API key is not valid" } }
So lets cater for both in a JsonResponse
struct:
type JsonResponse struct { Valid bool `json:"valid"` Error *struct { Code. int `json:"code"` Message string `json:"message"` } `json:"error"` Result map[string]interface{} `json:"rates"` }
I have put Result to be mapped to the rates
JSON key. For this example, I am going to use the Rates()
which calls the /rates
endpoint and the currency data is returned under the rates
key. Be sure to check the api documentation for the structure of the other endpoints.
Great, now we are ready to use json.Unmarshal()
on the response and turn it into a struct.
var response JsonResponse if nil != json.Unmarshal(body, &response) { fmt.Println("Error parsing JSON: ", err) return }
Then we can check if the response is valid and if so, get one of the currency values (EURO). If the response is not valid, we can print out the error code and message from the api response.
if response.Valid { fmt.Println(response.Result["EUR"]) } else { fmt.Printf("API returned error: Code: %d, Message: %s\n", response.Error.Code, response.Error.Message) }
Now lets put it all together (make sure to replace the API key):
package main import ( "fmt" "encoding/json" "github.com/houseofapis/currencyapi" ) type JsonResponse struct { Valid bool `json:"valid"` Error *struct { Code int `json:"code"` Message string `json:"message"` } `json:"error"` Result map[string]interface{} `json:"rates"` } type XmlResponse struct { Valid bool `xml:"valid"` Error *struct { Code int `xml:"code"` Message string `xml:"message"` } `xml:"error"` Result map[string]interface{} `xml:"rates"` } 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.Println(response.Result["AED"]) } else { fmt.Printf("API returned error: Code: %d, Message: %s\n", response.Error.Code, response.Error.Message) } }
Final Thoughts
Our CurrencyAPI Go wrapper aims to simplify your experience with our currency conversion APIs. By employing this wrapper, not only can developers swiftly integrate CurrencyAPI.net into their Go applications, but they also gain an edge in handling various outputs with precision. Whether you’re developing a FinTech app, an eCommerce platform, or just need currency conversion for your next project, this wrapper is your ticket to a streamlined development process!
For more information about our Currency API go wrapper, head to the Github.
Outro
Stay tuned for more guides, and be sure to check our repository for updates and additional functionalities. If you found this guide helpful, share it with your fellow Gophers and help them harness the power of CurrencyAPI in Go with ease.