How to use the Fetch API in JavaScript

How to use the Fetch API in JavaScript

ยท

2 min read

Hey All ๐Ÿ‘‹

In this article, we'll be covering the Fetch API in JavaScript how you can use it to make HTTP requests.

What is the Fetch API?

The fetch() method provides a simple way to make HTTP requests in JavaScript.

It is natively in the browser, meaning you don't have to import an additional module (like axios).

Additionally, its asynchronous and promise-based which makes catching errors and handling responses easy.

Using the Fetch API

The syntax is very simple, you just have to use the fetch() method

Making a GET request is very simple:

fetch('request url')

Replace request url with the URL you want tor request.

The fetch method returns a promise, which means there are two ways you can handle the response.

Using .then Syntax

fetch('request url...')
      .then(response => response.json())
      .then(json => console.log(json))
      .catch(error => console.error(error));

Using async/await

async function makeRequest() {
    const response = await fetch('request url...');
    const json = await response.json();
    console.log(json);
}

We can improve the async/await further by wrapping it in a try/catch statement to catch an error:

async function makeRequest() {
    try {
        const response = await fetch('request url...');
        const json = await response.json();
        console.log(json);
    } catch (error) {
        console.error(error)
    }
}

Additional Options

You can add options to the request by adding a second parameter.

This allows you to add headers, change the request type, and more.

For example, to make a post request:

fetch("https://example.com/profile", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });

The method can be set as any HTTP Request method like GET, POST, PUT, DELETE, etc.

The headers object is used to control the headers of the request.

This could be used for authenticating requests, changing the content type (like in the request above), or other headers you want to include.

The body is the request's body.

Wrapping up

That is a overview of how the Fetch API works in JavaScript.

It can used as an alternative to popular packages like axios, as well as built in methods like XMLHttpRequest

๐Ÿ‘Œ Thanks for reading this article!

If you like what I do and would love to see more related content, follow me on my other social platforms:

Twitter: Blake Yeboah

GitHub: Blake-K-Yeboah

LinkedIn: Blake Yeboah

ย