Making API calls from Javascript
 

Making API calls from Javascript

I now have a few situations where I make calls to external APIs. I really do need to fully understand what is going on here. It seems that it is more than copying a few code examples

My requirements are to be able to call a number of APIs to collect data such as my current IP address and to use this data to perform specific actions on this website. The examples often just show how an API call could be made but I feel that I need a deeper understanding of what is going on.

The call to the ipify API is a case in point as the data returned is a JSON object that contains my current IP address, I want to use this address to determine whether it is different to a stored value not just display the value on the screen.

FreeCodeCamp (Joan Ayebola) said:

Calling an API (Application Programming Interface) in JavaScript is a fundamental action that web developers need to know how to perform. It allows you to fetch data from external sources and integrate it into your web applications.

Looking at the examples on the FreeCodeCamp is would seem that the APIs used need to have an API key to get them to work. The first example details the retrieval of data from a weather tracking website (OpenWeatherMap). There is a free subscription but I am not sure that I want to stir that one up.

The ipify API does not need a key and as such is probably my best bet. Similarly the Fetch API is also well documented and I want to use this to fetch the stored IP address from a file.

Top

In both of the examples a const containing the APIurl and another to hold the outputElement. The outputElement has its innerHTML updated by the API call.

Below is the code in a PRE tag (for expediency)


const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=London&appid=${apiKey}`;

const outputElement = document.getElementById('weather-output');

fetch(apiUrl)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    const temperature = data.main.temp;
    const description = data.weather[0].description;
    const location = data.name;
    outputElement.innerHTML = `<p>Temperature in ${location}: ${temperature}°C</p>
                               <p>Weather: ${description}</p>`;
  })
  .catch(error => {
    console.error('Error:', error);
  });
 

Links

Link to PDF Disabled

If you require a copy please email tempusfugit.me.uk

Top

References - a note on these

  • How to Call an API in JavaScript - https:// www.freecodecamp.org/ news/ make-api-calls-in-javascript/ - Joan Ayebola

Site design by Tempusfugit Web Design -