DEV Community

Cover image for How to create a Currency Converter app using ExchangeRate REST API
Gbadebo ifedayo
Gbadebo ifedayo

Posted on

How to create a Currency Converter app using ExchangeRate REST API

It is impossible to underplay how crucial currency converters are for navigating the complex nature of the global economy, whether they take the shape of web platforms, smartphone applications, or integrated banking systems.
The ability to accurately price goods and services across borders, as well as the ability to track changes in exchange rate valuations in real-time, make currency conversion valuable in international trade, foreign exchange, travel and other areas of life.
This article demonstrates how to create a Currency Converter app in Vanilla JS using a REST API.

Pre-requisites for this project

  • Understanding of API interaction

  • An ExchangeRate-API account, create one here

  • Knowledge of jQuery animation

The repository for this project is located at Github; fork it to get started. A live demo of this app can also be found on Vercel.

Setting up the project

Including jQuery in the project

jQuery is a Javascript library that optimizes web development by providing solutions that shorten and simplify Javascript code. An instance of this is its collection of preset effects that can be used to manipulate the DOM.
To include jQuery in the app, we download it from jQuery and copy the jquery.min file from it into our app's root directory.

Establishing a connection to the REST API

What is a REST API?

A RESTful API is a method for online information sharing and communication across various computer systems. It functions like a collection of guidelines that allow communication between software programs. When a client (such as a web or mobile application) wants to receive or send data while using a REST API, It makes a request to the API which responds to the request by returning data that was requested by the client.

In this project, we require a REST API that can provide data containing up-to-date conversions between currencies, a great example that is used for this project is ExchangeRate-API. It also offers access to historical exchange rate data, allowing developers to retrieve rates for dates or past periods.
After creating an Exchange Rates API account, we head over to the dashboard to find our API key, URL, and information on our API usage. We can find the link to the documentation in the sidebar to learn more about ExchangeRate-API.

NOTE: Don't share your ExchangeRate API key or URL

ExchangeRate-API Dashboard

Constructing the app

First, we create a file named index.js and insert the following code into the body tag:


        <header>
            <div class="logo">             
                <h1>currency converter <i class="fa fa-money"></i></h1>
                <p class="msg"></p>
            </div>
        </header>

        <div class="actual-page">
            <form action="">
                <label for="amount">Amount</label>
                <input type="number" id="amount" placeholder="0">
                <div class="inputs">
                    <div class="from">
                        <label for="first-input">From</label>
                        <select name="from" id="first-input" onchange="updateCurrencyName()">
                            <option value="UGX">UGX - Ugandan shilling</option>
                            <option value="USD" selected>USD - United States dollar</option>
                            <option value="UYU">UYU - Uruguayan peso</option>
                            <option value="UZS">UZS - Uzbekistani soʻm</option>
                            <option value="VES">VES - Venezuelan bolívar</option>
                        </select>
                    </div>
                    <div class="to">
                        <label for="second-input">To</label>
                        <select name="to" id="second-input" onchange="updateCurrencyName()">    
                            <option value="EUR" selected>EUR - Euro</option>
                            <option value="FJD">FJD - Fijian dollar</option>
                            <option value="FKP">FKP - Falkland Islands pound</option>
                            <option value="GBP">GBP - British pound</option>
                            <option value="GEL">GEL - Georgian lari</option>
                        </select>
                    </div>
                </div>
                <button class="btn" onclick="getExRate()" type="button">Convert <i class="fa fa-exchange"></i></button>
            </form>
        <script src="script.js" defer></script>

Enter fullscreen mode Exit fullscreen mode

In the code above:

-We create two select tags whose values represent the source and destination currencies respectively.

  • The value of the selected option tag is sent to the API and used to obtain conversion rates.

To include additional currencies in the app, more option tags can be added.
Next, the app is styled in style.css:

Next, we create a script.js file in the app's directory to store the code that interacts with the API to fetch the conversion rates.

//Define variables
var fromCurrency=document.querySelector('#first-input');
var toCurrency=document.querySelector('#second-input');
var button=document.querySelector('.btn');
var message=document.querySelector('.msg');
var input=document.getElementById('amount');
const submit=document.querySelector('.submit');
var outputText
const actualPage=document.querySelector('.actual-page');

Enter fullscreen mode Exit fullscreen mode

The first step is to define the variables that will be used in this project. Some of these variables will be assigned to DOM elements.
Next, we develop a function that translates the display price figures to currency format and reduces them to a maximum of two fraction digits. To achieve this, we use Javascript's Intl.NumberFormat which accepts two parameters namely:

  • Language which specifies what language the number is displayed in, e.g., 'en-US', 'de-DE', 'en-GB'

  • A list of options used to customize the result

function formatToCurrency(number,currencyCode){
    var options={
        style:'currency',
        currency:currencyCode,
        maximumFractionDigits:2,
        currencyDisplay:'symbol',
    };
    const currencyFormatText=new Intl.NumberFormat('en-US',options).format(number);
    return currencyFormatText;
};   
Enter fullscreen mode Exit fullscreen mode

The function above contains an object called options which contain the following properties:

  • style: This property determines the formatting style for the number, e.g., decimal, currency, percent

  • currency: This property specifies the currency code or symbol to be used for formatting the number as currency

  • maximumFractionDigits: This property specifies the maximum number of digits to display after the decimal point

  • currencyDisplay: This property determines how the currency should be displayed, e.g., symbol, code, name

Next up, we create an async function getExRate which awaits for the rates to be fetched from the API before calculating the conversion result using the rate between the currencies selected:

async function getExRate(){
    const amount=input.value;   
    const fromText=fromCurrency.value;
    const toText=toCurrency.value;
    const apiKey='72f99500f6844804f605d47c';
    const url =`https://v6.exchangerate-api.com/v6/${apiKey}/latest/USD`;
    const api=await fetch(url);
    const data=await api.json();
    const rates=data.conversion_rates;
    const exchangeRate=rates[toText]/rates[fromText];
    const result= exchangeRate*amount;
    const fromNumber=formatToCurrency(amount,fromText);
    const toNumber=formatToCurrency(result,toText);
    outputText=`${fromNumber} is equal to ${toNumber}`;
    message.textContent=outputText; 
};
Enter fullscreen mode Exit fullscreen mode

The function in the code block above:

  • Collects the value of money to be converted, the currency it is being converted from, and the currency to be converted to

  • Defines a variable url to store the combination of the Exchange rates URL and API key.

  • Creates the variables api and data which fetches the data and converts it to a readable format respectively

  • Calculates the equivalent of the amount in the latter currency

Now that the functions needed for the currency conversion is complete, we call it whenever the convert button is clicked.

button.addEventListener('click',getExRate);

Enter fullscreen mode Exit fullscreen mode

Creating animations with jQuery

Now that the functionality of the app is complete, we add animations that are performed once the app is loaded:

//screen load animations
$(document).ready(function(){
    $('.actual-page').fadeIn(1500);    
    $('.btn').animate({top:'0'},800);
    $('h1').animate({bottom:'0'},800);
    $('figure').animate({top:'0'},1200);
    $('label').animate({bottom:'0'},1000);
}
);
Enter fullscreen mode Exit fullscreen mode

The jQuery code above is placed in a $(document).ready() function and is executed once only when the DOM is fully loaded.
fadeIn() used in the first function is one of the preset effects available in the JQuery library, to learn more on these effects, click here.
As for the remaining functions, the targeted elements have their position property set to relative, and have all been displaced in a direction. The code above reverts their displacement to the default position using the animate function.
In jQuery, DOM elements are accessed with the following methods:

  • By Tag Name e.g $('div')

  • By ID e.g $('#myElement')

  • By Class e.g $('.myClass')

  • By Using CSS Selectors e.g $('#myDiv .myClass')

  • By Traversing the DOM e.g .parent(), .children(), .siblings(), .find(), etc.

Conclusion

In summary, this article gives an overview of REST APIs and then demonstrates how to use JavaScript to retrieve data from ExchangeRate-API in a currency converter application. By following the steps mentioned, we can provide seamless currency conversion functionality for our application.

Resources

Top comments (0)