Hello Guys,
As per daily transaction we needed the currency conversion. Open exchange rates provides the API for the same.
Let’s implement the API along with our ruby application:
First of all install listed gems and than proceed
require ‘rubygems‘
require “uri”
require “net/https”
require ‘json‘
def currency_conversion(source_currency, target_currency, date, original_amount)
if date == Time.now.to_date
parsed_url = URI.parse(“http://openexchangerates.org/latest.json“)
else
parsed_url = URI.parse(“http://openexchangerates.org/historical/#{date.year}-#{date.strftime(‘%m’)}-#{date.strftime(‘%d’)}.json”)
end
begin
response = Net::HTTP.get_response(parsed_url)
rescue
response = nil
end
if !response.nil? && response.class == Net::HTTPOK
data = JSON.parse(response.body)
base_currency = data[“base”]
target_rate = data[“rates”][target_currency].to_f
base_rate = data[“rates”][source_currency].to_f
exchange_rate = target_rate / base_rate
converted_amount = original_amount * exchange_rate
puts “#{original_amount} #{source_currency} = #{converted_amount} #{target_currency}”
end
end
Invoke from method by passing appropriate parameters:
source_currency: Currency from which you have to convert amount
target_currency: Currency in which you need converted amount
date: Conversion rate for required date
original_amount: Amount in source currency
currency_conversion(‘USD’, ‘INR’, Time.now.to_date, 1)
Hope this article useful to you. One more important thing if you have the AppId than you can use it by passing the AppId along with each api call.
Below is the syntax to amend the AppId:
http://openexchangerates.org/latest.json?app_id=%5BAPP_ID%5D or
http://openexchangerates.org/historical/%5BYEAR%5D-%5BMON%5D-%5BDay%5D.json?app_id=%5BAPP_ID%5D
For more information follow http://openexchangerates.org/documentation