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
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:
"https://handlers.education.launchcode.org/static/weather.json"
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.
fetch
Example¶Now let's add fetch
in the Launch Status web page.
Example
A <script>
tag has been added that includes:
fetch
and response handler function on line 7.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:
fetch
as a parameter..then()
statement executes..then(function(response)
runs, and this function deals with the data
sent back from the API.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.
We can see evidence of the GET request by following these steps:
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.
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
}
Now that we have JSON weather data, we can add HTML elements to the page to display that data.
Example
div
object is defined and linked to the HTML element
with the id weather-conditions
.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:
fetch
command sends a request to the URL.then
method calls the anonymous
handler function and passes in the response
object (also line 6).response
object. When this is successful, the anonymous
function(json)
gets called.div
object is defined and linked to the HTML element
with the id weather-conditions
.innerHTML
property of the div
object is set to be
the HTML elements in lines 11 - 16.json
object.div
element on line 26.Opening the developer tools on the web page shows the added HTML:
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
.
Question
What is the correct syntax for fetch
?
fetch("GET", "https://api.url").then(...);
fetch("https://api.url").doStuff(...);
fetch("https://api.url").then(...);