I am trying to integrate the Currencylayer API into my website to fetch real-time exchange rates for different currencies.
My goal is to display converted currency values dynamically on my website, such as converting USD to EUR, INR, or GBP for users based on their preferences.
From the documentation, I understand that I need to send a request like this:
http://api.currencylayer.com/live?access_key=YOUR_ACCESS_KEY
The API returns exchange rate data in JSON format, including currency pairs like USDINR, USDEUR, and more.
What I tried
I attempted to call the API using JavaScript:
const access_key = "YOUR_ACCESS_KEY";
fetch(`http://api.currencylayer.com/live?access_key=${access_key}`)
.then(response => response.json())
.then(data => {
console.log(data);
document.getElementById("output").innerHTML = data.quotes.USDINR;
})
.catch(error => console.error(error));
Expected result
The exchange rate (for example USD to INR) should be displayed on the webpage.
Actual result
Nothing is displayed on the page, or sometimes I get errors such as:
CORS policy blocked request
Mixed content error (HTTP vs HTTPS)
Undefined data in response
Questions
What is the correct way to call the Currencylayer API from the frontend?
Do I need to use HTTPS or a backend proxy to make this work properly?
How can I secure my API key and avoid exposing it in frontend code?
Is there a way to convert currencies dynamically (for example USD to INR) using the API response?