There are many instances where currencies need to be converted with the most recent and accurate conversion rates. It is time consuming to look up conversion rates manually, so in this article an automatic currency converter will be created in Ninox.
There are several choices of APIs that provide free access to exchange rates. For the purposes of this article, we have chosen CurrencyLayer since the API is simple to use. It is easy to go to currencylayer.com and sign up to get a free API key if you would like to follow along.
To set up, we will need a currencies table to store all of their currency names and their corresponding three letter codes so that new currencies can be added easily from one place. Create a table named “Currencies” with two text fields named “Name” and “Code”.
Now we will create the Table where the currencies will be converted, named “Currency Conversion”. In this table we will create a text field named “Convert”, two links to the “Currencies” table displayed in radio button format named “From” and “To”, a button with label “GO”, and a number field to hold the result of the conversion. From here the following code was inserted into the button click function:
do as server let url := "http://api.currencylayer.com/live?access_key=YOUR ACCESS KEY"; url := url + "¤cies=" + FROM.Code + "," + TO.Code; let response := http("GET", url); let quotesStr := formatJSON(response.result.quotes); let fromConverter := item(split(item(split(quotesStr, "USD" + FROM.Code + """:"), 1), ","), 0); let toConverter := item(split(item(split(quotesStr, "USD" + TO.Code + """:"), 1), "}"), 0); RESULT := CONVERT * number(toConverter) / number(fromConverter) end
In the code above the first three lines in the ‘do as server’ block send in the request to the API with the currencies to be converted from and to. The next three lines work with the result to extract the two converters for the from currency and the to currency. In the last line the conversion is calculated and the result is set to the calculated value.
Now we have a currency converter that can convert based on live conversion rates that can be placed wherever we need it in the database.