26.3. Fetching Data

Now that we know what an API is, let's use one to update a web page. Let's use a weather API to add weather data to a web page. The URL for this special LaunchCode weather API is https://handlers.education.launchcode.org/static/weather.json.

Example JSON returned from our weather API.

{
   "temp": 67,
   "windSpeed": 5,
   "tempMin": 50,
   "tempMax": 71,
   "status": "Sunny",
   "chanceOfPrecipitation": 20,
   "zipcode": 63108
}

We can see that this API returns useful information like temp and windSpeed. Our goal is to add that data to a Launch Status web page. Note, this API is for instruction purposes and does not contain real time data.

Example

Launch Status web page, which we will add weather data to.

 1<!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>Launch Status</title>
 5   </head>
 6   <body>
 7      <h1>Launch Status</h1>
 8      <h3>Weather Conditions</h3>
 9      <div id="weather-conditions">
10         <!-- TODO: dynamically add html about weather using data from API -->
11      </div>
12   </body>
13</html>

Warning

Before going through the fetch examples, please know that fetch does NOT work in Internet Explorer. List of alternative browsers

26.3.1. fetch Function

To request the weather data, we will use the fetch function. fetch is a global function that requests, or fetches, resources such as data from an API.

Take note of two necessary aspects of the fetch function:

  1. The URL of where the data is located.
    1. For this example, it will be "https://handlers.education.launchcode.org/static/weather.json"
  2. A response handler function to utilize the data that is being fetched.
    1. For this example, it will be function(response){...};

Example

Notice a string URL is passed to fetch. Also notice the anonymous request handler function that has a response parameter. The .then method will be explained soon.

fetch("https://handlers.education.launchcode.org/static/weather.json").then(function(response) {
   console.log(response);
} );

In this example, we are requesting data from https://handlers.education.launchcode.org/static/weather.json and our response handler (the anonymous function) simply logs the response to the console.

26.3.2. fetch Example

Now let's add fetch in the Launch Status web page.

Example

A <script> tag has been added that includes:

  1. A load event handler on line 6.
  2. A fetch and response handler function on line 7.
  3. A console.log(response); on line 8 that prints out the response object.
 1          <!DOCTYPE html>
 2<html>
 3   <head>
 4      <title>Launch Status</title>
 5      <script>
 6         window.addEventListener("load", function() {
 7            fetch("https://handlers.education.launchcode.org/static/weather.json").then(function(response) {
 8               console.log(response);
 9            } );
10         });
11      </script>
12   </head>
13   <body>
14      <h1>Launch Status</h1>
15      <h3>Weather Conditions</h3>
16      <div id="weather-conditions">
17         <!-- TODO: dynamically add html about weather using data from API -->
18      </div>
19   </body>
20</html>

Let's break down how fetch works:

  1. A URL is passed to fetch as a parameter.
  2. This causes an HTTP GET request to be sent from the browser to the API.
  3. The API processes the request and sends back a response, which contains data.
  4. Once the browser receives the response, the .then() statement executes.
  5. The anonymous response handler function called by .then(function(response) runs, and this function deals with the data sent back from the API.
  6. Based on the code in the handler function, the web page gets updated using DOM methods.

Note

In this section, fetch is used to make GET requests. fetch can also be used to make other types of HTTP requests such as POST and PUT.

26.3.2.1. View the GET Request

We can see evidence of the GET request by following these steps:

  1. Open the Launch Status web page in its own tab.
  2. Open developer tools.
  3. Open the Network tab in developer tools.
Screen shot showing developer tools open with the network call to the API highlighted.

The GET request to the Weather API highlighted in developer tools.

In the image above, you can see the web page has been rendered on the left. In the developer tools, the GET request to the Weather API has been highlighted along with the response from that request. The response shows the JSON data that was received. In the console output, you can see the Response object has been logged. We will use that object next.

26.3.2.2. Response Object

The response to the GET request is contained in a Response object, which is an instance of the Response class. The class contains methods that allow us to access the status of an API request and the data returned in the response.

Example

On line 8, the json() method is used to gain access to the JSON data contained in the response object.

Line 9 logs the JSON to the console. We'll discuss .then() later.

 1<html>
 2   <head>
 3      <title>Launch Status</title>
 4      <script>
 5         window.addEventListener("load", function() {
 6            fetch("https://handlers.education.launchcode.org/static/weather.json").then( function(response) {
 7               // Access the JSON in the response
 8               response.json().then( function(json) {
 9                  console.log(json);
10               });
11            });
12         });
13      </script>
14   </head>
15   <body>
16      <h1>Launch Status</h1>
17      <h3>Weather Conditions</h3>
18      <div id="weather-conditions">
19         <!-- TODO: dynamically add html about weather using data from API -->
20      </div>
21   </body>
22</html>

Console Output

Object {
   temp: 67,
   windSpeed: 5,
   tempMin: 50,
   tempMax: 71,
   status: "Sunny",
   chanceOfPrecipitation: 20,
   zipcode: 63108
}

26.3.2.3. Use the DOM and JSON Data to Update the Page

Now that we have JSON weather data, we can add HTML elements to the page to display that data.

Example

  1. On line 8, the div object is defined and linked to the HTML element with the id weather-conditions.
  2. On line 10, the innerHTML property of the div object is set to be the HTML elements in lines 11 - 16.
 1<html>
 2   <head>
 3      <title>Launch Status</title>
 4      <script>
 5         window.addEventListener("load", function() {
 6            fetch("https://handlers.education.launchcode.org/static/weather.json").then( function(response) {
 7               response.json().then( function(json) {
 8                  const div = document.getElementById("weather-conditions");
 9                  // Add HTML that includes the JSON data
10                  div.innerHTML = `
11                     <ul>
12                        <li>Temp ${json.temp}</li>
13                        <li>Wind Speed ${json.windSpeed}</li>
14                        <li>Status ${json.status}</li>
15                        <li>Chance of Precip ${json.chanceOfPrecipitation}</li>
16                     </ul>
17                  `;
18               });
19            });
20         });
21      </script>
22   </head>
23   <body>
24      <h1>Launch Status</h1>
25      <h3>Weather Conditions</h3>
26      <div id="weather-conditions">
27         <!-- Weather data is added here dynamically. -->
28      </div>
29   </body>
30</html>

Let's take a look at the expected sequence of events:

  1. In line 6, the fetch command sends a request to the URL.
  2. When the API returns a response, the then method calls the anonymous handler function and passes in the response object (also line 6).
  3. On line 7, the handler function tries to retrieve the JSON data from the response object. When this is successful, the anonymous function(json) gets called.
    1. On line 8, the div object is defined and linked to the HTML element with the id weather-conditions.
    2. On line 10, the innerHTML property of the div object is set to be the HTML elements in lines 11 - 16.
    3. The HTML in lines 11 - 16 gets filled in using weather data stored in the json object.
  4. The two anonymous functions end, and the HTML defined in lines 11 - 16 gets added to the div element on line 26.

Opening the developer tools on the web page shows the added HTML:

Screen shot of browser showing Launch Status web page with the weather data in HTML.

Weather data added to web page.

Note

fetch was chosen as the tool to request data because it's supported in modern browsers by default and is simple to use. When viewing resources other than this book, you will see various other ways to request data in a web page with JavaScript. Other ways include, but are not limited to, jQuery.get, jQuery.ajax, and XMLHttpRequest.

26.3.3. Check Your Understanding

Question

What is the correct syntax for fetch?

  1. fetch("GET", "https://api.url").then(...);
  2. fetch("https://api.url").doStuff(...);
  3. fetch("https://api.url").then(...);