Currency Converter Web App Using CurrencyLayer API

Currency Converter Web App Using CurrencyLayer API

In today’s globalized world, currency conversion is a common requirement for individuals and businesses alike. Whether you are shopping online, traveling, or conducting international transactions, knowing the value of one currency relative to another is essential. One of the easiest ways to integrate real-time currency conversion into your website is by using APIs, and in this article, we’ll walk you through building a simple currency converter app using the CurrencyLayer API.

What is CurrencyLayer API?

CurrencyLayer is a popular API service that provides real-time and historical exchange rates for over 170 world currencies. With its straightforward API, developers can access exchange rates, historical data, and currency information. CurrencyLayer supports a wide range of endpoints to get accurate, up-to-date currency information, making it an excellent choice for any web application or financial tool.

How Does the Currency Converter Work?

In this article, we will build a Currency Converter Web App that allows users to:

  1. Select a source and target currency.
  2. Input an amount to convert.
  3. Get real-time conversion results with the latest exchange rate.

We will leverage CurrencyLayer’s API to fetch the list of currencies and the conversion rates between them. Let’s dive into the steps involved in building this tool.

Follow this video for complete guidance:

Currency Converter – Full Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Currency Converter Pro</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <style>
        body{
            background: radial-gradient(circle at top right, #1a1a1a, #000000);
        }
        .glass-card { 
            backdrop-filter: blur(10px); 
            background: rgba(255, 255, 255, 0.8); 
        }
        .currency-bg {
            background: linear-gradient(120deg, #6B73FF 0%, #000DFF 100%); 
        }
        .glow { 
            box-shadow: 0 0 30px rgba(107, 115, 255, 0.3); 
        }
        .hover-scale:hover { 
            transform: scale(1.02); 
            transition: transform 0.3s ease; 
        }
    </style>
</head>
<body class="min-vh-100 d-flex align-items-center py-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card border-0 rounded-4 glass-card glow hover-scale">                    
                    <div class="card-body p-4 p-lg-5">
                        <div class="text-center mb-5">
                            <h1 class="display-4 text-primary fw-bold mb-2">
                                <i class="fas fa-globe-americas me-2"></i>Exchange
                            </h1>
                            <p class="text-muted lead">Real-time currency conversion</p>
                        </div>

                        <!-- Amount Input -->
                        <div class="mb-4 position-relative">
                            <div class="input-group input-group-lg">
                                <span class="input-group-text border-0 currency-bg text-white">
                                    <i class="fas fa-coins"></i>
                                </span>
                                <input type="number" id="amount" class="form-control form-control-lg border-0 shadow-none" placeholder="Enter amount" value="1">
                            </div>
                        </div>

                        <!-- Currency Selectors -->
                        <div class="row g-4 mb-4">
                            <div class="col-6">
                                <select id="fromCurrency" class="form-select form-select-lg border-0">
                                    <option value="">Loading...</option>
                                </select>
                            </div>
                            <div class="col-6">
                                <select id="toCurrency" class="form-select form-select-lg border-0">
                                    <option value="">Loading...</option>
                                </select>
                            </div>
                        </div>

                        <!-- Convert Button -->
                        <button id="convertBtn" class="btn btn-lg w-100 mb-4 text-white currency-bg hover-scale">
                            <i class="fas fa-exchange-alt me-2"></i>Convert
                        </button>

                        <!-- Result Card -->
                        <div id="result" class="p-4 rounded-4 text-center d-none position-relative overflow-hidden">
                            <h3 class="conversion-result mb-2 fw-bold"></h3>
                            <p class="text-muted mb-0 small">Updated: <span id="updateTime"></span></p>
                        </div>

                        <!-- Loading -->
                        <div id="loading" class="text-center d-none">
                            <div class="spinner-border text-primary" role="status"></div>
                        </div>

                        <!-- Error -->
                        <div id="error" class="alert alert-danger d-none"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script>
        const API_KEY = 'YOUR_API_KEY';
        
        // Load currencies
        $.get(`https://api.currencylayer.com/list?access_key=${API_KEY}`, data => {
            if (data.success) {
                const options = Object.entries(data.currencies)
                    .map(([code, name]) => `<option value="${code}">${code} - ${name}</option>`)
                    .join('');
                $('#fromCurrency').html(options).val('USD');
                $('#toCurrency').html(options).val('EUR');
            }
        });

        // Convert currency
        $('#convertBtn, #amount').on('click keypress', e => {
            if (e.type === 'keypress' && e.key !== 'Enter') return;
            
            const amount = $('#amount').val();
            const from = $('#fromCurrency').val();
            const to = $('#toCurrency').val();

            $('#loading').removeClass('d-none');
            $('#result, #error').addClass('d-none');
            $('#convertBtn').prop('disabled', true);

            $.get(`https://api.currencylayer.com/convert?access_key=${API_KEY}&from=${from}&to=${to}&amount=${amount}`)
                .done(data => {
                    if (data.success) {
                        const result = `${parseFloat(amount).toLocaleString()} ${from} = ${data.result.toLocaleString()} ${to}`;
                        $('.conversion-result').text(result);
                        $('#updateTime').text(new Date().toLocaleString());
                        $('#result').removeClass('d-none');
                    } else {
                        throw new Error(data.error.info);
                    }
                })
                .fail(err => {
                    $('#error').text(err.message).removeClass('d-none');
                })
                .always(() => {
                    $('#loading').addClass('d-none');
                    $('#convertBtn').prop('disabled', false);
                });
        });
    </script>
</body>
</html>

 

 


Step 1: Setting Up the Frontend

The app is designed with a clean, modern, and responsive UI using Bootstrap 5 and Font Awesome icons. The design includes the following components:

  • Amount Input Field: A number input where users can enter the amount they want to convert.
  • Currency Selectors: Dropdown menus to select the source currency (e.g., USD) and the target currency (e.g., EUR).
  • Convert Button: A button to trigger the conversion process.
  • Result Card: A container to display the conversion result and the time the conversion was last updated.
  • Loading Spinner: A spinner that appears while the conversion is being processed.
  • Error Handling: A message box that displays errors (e.g., API issues or invalid data).

Step 2: Using the CurrencyLayer API

To retrieve currency data and perform the conversion, we will make two primary API calls:

  1. List of Currencies: To get all available currencies supported by the API.
    • Endpoint: https://api.currencylayer.com/list?access_key=YOUR_API_KEY
    • This call returns a list of all currencies, which will be populated into the dropdown menus for users to select from.
  2. Currency Conversion: To convert the entered amount from one currency to another.
    • Endpoint: https://api.currencylayer.com/convert?access_key=YOUR_API_KEY&from=FROM_CURRENCY&to=TO_CURRENCY&amount=AMOUNT
    • This endpoint requires the source currency, target currency, and the amount to be converted.

Both endpoints require an API key, which you can obtain by signing up for a free or paid plan on the CurrencyLayer website.


Step 3: Integrating CurrencyLayer API with JavaScript

The backend part of the web application uses JavaScript (with jQuery) to interact with the CurrencyLayer API. Here’s a quick overview of how we handle the API requests:

  • Loading Currencies: On page load, we call the list endpoint to retrieve all supported currencies and populate the dropdown menus for users to select from.
  • Currency Conversion: When the user clicks the “Convert” button or presses the “Enter” key, the app triggers the convert API endpoint to fetch the conversion rate and display the result.

Here is how the data is handled:

  • The amount entered by the user is fetched from the input field.
  • The selected source and target currencies are taken from the dropdown menus.
  • A call is made to the CurrencyLayer convert endpoint, and the result is displayed on the page.

Step 4: Error Handling and UX Improvements

To improve user experience, we’ve incorporated:

  • Loading Spinner: While waiting for the API response, a loading spinner appears, ensuring users know that the system is processing their request.
  • Error Display: If something goes wrong—whether it’s an invalid API key or a network error—the app shows an error message to the user.

The conversion result includes:

  • The amount entered by the user, along with the source and target currencies.
  • The converted amount based on real-time exchange rates.
  • The time the exchange rate was last updated, ensuring transparency.

CurrencyLayer API Endpoints Used

  1. List of Currencies: This endpoint provides a complete list of available currencies that you can use for conversion. It returns a JSON object where the key is the currency code (e.g., USD, EUR) and the value is the currency name (e.g., United States Dollar, Euro).
    • Endpoint: https://api.currencylayer.com/list?access_key=YOUR_API_KEY

    This data is used to populate the dropdown menus for the user to select their source and target currencies.

  2. Currency Conversion: The conversion endpoint allows you to convert an amount from one currency to another. You simply pass the source currency, target currency, and amount in the URL parameters.
    • Endpoint: https://api.currencylayer.com/convert?access_key=YOUR_API_KEY&from=FROM_CURRENCY&to=TO_CURRENCY&amount=AMOUNT

    This is where the real magic happens, as it returns the converted amount based on the latest exchange rate.


Conclusion

By integrating the CurrencyLayer API, we’ve built a fully functional and easy-to-use Currency Converter Web App. The app allows users to convert currencies in real time, ensuring they have the most up-to-date conversion rates available.

With its simple interface, smooth user experience, and the power of the CurrencyLayer API, this currency converter is a practical tool for anyone needing to perform currency conversions on the fly. Whether you’re running a business with international clients, planning your next vacation, or just curious about currency rates, this tool can serve as a reliable companion.


API Key and Access To use the CurrencyLayer API, you need to sign up on their website and obtain an API key. The API offers both free and paid plans, depending on your needs. The free plan gives access to limited features, such as hourly exchange rates for a subset of currencies. For more extensive use, the premium plans provide full access to real-time, historical data, and more.

Start integrating the CurrencyLayer API today and build your own currency conversion tools with ease!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *