Currency Conversion in JavaScript: A Practical Guide
Currency Conversion in JavaScript
Converting currencies in JavaScript can be straightforward, especially with the help of REST APIs like CurrencyRest. In this guide, we'll walk you through how to make currency conversions using JavaScript and Node.js with the fetch API. You’ll be able to convert real money values seamlessly.
Why Use CurrencyRest API?
CurrencyRest provides access to real-time and historical exchange rates for 108 fiat currencies and 94 cryptocurrencies. With a straightforward REST API, you can perform any currency conversion that you need.
Setting Up Your Project
Before diving into the code, ensure you have Node.js set up on your machine:
- Visit nodejs.org to download and install Node.js.
- Create a new project folder and navigate to it in your terminal.
- Run
npm init -yto initialize a new Node.js project. - Install
node-fetchfor making HTTP requests:npm install node-fetch
Making Your First API Call
Here’s how to convert currencies using the CurrencyRest API:
Example: Convert 100 USD to XOF
In your JavaScript file, use the following code:
const fetch = require('node-fetch');
const apiUrl = 'https://api.currencyrest.com/api/v1/convert';
const fromCurrency = 'USD';
const toCurrency = 'XOF';
const amount = 100;
async function convertCurrency(from, to, amount) {
const response = await fetch(`${apiUrl}?from=${from}&to=${to}&amount=${amount}`);
const data = await response.json();
console.log(`Conversion Result: ${data.result}`);
}
convertCurrency(fromCurrency, toCurrency, amount);
Understanding the API Call
In the code above:
- We import the
node-fetchpackage to enable HTTP requests. - We define the API URL and specify the currencies to convert and the amount.
- The
convertCurrencyfunction fetches the conversion result, and the response is logged to the console.
Handling Errors
It’s important to handle potential errors when calling APIs. Here’s an updated version of the conversion function:
async function convertCurrency(from, to, amount) {
try {
const response = await fetch(`${apiUrl}?from=${from}&to=${to}&amount=${amount}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log(`Conversion Result: ${data.result}`);
} catch (error) {
console.error('Error:', error);
}
}
Testing Your Code
To test the conversion, run your file using Node.js:
node yourfile.js
You should see the converted amount printed to the console.
Conclusion
Integrating CurrencyRest into your JavaScript or Node.js applications allows for quick and efficient currency conversions. It offers extensive access to currency pairs and historical data that can enhance any financial application.
Sign Up for CurrencyRest
Don't forget to sign up for CurrencyRest to take advantage of 300 free requests each month with full access to all currency pairs. Start coding your currency conversion solution today!
CurrencyRest
Author