How to use Fetch API to create HTTP request

Working with data from the server is an important part. In this article, we’ll see how to use Fetch API to get data.

I. What is Fetch API?

Fetch API is quite similar to XML HTTP Request but much simpler to use. To create an HTTP Request, we need to use the method fetch() of the Fetch API.

The first parameter of the fetch() method is the API URL. This method returns a Promise, and we need to process it to get the desired result.

We use then() to do what we want after the fetch is done and catch() to handle errors.

fetch("https://api.github.com/users")
    .then(response => {
        // handle response data
    })
    .catch(err => {
        // handle errors
    });

II. GET Request

The default request method used in Fetch API is GET.

For example, we get data from GitHub API and log it.

fetch("https://api.github.com/users")
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

III. POST Request

To use a POST request, we need to pass the second parameter of the fetch() method as an option. We then set the method and body parameters in the fetch() options.

const options = {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "new", post: "new post" }),
};

fetch("https://jsonplaceholder.typicode.com/posts", options)
  .then((res) => res.json())
  .then((data) => console.log(data));

Note:Content-Type of Headers defaults to text/plain. To send data as JSON, we need to set it to application/json and the same for other data types.

IV. Response Object

The response object has information about the server’s response to the HTTP request.

Some common response properties:

  • response.status: the response status code.
  • response.statusText: HTTP status code message (default value “"). HTTP/2 does not support status messages.
  • response.ok
  • response.type
  • response.url
fetch("https://api.github.com/users").then((res) => {
  console.log(res.status);
  console.log(res.statusText);
  console.log(res.ok);
  console.log(res.type);
  console.log(res.url);
});

In the Response Object, there are a few methods that help us format the desired data type, such as JSON, text, blob, formData, or arrayBuffer.

  • json() - This method returns JSON.
  • text() - This method returns data of text.
  • blob() - This method returns Blob format.
  • formData() - Returns the type FormData.
  • arrayBuffer() - Returns type ArrayBuffer.

Example:

fetch("https://api.github.com/users")
  .then((res) => res.text())
  .then((data) => console.log(data))
  .catch((err) => console.log(err));

V. Handle errors

fetch() provides us with the catch() method to catch server errors. However, it only catches some error cases. It only takes care of cases like network errors or invalid host addresses etc.

To handle an error, we need to add more steps:

fetch("https://api.github.com/users")
  .then((res) => {
    if (!res.ok) {
      throw new Error("Failed. There's an error!");
    }
    return res.json();
  })
  .then((data) => console.log("Success:", data))
  .catch((error) => console.log("Failed:", error));

VI. Using Async/Await

We can simplify and make the code more coherent with async/await.

async function fetchData() {
  let response = await fetch("https://api.github.com/users");
  let data = await response.json();
  console.log(data);
}

fetchData();

Handle errors with try…catch…

async function fetchData() {
  try {
    let response = await fetch("https://api.github.com/users");
    let data = await response.json();
    if (!response.ok) {
      throw new Error("Failed. There's an error!");
    }
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

fetchData();