Live Currency Rates Using Our NodeJS SDK

Let's make your NodeJS projects smarter with our dedicated NodeJS SDK for CurrencyApi.net! Whether you're crafting web applications, financial tools, or backend services, our SDK equips you with everything you need to effortlessly integrate live currency rates into your NodeJS projects. By the end of this tutorial, you'll be seamlessly fetching and using real-time currency data.

Installation

To begin using the CurrencyApi.net NodeJS SDK, ensure you have Node v8 or higher installed. We have tested it up to NodeJs v22.9.0.

Then you can install the SDK via NPM:

npm install currencyapi-node

Importing the NodeJS SDK

After installation, include the SDK in your NodeJS project:

import CurrencyApi from './src/CurrencyApi.js';

Adding your API Key with NodeJS

You're all set to start leveraging the CurrencyApi.net NodeJS SDK. Begin by creating an instance of the CurrencyApi class with your API key:

const currency = new CurrencyApi('YOUR_API_KEY');

Get Your Free API Key

Unlock live exchange rates instantly with our Currency API. We offer flexible pricing plans to get you started. Sign up today and continue with the NodeJS tutorial!

Get Currency API Key »

Fetching Live Currency Rates with NodeJS

Let's dive into fetching live currency rates using the following method:

const result = await currency.rates().get();
// Or using promises
currency.rates().get()
    .then(console.log);

This will output the response containing all the currency rates of the default base currency. The default is USD.

The rates() method is a convenient way to access the /rates endpoint.

Here's a complete example showcasing the API response:

import CurrencyApi from './src/CurrencyApi.js';

const currency = new CurrencyApi('YOUR_API_KEY');

(async () => {
    try {
        const result = await currency.rates().get();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
})();
# Outputs
{
    "valid": true,
    "updated": 1727622003,
    "base": "USD",
    "rates": {
        "AED": 3.673,
        "AFN": 68,
        "ALL": 88.25,
        "AMD": 387.32,
        "ANG": 1.801995,
        "AOA": 943.5,
        "ARS": 965.4662
        // ...
    }
}

Great! You've successfully retrieved live currency rates using our NodeJS SDK.

Available Methods for Rates Endpoint - NodeJS SDK

Method Description
base() Sets the base currency for conversions. Outputs all currency conversions for the specified currency. Default is USD.
output() Specifies the response format: JSON or XML. Default is JSON.

Converting Currency Amounts

Easily convert amounts between currencies using our Currency API and NodeJS SDK. This method provides a streamlined response, optimizing performance and reducing data overhead.

The convert() method utilizes the /convert endpoint of our Currency API.

Let's convert 100 USD to EUR with the NodeJS SDK:

const result = await currency.convert().from('USD').to('EUR').amount(100).get();
console.log(result);
# Outputs
{
    "valid": true,
    "updated": 1727625603,
    "conversion": {
        "amount": 100,
        "from": "USD",
        "to": "EUR",
        "result": 85.37
    }
}

As shown, the response is concise and contains only the necessary conversion details.

Available Methods for Convert Endpoint - NodeJS SDK

Method Description
from() The currency you want to convert from. Must be a three-letter ISO 4217 currency code. Required.
to() The currency you want to convert to. Must be a three-letter ISO 4217 currency code. Required.
amount() The amount you wish to convert. Should be a numerical value and can include decimals. Required.
output() Specifies the response format: JSON or XML. Default is JSON.

NodeJS - Fetching Historical Currency Rates

Need historical currency data? Our SDK provides endpoints to access past currency rates with ease.

The history() method leverages the /history endpoint of our Currency API.

Retrieve historical rates for USD on January 1st, 2024 using the NodeJS SDK:

const result = await currency.history().date('2024-01-01').base('USD').output('JSON').get();
console.log(result);
# Outputs
{
  valid: true,
  base: 'USD',
  date: '2024-01-01',
  rates: {
    AED: 3.6728,
    AFN: 70.83428,
    ALL: 93.79385,
    AMD: 405.595,
    ANG: 1.807342,
    AOA: 828.8,
    ARS: 810.8593,
    // ...
  }
}

The response provides a JSON object with historical currency rates for the specified date.

Available Methods for History Endpoint with NodeJS SDK

Method Description
date() The specific date for which you want historical currency rates. Format: YYYY-MM-DD. Required.
base() Sets the base currency for conversions. Outputs all currency conversions for the specified currency. Default is USD.
output() Specifies the response format: JSON or XML. Default is JSON.

Return multiple historical day rates with NodeJs

Accessing currency rates over a specific timeframe enables developers to build applications that monitor currency fluctuations over time, such as graphs, analytics dashboards, and more.

The timeframe() method utilizes the /timeframe endpoint of our Currency API.

Retrieve rates for USD between February 1st, 2023 and February 5th, 2023 using the NodeJS SDK:

const result = await currency.timeframe().startDate('2023-02-01').endDate('2023-02-05').get();
console.log(result);
# Outputs
{
    "valid": true,
    "base": "USD",
    "start_date": "2023-02-01",
    "end_date": "2023-02-05",
    "rates": {
        "2023-02-01": {
            "AED": 3.6728,
            "AFN": 70.83428,
            "ALL": 93.79385,
            "AMD": 405.595,
            "ANG": 1.807342,
            "AOA": 828.8,
            "ARS": 810.8593,
            // ...
        },
        // ...
        "2023-02-05": {
            "AED": 3.6732,
            "AFN": 88.64088,
            "ALL": 105.71149,
            "AMD": 391.9258,
            "ANG": 1.78267,
            "AOA": 504.30012,
            "ARS": 187.29207
            // ...
        }
    }
}

The API returns multiple days of currency rates in a single response, simplifying the process of tracking currency trends over time.

Available Methods for Timeframe Endpoint - NodeJS SDK

Method Description
startDate() The start date for the currency rate timeframe. Format: YYYY-MM-DD. Required.
endDate() The end date for the currency rate timeframe. Format: YYYY-MM-DD. Required.
base() Sets the base currency for conversions. Outputs all currency conversions for the specified currency. Default is USD.
output() Specifies the response format: JSON or XML. Default is JSON.

Best Practices

To ensure a smooth and efficient integration with the NodeJS SDK, adhere to the following best practices:

  • Cache API responses when appropriate to minimize redundant API calls and enhance performance.
  • Implement robust error handling to gracefully manage unexpected issues and maintain application stability.
  • Securely store your API key using environment variables to protect sensitive information.
  • Regularly consult the official documentation for updates and advanced usage techniques.

Handling Responses

JSON Response

By default, the SDK returns responses in JSON format. This makes it straightforward to work with the data directly within your NodeJS applications.

XML Response

You can opt for XML responses by specifying the output parameter. Here's how to retrieve and handle XML responses:

const result = await currency.rates().output('XML').get();
console.log(result);
# Outputs
<?xml version="1.0" encoding="utf-8"?>
<root>
    <valid>true</valid>
    <updated>1727720883</updated>
    <base>USD</base>
    <rates>
        <AED>3.673</AED>
        <AFN>68</AFN>
        <ALL>88.25</ALL>
        <AMD>387.29</AMD>
        <ANG>1.80184</ANG>
        <AOA>943</AOA>
        <ARS>968.7457</ARS>
        <!-- ... -->
    </rates>
</root>

To process the XML response in NodeJS, you can use the xml2js library:

import CurrencyApi from './src/CurrencyApi.js';
const xml2js = require('xml2js');

const currency = new CurrencyApi('YOUR_API_KEY');

(async () => {
    try {
        const result = await currency.rates().output('XML').get();
        xml2js.parseString(result, (err, result) => {
            if (err) {
                throw err;
            }
            const rates = result.root.rates[0];
            for (const [currency, rate] of Object.entries(rates)) {
                console.log(`Currency: ${currency}, Rate: ${rate}`);
            }
        });
    } catch (error) {
        console.error(error);
    }
})();
# Outputs
Currency: AED, Rate: 3.673
Currency: AFN, Rate: 69
Currency: ALL, Rate: 89.675
Currency: AMD, Rate: 386.99
// ...

Looping Over the JSON Response in NodeJS

To iterate through the JSON response and utilize the data effectively in your application:

const result = await currency.rates().get();
const baseCurrency = result.base;
const rates = result.rates;

console.log(`Base Currency: ${baseCurrency}`);
for (const [currency, rate] of Object.entries(rates)) {
    console.log(`${currency}: ${rate}`);
}
# Outputs
Base Currency: USD
AED: 3.673
AFN: 68
ALL: 88.25
AMD: 387.29
ANG: 1.80184
AOA: 943
ARS: 968.7109
// ...

Error Handling - NodeJS SDK

Effective error handling ensures your application remains resilient and provides meaningful feedback to users:

try {
    const result = await currency.rates().get();
    console.log(result);
} catch (error) {
    console.error(`An error occurred: ${error.message}`);
}

Integrating into Your NodeJS Application

Integrate the CurrencyApi.net NodeJS SDK seamlessly into your NodeJS applications, whether you're building REST APIs, real-time services, or data processing tools.

Here's an example of a simple currency converter function within a NodeJS application:

import CurrencyApi from './src/CurrencyApi.js';

const currency = new CurrencyApi('YOUR_API_KEY');

async function convertCurrency(amount, fromCurrency, toCurrency) {
    try {
        const result = await currency.convert()
            .from(fromCurrency)
            .to(toCurrency)
            .amount(amount)
            .get();
        return result.conversion.result;
    } catch (error) {
        throw new Error(`Conversion failed: ${error.message}`);
    }
}

(async () => {
    try {
        const converted = await convertCurrency(100, 'BTC', 'USD');
        console.log(`100 BTC is equal to ${converted} USD`);
    } catch (error) {
        console.error(error);
    }
})();

Conclusion

The CurrencyApi.net NodeJS SDK offers a straightforward and efficient method to integrate live currency rates into your NodeJS applications. With easy setup, comprehensive documentation, and dependable support, enhancing your projects with up-to-date currency data has never been easier.

Other Useful Links:

Other SDKs

Not working with NodeJS? Explore our other SDKs tailored for different programming languages:

Python SDK

Effortlessly incorporate live currency data into your Python applications with our intuitive SDK. Access real-time exchange rates, currency conversions, and more.

Explore the Python SDK →

GoLang SDK

Quickly implement currency data into your GoLang applications with our user-friendly SDK. Access live exchange rates, currency conversions, and more.

Explore the GoLang SDK →

PHP SDK

Seamlessly connect to our Currency API from your PHP applications. This SDK ensures smooth and efficient access to the latest currency rates and services.

Check out the PHP SDK →

Get Started with CurrencyApi.net Today!

Sign up now to access live currency rates and enhance your NodeJS applications.

View Pricing & Plans »
Meet the Author
Oli Girling

Oli Girling

Founder & Senior Software Engineer

London, UK

Connect on LinkedIn