Lesson 13 of 16
In Progress

Working with APIs and AJAX Requests

In this chapter of the “Learn JavaScript” course, we will be exploring how to work with APIs (Application Programming Interfaces) and make AJAX (Asynchronous JavaScript and XML) requests in JavaScript. APIs allow you to access data and functionality from other websites and services, and AJAX allows you to make requests to APIs asynchronously, without the need to refresh the page.

What is an API?

An API is a set of rules that defines how two systems can communicate with each other. APIs allow you to access data and functionality from other websites and services, and can be accessed using HTTP requests.

There are many APIs available on the web, and they can be used to access a wide range of data and functionality. Some examples of what you can do with APIs include:

  • Retrieve data from a database or service
  • Add or update data in a database or service
  • Perform a specific action (e.g. sending an email or posting to social media)

APIs often require you to authenticate your request using an API key or other form of authentication. It is also common for APIs to have rate limits, which limit the number of requests you can make within a certain time period.

Making API requests with JavaScript

To make API requests in JavaScript, you can use the XMLHttpRequest object or the fetch function.

The XMLHttpRequest object is a legacy API that has been around since the early days of the web. It allows you to make HTTP requests and receive responses asynchronously, without the need to refresh the page. Here’s an example of how to use the XMLHttpRequest object to make a GET request to an API:

function makeRequest(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.onload = function() {
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    } else {
      console.error(xhr.statusText);
    }
  };
  xhr.send();
}

makeRequest("http://example.com/api/data");

The fetch function is a newer API that was introduced in JavaScript with the fetch API. It allows you to make HTTP requests and receive responses asynchronously, and returns a promise that resolves to a Response object. Here’s an example of how to use the fetch function to make a GET request to an API:

fetch("http://example.com/api/data")
  .then(function(response) {
    return response.text();
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error(error);
  });

Both the XMLHttpRequest object and the fetch function allow you to make other types of HTTP requests, such as POST, PUT, DELETE, etc., by setting the method property of the request.

Working with JSON data

Many APIs return data in JSON (JavaScript Object Notation) format, which is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

To parse JSON data in JavaScript, you can use the JSON.parse function. Here’s an example of how to parse JSON data using the JSON.parse function:

var jsonData = '{"name": "John", "age": 30, "city": "New York"}';
var data = JSON.parse(jsonData);
console.log(data.name); // "John"
console.log(data.age); // 30
console.log(data.city); // "New York"

To convert a JavaScript object or array into a JSON string, you can use the JSON.stringify function. Here’s an example of how to convert a JavaScript object into a JSON string using the JSON.stringify function:

var data = {name: "John", age: 30, city: "New York"};
var jsonData = JSON.stringify(data);
console.log(jsonData); // '{"name":"John","age":30,"city":"New York"}'

Working with AJAX requests

AJAX (Asynchronous JavaScript and XML) is a term used to describe the process of making asynchronous HTTP requests and receiving responses in JavaScript, without the need to refresh the page. AJAX allows you to update parts of a webpage dynamically, by making requests to an API and updating the DOM (Document Object Model) with the response.

To make an AJAX request in JavaScript, you can use the XMLHttpRequest object or the fetch function, as we discussed earlier. Here’s an example of how to make an AJAX request using the XMLHttpRequest object:

function makeRequest(url) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url);
  xhr.onload = function() {
    if (xhr.status === 200) {
      var data = JSON.parse(xhr.responseText);
      // Update the DOM with the response data
    } else {
      console.error(xhr.statusText);
    }
  };
  xhr.send();
}

// Make the AJAX request when the button is clicked
var button = document.getElementById("button");
button.addEventListener("click", function() {
  makeRequest("http://example.com/api/data");
});

Here’s an example of how to make an AJAX request using the fetch function:

function makeRequest(url) {
  fetch(url)
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      // Update the DOM with the response data
    })
    .catch(function(error) {
      console.error(error);
    });
}

// Make the AJAX request when the button is clicked
var button = document.getElementById("button");
button.addEventListener("click", function() {
  makeRequest("http://example.com/api/data");
});

Conclusion

In this chapter of the “Learn JavaScript” course, we learned about APIs and how to make AJAX requests in JavaScript. We also learned how to work with JSON data, and how to use the XMLHttpRequest object and the fetch function to make HTTP requests and receive responses asynchronously.

By understanding how to work with APIs and make AJAX requests, you can build dynamic, interactive web applications that can access and manipulate data from other websites and services.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Make an AJAX request to the GitHub API to retrieve the list of repositories for a given user, and display the repository names in a list on the page.

function getRepos(username) {
  fetch(`https://api.github.com/users/${username}/repos`)
    .then(function(response) {
      return response.json();
    })
    .then(function(repos) {
      var list = document.getElementById("repo-list");
      repos.forEach(function(repo) {
        var li = document.createElement("li");
        li.textContent = repo.name;
        list.appendChild(li);
      });
    })
    .catch(function(error) {
      console.error(error);
    });
}

var button = document.getElementById("button");
button.addEventListener("click", function() {
  var username = document.getElementById("username").value;
  getRepos(username);
});

Make an AJAX request to the OpenWeatherMap API to retrieve the current weather for a given city, and display the temperature and weather description on the page.

function getWeather(city) {
  fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`)
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var temperature = data.main.temp;
      var description = data.weather[0].description;
      document.getElementById("temperature").textContent = temperature;
      document.getElementById("description").textContent = description;
    })
    .catch(function(error) {
      console.error(error);
    });
}

var button = document.getElementById("button");
button.addEventListener("click", function() {
  var city = document.getElementById("city").value;
  getWeather(city);
});

Make an AJAX request to the Wikipedia API to search for articles with a given keyword, and display the article titles and descriptions in a list on the page.

function searchArticles(keyword) {
  fetch(`https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&formatversion=2&srsearch=${keyword}`)
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var list = document.getElementById("article-list");
      data.query.search.forEach(function(article) {
        var li = document.createElement("li");
        var a = document.createElement("a");
        a.textContent = article.title;
        a.href = `https://en.wikipedia.org/wiki/${article.title}`;
        li.appendChild(a);
        li.appendChild(document.createTextNode(` - ${article.snippet}`));
        list.appendChild(li);
      });
    })
    .catch(function(error) {
      console.error(error);
    });
}

var button = document.getElementById("button");
button.addEventListener("click", function() {
  var keyword = document.getElementById("keyword").value;
  searchArticles(keyword);
});

Make an AJAX request to the NASA Astronomy Picture of the Day API to retrieve the current “Astronomy Picture of the Day,” and display the image and description on the page.

function getAPOD() {
  var apiKey = "YOUR_API_KEY";
  fetch(`https://api.nasa.gov/planetary/apod?api_key=${apiKey}`)
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      var img = document.getElementById("apod-img");
      img.src = data.url;
      img.alt = data.title;
      document.getElementById("apod-title").textContent = data.title;
      document.getElementById("apod-description").textContent = data.explanation;
    })
    .catch(function(error) {
      console.error(error);
    });
}

getAPOD();

Make an AJAX request to the USGS Earthquake API to retrieve a list of earthquakes in the past week, and display the earthquake magnitudes and locations on a map using the Google Maps API.

First, you’ll need to obtain an API key for the Google Maps API by following the instructions on the Google Maps API documentation. Then, you can use the following code to make the AJAX request to the USGS Earthquake API and display the earthquakes on a map:

function initMap() {
  var map = new google.maps.Map(document.getElementById("map"), {
    zoom: 2,
    center: {lat: 0, lng: 0}
  });

  fetch("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2022-01-01&endtime=2022-01-08")
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      data.features.forEach(function(earthquake) {
        var marker = new google.maps.Marker({
          position: earthquake.geometry.coordinates,
          map: map,
          title: `Magnitude ${earthquake.properties.mag} - ${earthquake.properties.place}`
        });
      });
    })
    .catch(function(error) {
      console.error(error);
    });
}