CSCI 185: Fall 2022

Introduction to Programming for the Web

CSCI 185: Fall 2022

Fish by @akeatk

Lectures > 20. Intro to the fetch API

Today, we are going to be learning about JavaScript’s fetch API, and how to use it to retrieve data from various content providers (i.e. servers).

Today's Activities

For today, please do the following:

1. Complete the Assigned Readings

  1. Lazaris, Louis (2020). Fetch API Tutorial for Beginners: How to Use Fetch API.
    For Wednesday / HW4
  2. Using Fetch. Mozilla Developer Network
    For your reference.

2. Review the Slides

  1. Intro to fetch

3. Watch the Lecture Video(s)

Link Title Type Duration
Video 1 Course API Practice: Section 1 (12:30-1:45PM) lecture 1:09:48
Video 2 Course API Practice: Section 2 (3:30-4:45PM) lecture 1:21:39

4. Review the Code from Class

The live coding files that Sarah made are posted here:

  1. Section 1 (12:30-1:45PM)
  2. Section 2 (3:30-4:45PM)

Notes on the JavaScript Fetch API

As described via the Mozilla developer pages:

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

Consider the following example, which fetches a JSON file from across the network and prints it to the console:

const addressOfData = 'https://www.apitutor.org/flickr/simple/?tags=cat'

// function definition to fetch:
async function fetchData() {
    data = await fetch(addressOfData).then(response => response.json());
    displayData(data);
} 

// function definition to display results:
function displayData(data) {
    console.log(data);
}

// invoke the fetch to initiate the process:
fetchData();

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object). This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method.