<img alt="JavaScript Fetch API Explained" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/JavaScript-Fetch-API-Explained.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

JavaScript Fetch API provides an intuitive way to make requests from your application client running in the browser.

It is both easy to use and makes use of modern JavaScript syntax. This article is a guide on how to use the Fetch API.

What is JavaScript Fetch API?

JavaScript Fetch API is an interface modern browsers provide to make requests from the front end. It provides an alternative to the older AJAX XMLHttpRequest.

It is available as a global function called fetch. When called with arguments, this function returns a promise that resolves to a response. With the fetch function, you can make all sorts of HTTP requests.

Advantages of Fetch API Over Other Methods

  • It has a simpler and more intuitive interface that is easy to learn and use. As a result, your code becomes cleaner when you use the Fetch API. XMLHttpRequest is more complicated, and your code is not as clean as when you use the Fetch API.
  • It supports promises, which enables you to write asynchronous code more cleanly. XMLHttpRequest does not support them; instead, you must add callbacks to event handlers. Depending on your preference, you might prefer the JavaScript Fetch API.
  • It is natively supported in the browser. This means you do not need to add additional libraries to make requests. Additional libraries will make your JavaScript bundle larger and slow down your website.

Using the Fetch API

This section will cover making different requests using the JavaScript Fetch API. To write the code, you may use whatever editor you prefer. Just make sure you run the code in the browser. I will run it inside a script tag in an HTML file.

A Simple GET Request

First, we are going to learn to make a simple get request. The code for doing so follows this structure:

fetch(url)

Therefore, if we wanted to fetch posts from the JSON Placeholder API, you would do it as follows:

fetch('https://jsonplaceholder.typicode.com/posts');

The function call will return a promise, resolving the API response or an error if one has been encountered. Therefore, to access the response, we will use the await keyword. But we can only use the await keyword in an asynchronous function.

So, we will wrap the fetch function with an async function and call that. If you are unfamiliar with all this, here is a detailed guide on Asynchronous JavaScript. Anyway, the code:

async function getData() {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    console.log(response);
}

getData();

If you run the code above, you should get the following output in your output.

<img alt="async output" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-25-15-40-46.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

The output indicates that the fetch function returned a Response object. This object has properties that include the status, headers, and body. The response data is stored as a JSON string in the body. Therefore, we must extract the string and parse the JSON to get the data as a JavaScript Object.

Luckily, the Response object has a handy method called json(). This method reads the response’s body and tries to parse the string as JSON. It returns a promise that resolves to an object parsed from the JSON.

However, this method will raise an error if the body is not a valid JSON string. Therefore, we should only parse the JSON if the response has a 200 status code.

So, the code to get posts will be as follows:

async function getData() {
    const response = await fetch(
        "https://jsonplaceholder.typicode.com/posts"
    );

    if (response.status == 200) {
        const posts = await response.json();
        console.log(posts);
    } else {
        console.log("Something went wrong:", response.status);
    }
}
getData();

Running the above code will yield the following results:

<img alt="code output" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-25-16-07-18.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

This is an array of a hundred posts.

Some API endpoints require headers. These headers could be used for authorization, for example. The JavaScript Fetch API provides an easy way to send headers as part of the request. You must pass an options argument to your fetch function call to specify headers.

fetch(url, options);

So, our previous example would now look like this:

async function getData() {
    const response = await fetch(
        "https://jsonplaceholder.typicode.com/posts", {
             headers: {
                 'x-auth': ''
             }
         }
    );

    if (response.status == 200) {
        const posts = await response.json();
        console.log(posts);
    } else {
        console.log("Something went wrong:", response.status);
    }
}
getData();

Because the JSONPlaceholder API does not require an authorization header, the above code will work as before. However, it is important to know that the option to pass in headers exists.

Passing in Other Options

In addition to passing in headers, you can pass many other options to the fetch function. The two options you will pass a lot are the request method and request body options.

We will make a POST request to the JSONPlaceholder API to demonstrate passing them both. Here is the code to do that:

async function getData() {
    const response = await fetch(
        "https://jsonplaceholder.typicode.com/posts", {
             method: 'POST',
             body: JSON.stringify({ 
                 title: 'Fetch API',
                 body: 'Lorem Ipsum',
                 userId: 1,
             })
        }
    );

    if (response.status == 200) {
        const posts = await response.json();
        console.log(posts);
    } else {
        console.log("Something went wrong:", response.status);
    }
}
getData();

In our options object, we have specified the request method we want to use and the body as properties. For both properties, we provided string arguments. We provided the string ‘POST’ for the request method since we want to make a POST request. We also provided a JSON string for the body property. This JSON string is formed by stringifying an object with the needed properties.

Running this code in the browser yields the following output:

<img alt="Passing in Other Options output" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-25-18-00-37.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

The output is an object that contains the ID we just received from the server. Here is a great resource for the full list of options you can pass in.

Errors When Using the JavaScript Fetch API

#1. Network Errors

When making network requests, it is common to encounter errors. The fetch function returns a promise that resolves to the result or rejects when a network error has been encountered. Therefore, we must wrap our code in a try/catch block. To handle network errors gracefully.

#2. Other Errors

In addition to network errors, you may also encounter other errors, such as 404s, 403s, and 500s. The fetch function does not throw an error when such errors are encountered. Therefore, you need to check for them by checking the response status code. For example, in the previous examples, we have only attempted to parse the response body when the status code was 200.

#3. CORS Errors

Other common errors you will encounter are CORS errors. CORS stands for Cross-Origin Resource Sharing. An Origin is the unique combination of a server’s protocol, host, and port. For example, my website could be running on localhost, the host, on port 5500, the port, and served over HTTP, the protocol. Therefore, the origin of that website would be http://localhost:5500.

The same website will make an API request to the https://jsonplaceholder.typicode.com API, a different origin. Therefore, these two origins, localhost, and JSONPlaceholder, are sharing resources. That is Cross-Origin Resource Sharing. However, the API server needs to enable CORS this to work. This is not always the case. The solution to handling such errors would be to make requests through a CORS-enabled proxy server.

Browser Support

The fetch API is a fairly modern feature. According to CanIUse.com, about 95% of global users have browsers that support it.

<img alt="browser support" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-25-19-23-58.png/w=800" data- decoding="async" src="data:image/svg xml,” width=”800″>

Conclusion

The JavaScript Fetch API is a syntactically better and more elegant way to write frontends that make API requests. Given its limited browser support, you might consider other HTTP client libraries.