Building a Currency Converter in Ruby

currencyapi.com provides currency data with update rates ranging from daily to minutely update frequencies. Hence, it is the perfect data provider for your Ruby currency converter. Developer experience is important to us. Therefore, you may access our API using the Ruby SDK, or alternatively via simple GET requests using an HTTP client. In this tutorial, we will focus on accessing the API directly using GET requests.

Simple Ruby Currency Converter Example

The Ruby SDK needs the fewest lines of code. This example uses only Ruby's standard library (net/http and json); run the following code to obtain currency exchange data.

Request

require 'net/http'
require 'json'

url = "https://api.currencyapi.com/v3/latest?apikey=YOUR-API-KEY"
uri = URI(url)
response = Net::HTTP.get(uri)
response_obj = JSON.parse(response)

rates = response_obj['data']

Since USD is set as a default base currency, all exchange rates are relative to USD. If you would like to change this, simply add the desired base_currency parameter to your request:

Request

...
url = "https://api.currencyapi.com/v3/latest?apikey=YOUR-API-KEY&base_currency=EUR"
...

In any case, you will end up with the following JSON response.

JSON response

{
   "meta":{
      "last_updated_at":"2023-08-02T23:59:59Z",
      "base_currency":"USD"
   },
   "data":{
      "ADA":{
         "code":"ADA",
         "value":3.3342788788
      },
      "AED":{
         "code":"AED",
         "value":3.673000426
      },
      "AFN":{
         "code":"AFN",
         "value":85.2268428169
      },
      "...": "..."
   }
}

The values in the JSON response are exchange rates. Since we intend to build a currency converter, we still have to multiply the exchange rate with the amount that we would like to convert, to end up with the desired result.

Converter Endpoint

If you do not wish to take this small extra step, currencyapi.com provides an extra /convert endpoint that was specifically designed for this task. However, it is not available on the free plan (it is available from the Small plan up).