Ever thought about adding exchange rates and currency conversion to your Node.js app? This is for you if you’re building a business app that deals with money from different countries. In this blog, we’ll talk about CurrencyLayer API, a tool that helps fetch real-time exchange rates. Moreover, we will also create a Node JS currency converter. We’ll explain why CurrencyLayer is a great choice, what it offers, and how it can save you time by providing ready-made solutions.
You’ll learn how to set up CurrencyLayer API in your Node.js web app, from the basic setup to fetching and showing exchange rate data. By the end, you’ll know how to make your Node JS Currency Converter handle different currencies smoothly. If you are going to build a trading platform or some kind of business app which needs to have the best reliable exchange rates & currency conversion features, you should go with CurrencyLayer.
Here is our demo app for today:
Table of Contents
What is CurrencyLayer?
CurrencyLayer offers one of the market-leading exchange rates api and currency conversion RESTful web services available in the marketplace.
CurrencyLayer provides a simplistic REST API with real-time and historical exchange rates for 168 countries.
-
Collected from various commercial sources & banks
-
Compatible with any application & programming languages
-
The best subscription plan and support
Why CurrencyLayer API?
Here are some features you should know about the CurrencyLayer API.
-
Official Exchange Rates for more than 160 countries with data updates ranging from every 60 minutes down to stunning 60 seconds.
-
Easy To Integrate API
-
Depending on your subscription plan you can get different data or can utilize all features
-
Free test subscription plans and inexpensive Startup-friendly subscription plans
How can I Reduce Technical Debt By Integrating APIs?
apilayer APIs helping millions of developers around the world by providing robust RESTful web services.
You can achieve high productivity in no time with APIs. There is no need to build everything from the beginning. And you can reduce technical debt by applying different approaches like integrating APIs and automate data manipulation.
Since apilayer services are used by top companies around the globe and integrated into millions of projects, you can have a long-term vision with these APIs!
How to Use the CurrencyLayer API?
As we have said, CurrencyLayer API can be integrated with any platform because of its flexible and simple API endpoints.
Here is an example of sending a request to a main endpoint of the API.
1 2 |
https://api.currencylayer.com/live ? access_key = YOUR_ACCESS_KEY |
And here is the response that you usually get
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
{ "success": true, "terms": "https://currencylayer.com/terms", "privacy": "https://currencylayer.com/privacy", "timestamp": 1430401802, "source": "USD", "quotes": { "USDAED": 3.672982, "USDAFN": 57.8936, "USDALL": 126.1652, "USDAMD": 475.306, "USDANG": 1.78952, "USDAOA": 109.216875, "USDARS": 8.901966, "USDAUD": 1.269072, "USDAWG": 1.792375, "USDAZN": 1.04945, "USDBAM": 1.757305, [...] } } |
As you can see it gives you some legal reminders, the source of the currency, and a timestamp. Well, the essential part is quotes object.
quotes – It includes all exchange rate values, consisting of the currency pairs and their respective conversion rates. And we are going to work with that.
What is the CurrencyLayer API Response Structure?
Let’s test the API endpoint.
How to Integrate Exchange Rates & Currency Conversion Features in the Node JS Web App?
Starting a new project always feels good but finishing it is the hard part! So in this demonstration, we try to show you a real-world Node.js web app that teaches you several valuable stuff:
-
Setup Node.js web app
-
Configuration
-
Integration of an API
-
Embedded JavaScript
-
Parsing JSON response
-
Presenting response in the classic style
-
and more
Here is what we create today!
How to Set Up Node JS with CurrencyLayer API?
Open your terminal, PowerShell or Bash. And type these commands to create a folder and initialize the basic project files
Then go back to your terminal and type this command to install the required node modules.
Now in this part, I would recommend you to copy static (css, js, images) files from our repository. And here is our project file structure:
Moreover, I would recommend you install nodemon. The nodemon is a tool that helps develop Node.js-based applications by automatically restarting the node application when file changes are detected. It improves your productivity.
Here you can follow these steps to configure nodemon.
Now, you can go back to your code editor and write this code for your app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const express = require('express') const app = express() const port = 2505 app.use(express.static('public')) app.use('/css', express.static(__dirname + 'public/css')) app.use('/img', express.static(__dirname + 'public/img')) app.use('/js', express.static(__dirname + 'public/js')) app.set('views', './src/views') app.set('view engine', 'ejs') const dashboardRouter = require('./src/routes/dashboard') app.use('/', dashboardRouter) const exchangeRatesRouter = require('./src/routes/exchangerates') app.use('/exerates', exchangeRatesRouter) app.listen(port, () => console.log(`Listening on port ${port}`)) |
As you can see, we are creating an ExpressJS-based app and specified the port. Then we are configuring static files. The “express.static” will help us to serve all static files in the public folder.
Then we declared the routes and views.
So, the main part is the exchangerates.js file. In this router handler, we fetch data from CurrencyLayer API and send data to the exchangerates view.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
const express = require('express') const exchangeRatesRouter = express.Router() const axios = require('axios') exchangeRatesRouter.get('', async(req, res) => { try { // send request to endpoint // for debugging you can add "format=1" as a parameter in the URL const currency = await axios.get(`http://apilayer.net/api/live?access_key=c92b0e664f8dd7743333fed2f42fd6c9`) // ------if you need to get keys and values into different containers----- // const exchangeName = Object.keys(currency.data.quotes) // const exchangeRates = Object.values(currency.data.quotes) // exchangeName.forEach(element => console.log(element)); // exchangeRates.forEach(element => console.log(element)); // send data to exchangerates page // res.render('exchangerates', { exeNames : exchangeName, exeRates: exchangeRates }) // --------------------------------------------------------------------------- // send only the quotes object elements // data is the JSON response and quotes is the object we need to parse res.render('exchangerates', { rates : currency.data.quotes }) } catch (error) { if(error.response) { console.log(error.response.data) } else if(error.request) { console.log(error.request) } else { console.log('Error', error.message) } } }) module.exports = exchangeRatesRouter |
I hope that the comments are helpful.
How to Iterate Key-value Pair Data and Present it in HTML5?
Here I will show you how to present key-value pair data in a table by iterating the elements. (You can find the whole exchangerates.ejs file from the repository)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<div class="container-fluid"> <h3 class="text-dark mb-1">CurrencyLayer API + Node.js</h3><button class="btn btn-primary" type="button" onclick="window.location.reload();" >Refresh</button> </div> <div class="container"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Major</th> <th>Price</th> </tr> </thead> <tbody> <!-- iterate key and values on the quotes object --> <% for(const [key, value] of Object.entries(rates)) { %> <tr> <td> <%- key %> </td> <td> <%- value %> </td> </tr> <% } %> </tbody> </table> </div> </div> |
As you can see, utilizing the Object.entries() method returns an array of a given object’s enumerable string keyed property pairs. This is like for…in.
Moreover, there is a dashboard feature that you can utilize and create more functionalities if your ideas to continue with CurrencyLayer API. It can be a boilerplate for your project!
And here is our result in action:
Check out the full source code in this repository.
Node JS Currency Converter: Conclusion
Adding exchange rates and currency conversion to your Node.js app can make it more useful for people with different currencies worldwide. CurrencyLayer API is a great tool for doing this because it’s simple to use and provides accurate rates. Following our guide, you can easily integrate CurrencyLayer API into your app and improve its functionality for international users. Using tools like CurrencyLayer API makes your app better and shows your commitment to making things easier for your users.
Node JS Currency Converter: FAQs
1. What’s CurrencyLayer API?
CurrencyLayer API gives real-time exchange rates and currency conversion info for different countries. It’s easy to use in your apps.
2. How Do I Use CurrencyLayer API for Node JS Currency Converter?
You sign up, get an API key, and then use it in your Node.js code to get exchange rates and convert currencies.
3. Is CurrencyLayer API Free?
Yes, there’s a free plan, but it has limits. If you need more, you can choose a paid plan.
4. Can I use CurrencyLayer API for My Business’s Node JS Currency Converter?
Yes, you can use it for your business. Just make sure to check the plan that fits your needs.
5. Is CurrencyLayer API Reliable?
Yes, it’s reliable. It gets its data from trusted sources, so you can trust the rates it gives you.
Ready to get started with CurrencyLayer? Sign up!