Exchange Rate REST API Integration with Ruby On Rails
Currency conversion can be tricky, especially when dealing with foreign exchange rate data.
The foreign currency market transacts over $6 trillion daily, and access to historical exchange rates can provide essential insights.
Instantaneous and accurate currency exchange rates benefit businesses with international operations. But what's the best and easiest way to embed this data into your app?
This post explains how to implement a currency converter API for seamless integration. This easy-to-integrate API will help tackle currency conversion challenges, especially with its support for efficient and reliable API requests. We showcase how to incorporate the CurrencyFreaks Exchange Rate API with Ruby on Rails, a robust web application framework.
This lets you understand that ceramic enterprises manage your ceramic currency conversions. We'll focus on Ruby on Rails along with its integration with live foreign exchange rate data and historical exchange rates for added flexibility.
This guide allows developers to incorporate live currency data into their apps, allowing for accurate currency exchange rates. Simple API requests will enable you to provide your users accurate results without much trouble. Let's dive in.
What's the Exchange Rate REST API?
An exchange rate REST API offers real-time and historical currency values, and many financial data providers provide this service for comprehensive access to exchange information. It works through HTTP requests, often delivering data in JSON format for easy parsing and integration.
With options for different currency pairs, including major currencies like USD, EUR, and GBP, these APIs are crucial for apps dealing with international transactions. An easy-to-use API makes currency conversion seamless, whether working with precious metals or more common currencies.
Integration with an API that supports updates and reliable data is essential for businesses operating globally.
Why Should You Choose Ruby On Rails to Create Currency Exchange Apps?
An exchange rates API offers tools and features to track real-time currency data, historical rates, and even precious metals values. Many APIs pull from reputable sources like the European Central Bank, ensuring accuracy for financial transaction applications.
Why Should You Choose Ruby On Rails to Create Currency Exchange Apps?
Different developers have preferences for programming languages, but Ruby on Rails is an excellent option for currency exchange apps. It follows the MVC (Model-View-Controller) architecture, helping to organize code and simplify development.
Rails provides libraries and tools that simplify using APIs, like exchange rate APIs. For instance, API requests are straightforward with tools like party and rest-client, and Active Record can manage database interactions, handling past exchange rates for currency pairs effortlessly.
The Ruby on Rails community is active and provides ample documentation. It also offers assistance when needed, especially when working with financial data providers.
How Do You Integrate CurrencyFreaks Exchange Rate REST API by Using Ruby On Rails?
To convert your currency exchange widget to a Ruby on Rails app, we'll create a Rail App that fetches exchange rates and renders a view for users. Here are the step-by-step instructions for setting this up in Rails on Windows.
1. Setup Rails Application
Install Rails: Ensure Rails and dependencies are installed. If not:
gem install rails
Create a New Rails Project:
rails new CurrencyExchangeApp
cd CurrencyExchangeApp
Configure Routes: In config/routes.rb, set the root route to the index action:
Rails.application.routes.draw do
root 'currency_converter#index'
end
2. Index.html.erb
Add the code given below to the app/views/currency_converter/index.html.erb file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Currency Exchange Rate Widget</title>
<!-- Google Fonts Import for Poppins -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
<style>
/* General Styling */
body {
font-family: 'Poppins', sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background: linear-gradient(135deg, #e3342f, #f6993f);
color: #333;
}
/* Widget Container */
#currency-widget {
width: 380px;
padding: 35px;
border-radius: 12px;
background: #fff;
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15); /* Soft shadow for depth */
text-align: center;
position: relative;
}
h2 {
font-size: 2.3rem;
color: #e3342f; /* Ruby red */
margin-bottom: 20px;
}
label {
font-size: 1.1rem;
color: #555;
margin-bottom: 8px;
display: block;
}
/* Input Fields */
input[type="text"], input[type="number"] {
width: 100%;
padding: 12px;
margin-bottom: 20px;
border: 2px solid #ddd;
border-radius: 8px;
font-size: 1rem;
background-color: #f9f9f9;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05); /* Soft inset shadow */
transition: border-color 0.3s ease;
}
input[type="text"]:focus, input[type="number"]:focus {
outline: none;
border-color: #e3342f; /* Ruby red border when focused */
}
/* Suggestions List */
.currency-suggestions {
list-style: none;
padding: 0;
margin: 0;
max-height: 150px;
overflow-y: auto;
border-radius: 8px;
background-color: white;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
position: absolute;
width: calc(100% - 24px);
}
.currency-suggestions li {
padding: 10px;
cursor: pointer;
transition: background-color 0.2s ease;
border-bottom: none; /* Remove any bottom borders */
margin: 0; /* Remove margins to avoid lines */
}
.currency-suggestions li:hover {
background-color: #f6993f; /* Light pink hover effect */
color: white;
}
/* Result Display */
#result {
font-size: 1.5rem;
font-weight: bold;
color: #444;
margin-top: 20px;
}
/* Button Styling */
#currency-widget button {
width: 100%;
padding: 15px;
background-color: #e3342f; /* Ruby red */
border: none;
border-radius: 8px;
color: white;
font-size: 1.2rem;
cursor: pointer;
transition: background-color 0.3s ease, transform 0.3s ease;
}
#currency-widget button:hover {
background-color: #f6993f; /* Light pink */
transform: scale(1.03); /* Slight scaling effect on hover */
}
/* Button Active State */
#currency-widget button:active {
background-color: #cc1f1a; /* Darker red when clicked */
transform: scale(0.98); /* Press effect */
}
/* Mobile Friendly Design */
@media screen and (max-width: 768px) {
#currency-widget {
width: 90%;
padding: 20px;
}
}
</style>
</head>
<body>
<div id="currency-widget">
<h2>Currency Converter</h2>
<label for="fromCurrencySearch">From Currency</label>
<input type="text" id="fromCurrencySearch" placeholder="Search currency..." autocomplete="off">
<ul id="fromCurrencySuggestions" class="currency-suggestions"></ul>
<label for="toCurrencySearch">To Currency</label>
<input type="text" id="toCurrencySearch" placeholder="Search currency..." autocomplete="off">
<ul id="toCurrencySuggestions" class="currency-suggestions"></ul>
<label for="amount">Amount</label>
<input type="number" id="amount" value="1">
<div id="result"></div>
<button id="convertButton">Convert</button>
</div>
<!-- JavaScript to handle conversion logic -->
<script>
const API_KEY = 'your_currencyfreaks_api_key'; // Replace with your CurrencyFreaks API key
let currencyRates = {};
let availableCurrencies = [];
const fromCurrencySearch = document.getElementById('fromCurrencySearch');
const toCurrencySearch = document.getElementById('toCurrencySearch');
const fromCurrencySuggestions = document.getElementById('fromCurrencySuggestions');
const toCurrencySuggestions = document.getElementById('toCurrencySuggestions');
const amountInput = document.getElementById('amount');
const resultDiv = document.getElementById('result');
const convertButton = document.getElementById('convertButton');
// Fetch currency data from CurrencyFreaks API
fetch(`https://api.currencyfreaks.com/v2.0/rates/latest?apikey=${API_KEY}`)
.then(response => response.json())
.then(data => {
currencyRates = data.rates;
availableCurrencies = Object.keys(data.rates);
})
.catch(err => console.error('Failed to fetch currency data', err));
function filterCurrencies(query, suggestionsBox) {
suggestionsBox.innerHTML = '';
const filteredCurrencies = availableCurrencies.filter(currency =>
currency.toLowerCase().includes(query.toLowerCase())
);
filteredCurrencies.forEach(currency => {
const li = document.createElement('li');
li.textContent = currency;
li.addEventListener('click', () => {
suggestionsBox.previousElementSibling.value = currency;
suggestionsBox.innerHTML = '';
});
suggestionsBox.appendChild(li);
});
}
fromCurrencySearch.addEventListener('input', function () {
filterCurrencies(fromCurrencySearch.value, fromCurrencySuggestions);
});
toCurrencySearch.addEventListener('input', function () {
filterCurrencies(toCurrencySearch.value, toCurrencySuggestions);
});
convertButton.addEventListener('click', () => {
const fromCurrency = fromCurrencySearch.value.toUpperCase();
const toCurrency = toCurrencySearch.value.toUpperCase();
const amount = parseFloat(amountInput.value);
if (!currencyRates[fromCurrency] || !currencyRates[toCurrency]) {
resultDiv.textContent = 'Please select valid currencies from the suggestions.';
return;
}
if (!isNaN(amount) && amount > 0) {
const convertedAmount = (amount * currencyRates[toCurrency]) / currencyRates[fromCurrency];
resultDiv.textContent = `${amount} ${fromCurrency} = ${convertedAmount.toFixed(2)} ${toCurrency}`;
} else {
resultDiv.textContent = 'Please enter a valid amount.';
}
});
</script>
</body>
</html>
3. application.js
Next, you should add the following code to the app/javascript/application.js:
document.addEventListener('DOMContentLoaded', function () {
const API_KEY = 'ADD-YOUR-API-KEY-HERE'; // Replace with your own API key
const fromCurrencySearch = document.getElementById('fromCurrencySearch');
const toCurrencySearch = document.getElementById('toCurrencySearch');
const fromCurrencySuggestions = document.getElementById('fromCurrencySuggestions');
const toCurrencySuggestions = document.getElementById('toCurrencySuggestions');
const amount = document.getElementById('amount');
const result = document.getElementById('result');
const convertButton = document.getElementById('convertButton');
let currencies = [];
// Fetch all available currency data from CurrencyFreaks API
fetch(`https://api.currencyfreaks.com/v2.0/rates/latest?apikey=${API_KEY}`)
.then(response => response.json())
.then(data => {
currencies = Object.keys(data.rates);
});
function filterCurrencies(query, suggestionsBox) {
suggestionsBox.innerHTML = '';
const filtered = currencies.filter(currency =>
currency.toLowerCase().startsWith(query.toLowerCase())
);
filtered.forEach(currency => {
const li = document.createElement('li');
li.textContent = currency;
li.addEventListener('click', () => {
suggestionsBox.previousElementSibling.value = currency;
suggestionsBox.innerHTML = '';
});
suggestionsBox.appendChild(li);
});
}
fromCurrencySearch.addEventListener('input', function () {
const query = fromCurrencySearch.value;
filterCurrencies(query, fromCurrencySuggestions);
});
toCurrencySearch.addEventListener('input', function () {
const query = toCurrencySearch.value;
filterCurrencies(query, toCurrencySuggestions);
});
convertButton.addEventListener('click', function () {
const fromCurrency = fromCurrencySearch.value;
const toCurrency = toCurrencySearch.value;
const amt = amount.value;
if (!currencies.includes(fromCurrency) || !currencies.includes(toCurrency)) {
result.textContent = 'Invalid currency selection. Please select from the suggestions.';
return;
}
fetch(`https://api.currencyfreaks.com/v2.0/rates/latest?apikey=${API_KEY}&base=${fromCurrency}&symbols=${toCurrency}`)
.then(response => response.json())
.then(data => {
const rate = data.rates[toCurrency];
const convertedAmount = (amt * rate).toFixed(2);
result.textContent = `${amt} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;
});
});
});
4. Run the Rails Server
Start the Rails server with:
rails server
Then open a web browser and navigate to http://localhost:3000 to access the Currency Exchange Widget.
Here is the currency widget we created:
Conclusion
Using Ruby on Rails to integrate an Exchange Rate REST API simplifies currency conversions. Instant conversions are crucial today. Ruby on Rails is a solid framework for building a currency exchange app.
By following this guide, you can easily integrate the CurrencyFreaks API. This integration delivers factual, accurate currency information vital for e-commerce or mobile apps involving currency conversion. With Ruby on Rails, you'll achieve your desired results for currency-related tasks.
FAQs
What Is Exchange Rate API?
An Exchange Rate API provides real-time currency conversion data for various currencies.
What Is the Best API for Exchange Rates?
CurrencyFreaks and Open Exchange Rates are popular and reliable options for exchange rates.
Is ExchangeRate API Free?
Yes, ExchangeRate API offers a free plan with limited requests per month.
Is Forex API Free?
Forex APIs offer free plans, but advanced features often require paid subscriptions.