fetch APi request for forex rates

27 views Asked by At

i'm a new developer trying to establish a connection with a free forex api service. im able to establish the connection as when i inspect my console it says "success" and shows the rates for each currency, but now im struggling to take that forex rate data and display it on my browser. I've tried creating a basic HTML code to store it with a unique ID name, but enhancing my script to place that forex rate inside the innerHTML is erroring out for me (browser displays "undefined" where the forex rate should show). No other errors in the console, so i think im mapping the field wrong in my js. Any guidance be greatly appreciated!

Here is my javascript:

var EURUSD = document.querySelector("#EURUSD");
let url = 'https://api.exchangeratesapi.io/v1';

function params(paramsObj) {
    return new URLSearchParams({
      access_key: '<added my unique API key here',
      ...paramsObj
    });
}

function getLatest(options) {
  fetch(`${url}/latest?${params(options)}`)
    .then(res => res.json())
    .then(displayData);

    function displayData(rates) {
        console.log(rates)
            EURUSD.innerText=`${rates.EUR}`
    }
}

// remove these if you want everything
getLatest({base: 'USD'});

here is a snippit from my browser console showing connectivity i believe (in my javascript above, based off below i thought i could do rates.CCY to pull specific rate):

{success: true, timestamp: 1711454285, base: 'USD', date: '2024-03-26', rates: {…}}
base
: 
"USD"
date
: 
"2024-03-26"
rates
: 
AED
: 
3.67229
AFN
: 
71.215413
ALL
: 
94.92401
AMD
: 
395.551886

here is my basic html:

<p id="EURUSD"></p>

here is an excerpt from their API Doc:

{
    "success":true,
    "fluctuation":true,
    "start_date":"2018-02-25",
    "end_date":"2018-02-26",
    "base":"EUR",
    "rates":{
        "USD":{
            "start_rate":1.228952,
            "end_rate":1.232735,
            "change":0.0038,
            "change_pct":0.3078
        },
        "JPY":{
            "start_rate":131.587611,
            "end_rate":131.651142,
            "change":0.0635,
            "change_pct":0.0483
        },
        [...]
    }
}
0

There are 0 answers