9) Modern Requests Lesson

JavaScript Fetch API: Introduction

10 min to complete · By Ian Currie

In this lesson, you'll learn about the Javascript fetch() method and how to use it. The fetch() method is a promise-based method that allows you to make HTTP requests.

How to Use the Javascript Fetch Method

fetch is a function that returns a promise that resolves to the response of the HTTP request. It takes a URL as an argument. For example, if you wanted to make a request to the Ghibli API, you would do something like this:

You can think of it as a pizza function like what was defined earlier, except instead of making virtual pizzas, it makes HTTP requests:

fetch("https://ghibliapi.vercel.app/people")
  .then((response) => response.json())
  .then((people) => console.log(people));

The above code will log the response to the console. The response is a JSON object that contains information about the people in the Ghibli films.

You first call the fetch() function with the URL as an argument. The default request method is GET, so you don't need to specify that. The fetch() function returns a promise that resolves to a Response object.

Remember, it doesn't return the response itself, but a promise that resolves to the response.

To access the response, you need to use the .then() method on the promise. The .then() method takes a callback function as an argument. The callback function takes the response as an argument.

The response object has a .json() method that returns a promise that resolves to the JSON data. The process of getting the JSON data is also asynchronous, so you need to use the .then() method on the promise to log the JSON data to the console.

Colorful illustration of a light bulb

Note: The Response object also has a .text() method that returns a promise that resolves to the text data. You can use this method if you want to get the text data instead of the JSON data.

If you erroneously use the .json() method on a response that isn't JSON-formatted, it will result in a parsing error. Conversely, .text() can be safely used to retrieve any text-based content, including JSON, which can then be manually parsed using JSON.parse().

Finally, your last .then() method is just there to log the JSON data to the console. You could do something else with it, like render it to the DOM.

Catching Errors

Though in reality, so many things can go wrong along the way. Your connection is shaky. An intermediate server that is handling your request goes down. The destination server has a hiccup. A transatlantic wire experiences some interference from the Cthulhu.

Really, it's amazing that the data reaches its destination 99.9% of the time. Though for that 1/1000 times that it doesn't, you need your program to be able to respond accordingly, hence the catch block:

fetch("https://ghibliapi.vercel.app/people")
  .then((response) => response.json())
  .then((people) => console.log(people))
  .catch((error) => console.log("FAIL"));

However, this promise will still resolve most of the time. For example, if you wanted to make a request to a URL that doesn't exist, you would still get a response. It would just be a response that says 404 - not found. This is the same for any other HTTP error code. fetch() only throws an error if the request fails to reach the server due to a network failure or if the request is blocked by the browser.

If you wanted to throw errors like 404 - not found. Then you would need something like this:

fetch("https://ghibliapi.vercel.app/people")
  .then(function (response) {
    if (!response.ok) throw new Error("Not 2xx response from server");
    return response.json();
  })
  .then((people) => console.log(people))
  .catch(function (err) {
    console.log("The data couldn't be fetched", " // ", err);
  });

Here you use the ok boolean property of the response object to check if the response is OK. If it's not OK, you throw an error. The error is then caught by the catch block.

Making POST Requests

The fetch() method can also be used to make POST requests. You can specify the request method, body, and other data in a plain object (called the options argument) as the second argument to the fetch() method:

fetch("https://httpbin.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Nomad",
    age: 30,
  }),
})
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((response) => console.log("FAIL"));

The above code will make a POST request to the https://httpbin.org/post URL. The second argument to the fetch() method is a plain object that specifies the request method, the body, and the headers of the request.

How do Promises Help With the Callback Hell?

Remember the pyramid of doom? Callback hell was a big motivator for the implementation of promises, so now, have a look at how the XMLHttpRequest pyramid of doom example might be written with promises:

const peopleInFilm = fetch(
  "https://ghibliapi.vercel.app/locations?name=Irontown"
)
  .then((locations) => locations.json())
  .then((locationData) => {
    console.log(locationData);
    return fetch(locationData[0].films[0]);
  })
  .then((films) => films.json())
  .then((filmData) => {
    console.log(filmData);
    filmData.people.forEach((personUrl) => {
      fetch(personUrl) // New fetch for each personUrl
        .then((personResponse) => personResponse.json())
        .then((personData) => console.log(personData))
        .catch((error) => console.log("FAILED TO FETCH PERSON DATA", error));
    });
  })
  .catch((error) => console.log("FAIL", error));

It is a lot easier to read than the XMLHttpRequest, but its not exactly easy to read. To be fair, it's no trivial task to have a computer do what you are asking it to do!

Who said promises were a solution to callback hell? Thankfully, the async await syntax can make things even better. Guess what? Async await is syntactic sugar for promises. It's just a different way of writing promises, so make sure you understand them well!

Summary: How to Use the Javascript Fetch Method

You've just explored how to harness the JavaScript fetch() method to make HTTP requests, a vital technique in modern web development. In this lesson, you:

  • Grasped the concept of the fetch() method, a promise-based function that allows you to make HTTP requests.
  • Found out that you need to convert the fetched response into JSON or text format using .json() or .text() methods, which are also asynchronous
  • Realized the importance of error handling with .catch(), ensuring your code can gracefully handle network failures or other exceptions during data retrieval.
  • Understood the significance of checking the response.ok property to handle HTTP errors like 404 or 500 statuses, which don't inherently throw errors in the fetch promise.
  • Discovered how to make POST requests by passing in an additional options object to fetch(), specifying the method, headers, and body of the request.