How to create a Currency Converter app using ExchangeRate REST API
Published: 2023-07-19 23:47:14

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](https://www.exchangerate-api.com/) 

- Knowledge of jQuery animation


The repository for this project is located at [Github](https://github.com/Gbadeboife/currency-converter-using-REST-api); fork it to get started. A live demo of this app can also be found on [Vercel](https://currency-converter-app.vercel.app/).

## 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](https://jquery.com/) 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](https://www.ibm.com/topics/rest-apis#:~:text=An%20API%2C%20or%20application%20programming,representational%20state%20transfer%20architectural%20style.) 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](https://www.exchangerate-api.com/). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpwz1328bon80gcn80tp.png)


## Constructing the app
First, we create a file named `index.js` and insert the following code into the `body` tag:
```html

        <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>

```
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`:

![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndbcsw132snujhkb2e6c.png)

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.

```javascript
//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');

```
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

```javascript
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;
};   
```
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:

```javascript
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; 
};
```
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.

```javascript
button.addEventListener('click',getExRate);

```

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

```javascript
//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);
}
);
```

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](https://api.jquery.com/category/effects/).
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.


![](https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExOGoxYjdvdHQ2b2ZubnpuMWVyaDJ2bXJ2MHNkZGlpdWpmbndoeXBmOSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dqCEHC4K14AB6L3Ag9/giphy.gif
)

## 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

- [REST API](https://www.ibm.com/topics/rest-apis#:~:text=An%20API%2C%20or%20application%20programming,representational%20state%20transfer%20architectural%20style.)

- [ExchangeRate-API](https://www.exchangerate-api.com/)

- [jQuery](https://jquery.com/)
- [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat)