Home > Software design >  How to get and supply API access key to successfully fetch the API?
How to get and supply API access key to successfully fetch the API?

Time:08-20

Trying to grab and manipulate currency exchange data. Can't figure out how to access the API key and integrate it into the code.

Here is JS code:

        document.addEventListener('DOMContentLoaded', function() {
            fetch('https://api.exchangeratesapi.io/latest?base=USD')
            .then (response => response.json())
            .then (data => {
                console.log(data);
                });
        });

Console output:

{success: false, error: {…}}
error: {code: 101, type: 'missing_access_key', info: 'You have not supplied an API Access Key. [Required format: access_key=YOUR_ACCESS_KEY]'}
success: false

CodePudding user response:

Normally the API docs shd show you how to use the API key, from my experience in React and Node, the API key is treated as an env variable and then you chain it into your request URL, so when you make your request you are authenticated and then sent a response.

Something like this:

document.addEventListener('DOMContentLoaded', function() {
            fetch('https://api.exchangeratesapi.io/insertAPIkeyHere/latest?base=USD')
            .then (response => response.json())
            .then (data => {
                console.log(data);
                });
        });
        
        // do refer to the docs for an idea of how they want the key utilised, but it shouldn't be to complex

CodePudding user response:

Thanks for everyone's feedback. Got it to work by carefully reading the documentation which signaled that I used an old URL from a dated course, and headers were needed in this case.

Here is the update:

            var myHeaders = new Headers();
            myHeaders.append("apikey", "API_KEY_HERE");

            var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            headers: myHeaders
            };

            fetch("https://api.apilayer.com/exchangerates_data/latest?&base=EUR", requestOptions)
            .then (response => response.json())
            .then (data => console.log(data))
            .catch(error => console.log('error', error));
  • Related