Fetch

fetch is a built-in Javascript function that allows us to make API requests using Javascript.

The basic syntax for fetch is as follows:

fetch(requestURL)
    .then(function(responseData){
        // Fetch will package the response into an object with some methods that allow us to do some useful things with the response.
        // Use the .json() method to return the data in JSON format
            return responseData.json();
    })
    .then(function(jsonData){
        // whatever we return in the first .then promise will be passed into this callback function
        // do some stuff with the jsonData here
    })
    .catch(function(error){
        // any errors encountered in the request or the .then promises above will be passed into this callback
        console.log("Oh no, there's been an error!", error);
    })

Example

In this example, we'll display a list of random people using fetch and the Random User API

index.html

First let's look at our data in the console

script.js

Now let's get some of this data rendering on the page!

script.js

Exercise

Add to the above code so that we see a photo along with the random user.

Last updated

Was this helpful?