The Fetch API

Using the Promise and Response objects of the Fetch API and get plain-text and JSON formatted data from remote web servers.

Learning Goals

At the end of this Tutorial, you will be able to:

  • Send a request to a web server with the Fetch API.
  • Work with the Response object.
  • Work with the Promise object for chaining multiple requests.
  • Handle server status codes.

The Fetch API: JS Code Snippets

The Fetch API

The Fetch API is a modern alternative to the older XMLHttpRequest API for making HTTP requests to web servers from web browsers. It uses the Promise object to provide more flexible features.

Sending a Request

You need to supply only a single argument to the fetch() method: the URL of the data that you want to fetch. This URL is known as an endpoint. See below.

let response = fetch(url);

The call to the requested resource by the fetch() method is asynchronous. That is, the time taken for the Fetch API to complete its task does not halt the execution of other instructions elsewhere in the web page.

However, it is good practice to wrap a fetch() call inside a function declared with the async keyword and prefix the fetch call with the await keyword. See below.

async function getSomeData() {
    let response = await fetch(url);
}

getSomeData();

Working with the Response object

If the request completes successfully, the requested data is returned and wrapped inside Response object. This has a number of useful properties and methods for working with the response.

.text()

Use this when the Response object contains only 'raw' or 'plain' text.

.json()

Use this when the Response object contains only data in JSON format.

Here is a smple example of fetching the contents of a raw text file.

async function fetchRawText() {
    let response = await fetch('https://www.w3.org/TR/PNG/iso_8859-1.txt'); 
    let data = await response.text(); 
    console.log(data);
}

fetchRawText()

To update the content of a <div> container with an id of "fetched-text" on the same web page, you could write this.

async function fetchRawText() {
    let response = await fetch('https://www.w3.org/TR/PNG/iso_8859-1.txt'); 
    let data = await response.text(); 
    document.querySelector(#fetched-text").innerText = data;
}

fetchRawText()

Here is a simple example of fetching some data in JSON format.

async function fetchJSONData() {
    let response = await fetch('https://type.fit/api/quotes'); 
    let data = await response.json(); 
    console.log(data);
}

fetchJSONData()

Working with the Promise object

Before it returns a Response object, the fetch() method returns a Promise object that can have one of three possible properties:

pending

The request's initial state.

fulfilled

The request has completed successfully and a value is returned.

rejected

The request has failed and a reason (error) is returned.

A Promise is said to be settled or resolved if it is either fulfilled or rejected, but not pending. When a Promise is fulfilled, you can use its then() and catch() methods to handle it.

See the sample code below.

fetch(url)
    .then(
        function(response) {
            // handle the response            
        }
    )
    
    .catch(
        function(err) {
            // handle any error
        }
    );

Or using modern arrow function syntax:

fetch(url)
    .then(response => {
        // handle the response
    })

    .catch(error => {
        // handle any error
    });

Using the Promise object enables multiple response functions to be chained togother.

Handling server status codes

The Response object provides web server status code and status text through two properties status and statusText properties. When a request is successful, the status code is 200 and status text is OK.

Here is a complete example of the Fetch API with the Promise object that tests for a successful web server connection.

async function fetchWithServerCheck() { 

await fetch('https://www.w3.org/TR/PNG/iso_8859-1.txt')
    .then(response => {

        if (response.status !== 200) {
            console.log('Error Status Code: ' + response.status);
            return;
        }

        response.text().then((data) => {
            console.log(data);
        });
    })

    .catch(error => {
        // handle any error
    });

}

// fetchWithServerCheck();