Javascript Fetch API Guide: Examples for All Methods

A comprehensive guide to the Javascript Fetch API with examples for all methods and error handling.

Share it on:

Javascript Fetch API Guide: Examples for All Methods

In this tutorial, I'm going to explain how the Fetch API works and how to send request using Async/Await and Promises. Also, How to handle errors.

Sound good? Let's get started.

What is Fetch API in Javascript?

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.

Fetch API Request Overview

Here's what a simple Fetch request setup looks like:

devsdash.com logo

Code Copied!

fetch('http://example.com/posts')
  .then(response => response.json())
  .then(data => console.log(data));

However, Fetch requests can also contain much more options like this:

devsdash.com logo

Code Copied!

fetch("http://example.com/posts", {
  method: "POST",
  mode: "cors",
  cache: "no-cache",
  credentials: "same-origin",
  headers: {
    "Content-Type": "application/json",
  },
  body: { slug: "hello-world" },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

What are all of these options?

Don't worry. You don't need to use all of these options. However, they're good to know.

Fetch API Response Overview

Now that we understand what's the content of a Fetch request. Let's take a look at the response.

Fetch response() object contains properties and methods.

Fetch API response properties

Properties hold information about the sent request.

I will not go through all the properties but the important ones. If you want more in-depth information please see Response - Web APIs | MDN.

Fetch API response methods

Methods are used to parse the response data to your desired data type.

For example: if a server sent response data in JSON like this:

devsdash.com logo

Code Copied!

[
  {
    userId: 1,
    id: 1,
    title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    body: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto",
  },
  {
    userId: 1,
    id: 2,
    title: "qui est esse",
    body: "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla",
  },
  {
    userId: 1,
    id: 3,
    title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    body: "et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut",
  }
]

You can't read the properties of this JSON object because it's stringified (Converted to string).

So, we need to use the response() object methods to convert it to an actual JSON object that we can use in our Javascript code.

I will not go through all the methods but the important ones. If you want more in-depth information please see Response - Web APIs | MDN.

Send GET requests using Fetch API

Let's see how to send GET requests in Javascript using Fetch API.

Async

This is a Fetch GET request example using Async / Await. Also, we're expecting a JSON response.

devsdash.com logo

Code Copied!

async function get() {
  const response = await fetch(
    "http://example.com/posts"
  );
  const data = await response.json();
  console.log(data);
}

Note that we used the method response.json() because we're expecting a JSON response.

Promises

This is a Fetch GET request example using Promises. Also, we're expecting a TEXT response.

devsdash.com logo

Code Copied!

fetch('http://example.com/posts')
  .then(response => response.text())
  .then(data => console.log(data));

Note that we used the method response.text() because we're expecting a TEXT response.

Send POST requests using Fetch API

Let's see how to send POST requests in Javascript using Fetch API.

Async

This is a Fetch POST request example using Async / Await.

devsdash.com logo

Code Copied!

async function post() {
  const response = await fetch("https://example.com/posts", {
    method: "POST",
    body: JSON.stringify({
      title: "foo",
      body: "bar",
      userId: 1,
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8",
    },
  });

  const data = await response.json();
  console.log(data);
}

Promises

This is a Fetch POST request example using Promises.

devsdash.com logo

Code Copied!

fetch("https://example.com/posts", {
  method: "POST",
  body: JSON.stringify({
    title: "foo",
    body: "bar",
    userId: 1,
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

Note that other methods (e.g., PUT, DELETE, PATCH) are similar to the POST method implementation.

Handling Fetch API Erros

Now that you know how to send requests and read responses. Let's take a look at handling errors since it's important to give feedback to the users if an error occurs.

Async

Here's an example of handling Fetch API errors when working with Async / Await.

devsdash.com logo

Code Copied!

async function get() {
  const response = await fetch(
    "https://example/posts"
  );

  //Check if response status is 200 - 299
  if (!response.ok) {
    const error = response.status;
	
    //Here is where you give feedback to the user or log the error
    throw new Error(error);
  }

  const data = await response.json();
  console.log(data);
}

Promises

Here's an example of handling Fetch API errors when working with Promises.

devsdash.com logo

Code Copied!

fetch("https://example/posts")
.then((response) => {
  //Check if response status is 200 - 299
  if (response.ok) {
    return response.json();
  }

  const error = response.status;

  throw new Error(error);
})
.then((data) => console.log(data))
.catch((error) => {
  //Here is where you give feedback to the user or log the error
  console.log(error);
});

In This tutorial

  • Introduction