These days, most web applications require real-time currency rate data. This helps users make educated decisions. Currency exchange rates are essential, whether it's a Svelte currency converter, financial dashboard, or e-commerce website. They need to be precise, up-to-date, and backed by reliable historical exchange rate data.

Integrating exchange rate APIs can be complex for beginners, especially when handling multiple API requests. But not with Svelte. Svelte is a modern, reactive framework that compiles Svelte components into efficient JavaScript at build time, making it fast and easy to use for apps like currency converters.

In this blog, we will show how to combine the CurrencyFreaks API with Svelte JS, handling both real-time and historical exchange rate data. The procedure will include getting the API key and creating a working currency converter.

You can also explore our guide on using a currency rates API with Python for backend integration.

How Do You Create a Svelte Currency Converter Using CurrencyFreaks API?

Follow the steps given below to create a Svelte currency converter:

Get the API Key

You should create an account with CurrencyFreaks. Next, you should log in to that account to get your API request key.

Choose the Desired Endpoint

CurrencyFreaks offers multiple endpoints for fetching the currency data. You can explore it through the CurrencyFreaks documentation. It is important to study those API endpoints before integrating them. It will help you choose which endpoint suits your project the most.

CurrencyFreaks Documentation Page

In this guide, we will choose the current currency exchange rates endpoint given below:

https://api.currencyfreaks.com/v2.0/rates/latest?apikey=YOUR_APIKEY

Here is the example response:

{

"date": "2023-03-21 12:43:00+00",

"base": "USD",

"rates": {

"AGLD": "2.3263929277654998",

"FJD": "2.21592",

"MXN": "18.670707655673546",

"LVL": "0.651918",

"SCR": "13.21713243157135",

"CDF": "2068.490771",

"BBD": "2.0",

"HNL": "24.57644632001569",

.

.

.

}

}

Build Your App

Step 1: Set up a Svelte project

If you don't already have Svelte installed, start by setting up a Svelte project.

  1. Install Node.js (if you haven't already).
  2. Run the following commands in your terminal:
npx degit sveltejs/template currency-widget

cd currency-widget

npm install

npm run dev

This will set up a basic Svelte project and run it locally on your machine.

Step 2: Create a CurrencyWidget.svelte File

In your main project directory, create a new Svelte component and name it CurrencyWidget.svelte. Paste the below-given code to the newly created file:

<script lang="ts">

    import { onMount } from "svelte";

    let fromCurrency: string = "USD";

    let toCurrency: string = "EUR";

    let amount: number = 1;

    let result: string = "";

    let currencies: string[] = [];

    const API_KEY: string = 'add-your-api-key'; // Replace with your API key

    onMount(async () => {  
    try {  
        const response = await fetch(`https://api.currencyfreaks.com/v2.0/rates/latest?apikey=${API_KEY}`);  
        const data = await response.json();  
        currencies = Object.keys(data.rates);  
        updateResult();  
    } catch (error) {  
        console.error("Failed to fetch rates:", error);  
    }  
});

    async function updateResult() {  
    try {  
        const response = await fetch(`https://api.currencyfreaks.com/v2.0/rates/latest?apikey=${API_KEY}&base=${fromCurrency}&symbols=${toCurrency}`);  
        const data = await response.json();  
        const rate: number = data.rates[toCurrency];  
        const convertedAmount: string = (amount * rate).toFixed(2);  
        result = `${amount} ${fromCurrency} = ${convertedAmount} ${toCurrency}`;  
    } catch (error) {  
        console.error("Conversion failed:", error);  
        result = "Conversion failed. Please try again.";  
    }  
}

</script>

<style>

   

    /* Widget container */

    #currency-widget {

        width: 450px;

        padding: 40px;

        border-radius: 20px;

        background-color: #f0f4f8;

        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);

        text-align: center;

        margin: 0 auto;

        margin-top: 10%;

        position: relative;

        top: 20%;

        transform: translateY(-20%);

        background: linear-gradient(135deg, #f0f4f8, #e2e8f0);

        background-size: cover;  

        background-position: center;  

        background-repeat: no-repeat;

    }

    /* Modernized heading */

    h2 {

        margin-top: 20%;

        font-size: 2em;

        font-weight: 700;

        color: #333;

        margin-bottom: 20px;

        letter-spacing: 0.05em;

    }

    label {

        font-size: 1.1em;

        font-weight: 600;

        color: #555;

        margin-bottom: 10px;

        display: block;

        text-align: left;

    }

    /* Smooth and rounded input styles */

    select, input {

        width: 80%;

        padding: 14px;

        margin-bottom: 20px;

        border: none;

        border-radius: 12px;

        font-size: 1em;

        background-color: #ffffff;

        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.05);

        color: #333;

    }

    /* Focus effect for better user experience */

    select:focus, input:focus {

        outline: none;

        box-shadow: 0 0 10px rgba(33, 147, 176, 0.3);

    }

    /* Stylish result display */

    #result {

        font-size: 1.4em;

        font-weight: bold;

        color: #333;

        margin-top: 20px;

        background-color: #edf7fa;

        padding: 15px;

        border-radius: 12px;

        border: 1px solid #ddd;

    }

    /* Redesigned button for a fresh look */

    button {

        width: 100%;

        padding: 15px;

        background-color: #b02185;

        border: none;

        border-radius: 12px;

        color: white;

        font-size: 1.2em;

        font-weight: bold;

        cursor: pointer;

        transition: background-color 0.3s ease, transform 0.2s ease;

    }

    /* Button hover effect */

    button:hover {

        background-color: #6d82ed;

        transform: translateY(-3px);

    }

    button:active {

        transform: translateY(0);

    }

</style>

<div id="currency-widget">

    <h2>Simple Currency Converter App</h2>

    <label for="fromCurrency">From Currency</label>

    <select id="fromCurrency" bind:value={fromCurrency}>

        {#each currencies as currency}

            <option value={currency}>{currency}</option>

        {/each}

    </select>

    <label for="toCurrency">To Currency</label>

    <select id="toCurrency" bind:value={toCurrency}>

        {#each currencies as currency}

            <option value={currency}>{currency}</option>

        {/each}

    </select\>

    <label for="amount">Amount</label>

    <input type="number" id="amount" bind:value={amount} min="1">

    <div id="result">{result}</div>

    <button on:click={updateResult}>Convert</button>

</div>

  • Real-time currency exchange rates come from CurrencyFreaks API. Selected currencies, amount, and result are stored as Svelte reactive variables.
  • The onMount function fetches all available currencies. This fills in the drop-down menus. Users select the "From" and "To" currencies.
  • Next, they enter the amount to be converted and click a button to execute the conversion. The conversion result is displayed on the screen. Users will appreciate the modern design, smooth inputs, hover effects on the button, and a beautiful container.

Step 3: Modify App.svelte Code

Inside your App.svelte file, paste the following code:

<script>

    import CurrencyWidget from './CurrencyWidget.svelte';

</script>

<main>

    <CurrencyWidget />

</main>

This code imports the CurrencyWidget Svelte component. The Svelte component is located in the CurrencyWidget.svelte file. Inside the <main> block, it uses this widget. The CurrencyWidget is then displayed on the page. This allows the parent component to show the widget and its functionality.

Step 4: Running the project

Now, run the following command to start the development server:

npm run dev

Visit http://localhost:5173 in your browser to see the currency exchange widget working with Svelte.

Step 5: Test the App

When you start the development server, you should see the screen given below:

Output 1

Enter the desired currencies and see the amount converted above the “Convert” button. You can select the currencies through the drop-down menu as shown below:

Output 2Output 3

Building the Currency Converter with SvelteKit

While the Svelte component works standalone, most modern Svelte apps are built with SvelteKit, which provides routing, server-side rendering, and better performance. Here’s how you can integrate the CurrencyFreaks API in a SvelteKit project:

// src/routes/+page.svelte  
<script lang="ts">  
import { onMount } from 'svelte';  
import { writable, get } from 'svelte/store';

export let data: any;  
const rates = writable({});  
const fromCurrency = writable('USD');  
const toCurrency = writable('EUR');  
const amount = writable(1);  
const result = writable('');

onMount(() => {  
    rates.set(data.rates);  
    updateResult();  
});

async function updateResult() {  
    const $from = get(fromCurrency);  
    const $to = get(toCurrency);  
    const $amount = get(amount);  
    const rate = get(rates)[$to];  
    result.set(`${$amount} ${$from} = ${(rate * $amount).toFixed(2)} ${$to}`);  
}  
</script>

Server Load Example (SvelteKit Endpoint)

// src/routes/api/rates/+server.ts  
import type { RequestHandler } from './$types';

export const GET: RequestHandler = async () => {  
    const API_KEY = 'add-your-api-key';  
    const res = await fetch(`https://api.currencyfreaks.com/v2.0/rates/latest?apikey=${API_KEY}`);  
    const data = await res.json();  
    return new Response(JSON.stringify(data));  
};

By fetching the rates server-side with SvelteKit, your app loads faster and avoids exposing the API key in the browser. This SvelteKit-specific approach ensures your currency converter app is fully optimized and production-ready.

Why Should You Choose Svelte JS with CurrencyFreaks Currency Exchange Rates API?

Combining the CurrencyFreaks API with Svelte.js is a great choice for developers looking to create a responsive app for currency conversion with real-time accuracy.

  • Svelte is a minimalist JavaScript framework that compresses code during the build, enabling apps to run faster. This enhances user experience and reduces load times, especially when handling frequent API requests for exchange rate updates.
  • The CurrencyFreaks API provides accurate rates for 1000 currencies, including 160 fiat currencies sourced from trusted providers such as the European Central Bank. This ensures your users always see current and reliable information.
  • Integrating this easy-to-integrate API with Svelte is simple. Svelte’s intuitive structure simplifies API integration, reducing development time and effort. Your app will display real-time currency exchange rates effortlessly and enable users to perform currency conversions without delay.
  • For developers needing more information on custom pricing, CurrencyFreaks offers tailored options based on your API usage. This combination of Svelte and CurrencyFreaks creates a high-performing Svelte currency converter with seamless updates, ensuring performance reliability.

Conclusion

You can easily implement the CurrencyFreaks API with Svelte JS to create a real-time Svelte currency converter. Svelte enables fast, easy application development. It also reduces the code needed to load the app. CurrencyFreaks provides the latest exchange rates for over 1,000 currencies, including 160+ fiat currencies. It gives the most accurate currency exchange rates.

Setting up a working Svelte currency converter takes just a few steps. This combination makes your app responsive and convenient for users. With Svelte and CurrencyFreaks, you can always deliver fast, accurate real-time currency data.

👉Looking for the 10 best currency exchange APIs? Explore now.

FAQs

How To Build A Svelte Exchange Rate App?

You can create a Svelte exchange rate app by building a component that fetches currency rates from an API like CurrencyFreaks. Use reactive variables to update conversions in real time. Svelte’s simple syntax and reactivity make it ideal for handling user input and displaying instant results.

SvelteKit API Integration Tutorial For Currency Conversion

In SvelteKit, integrate APIs either client-side with onMount or server-side using endpoints. Server-side fetching keeps your API key secure and improves performance. Combine Svelte stores with reactive variables to display live currency conversion results efficiently.

How To Display Real-Time Currency Rates In Svelte?

Use Svelte stores to store API response data and reactive variables to calculate conversions dynamically. Fetch rates from CurrencyFreaks and update the UI automatically whenever users select different currencies or input amounts. This approach ensures smooth, real-time updates without manual refreshes.

Best Practices For Building Svelte Currency Converters

Always fetch sensitive API data server-side in SvelteKit to avoid exposing your API key. Use reusable components for modularity, and handle errors gracefully to improve user experience. Applying CSS gradients and smooth input styles enhances usability while keeping the app visually appealing.

Sign up for free at CurrencyFreaks to fetch real-time currency rates.