The Fetch API is one of the crucial technologies that allow for the smooth and effortless creation of Web apps. It is a known fact that building user-friendly interfaces is a core aspect of web development in this modern age. One of the techniques that allow for this is by enabling the exchange of data between a web page and a server without the need to refresh the web page. As a result, the experience gets better and the web page feels more interactive. Hence the introduction of this powerful and effective technology, Save us from the crutches of the conventional and outdated XMLHttpRequest. Allowing us to focus on creating efficient and functional applications.

The purpose of this article is to discuss the Fetch API – what it does, how it works and where it can be efficiently utilized in Web development. In web development, one must have come across the term Asynchronous calls, this is because they are the cornerstone of creating a responsive application. Which is why the Fetch API is as important – More specifically the Promise aspect of it.

What is the Fetch API?

Fetch API is a new interface that allows servers to communicate with Javascript through HTTP requests. That way, there's no need to refresh the webpage every time you want to get new data from the server. The Fetch API is basically a better version of the older XMLHTTPRequest API, allowing for more complex and effective ways to initiate requests.

The Fetch API is better than its predecessor XMLHTTPRequest as it does not make use of call back functions instead it relies on the usage of promises. Asynchronous functions can be complex, but promises make it easier to manage them. Future completion that would dictate if the request worked or not - with the value depending on the latter, would be held by the promise.

With the fetch API, however, the application is able to send and receive other types of requests like GET, POST, PUT, DELETE and others. Other modern aspects like the ability to work with JSON responses and passing custom headers, sending credential requests are also supported.

What Is the Purpose of the Fetch API?

The Fetch API serves one purpose which is to send HTTPS requests to a server. This whole cycle starts once JavaScript calls the `fetch` method with `resourcelocator` `fetch('https://example.com/resource')`. End this method results with resolving the promise with Response containing the data obtained from the server.

Fetching API is versatile and supports a wide range of input parameters chiefly including querying a database, actively pushing the information obtained from UI, or even invoking files located on another server. The syntax is straightforward yet offers a great variety of simple and advanced requests functionality.

Basic Fetch Example

  fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was an error!', error);
});


In this example, the `fetch` function then takes in a URL and uses the GET HTTP method to fetch resources for that URL. After the requested URL sends its response over to the server, the javascript `then()` method proceeds to execute the code in it. The `response` token passed is an object containing the response received from the targeted server. In order to retrieve the information from this object which is in the form of JSON, `JSON.parse` is done using the `response.json`. Finally, to complete the process, the data is output through logs by `console.log`.

If there is an error (for instance, the server is unreachable), the error is reported because it has been logged using `console.log` in the `catch` method.

Fetch API Response Handling

Always remember that when using Fetch API, knowing how to manage the response of the server is very important. A response object has a number of methods that when used allowfor the processing of the data. Some of them are quite common and can be used in this particular case with the Fetch API.


1. response.json() : The response returned from the server can be a valid string in JSON format - this method approaches that string and formats it as a javascript object.

2. response.text() : If the server has sent the data in non-JSON format, for instance, returning an HTML or a simple text file, this method retrieves it and responds with it as plain text.

3. response.blob() : Servers might store images, videos, or other files specifically in binary data. This method is relevant here as it serves to retrieve the mentioned binary data.

4. response.status : When questions around whether the request was successfully processed - was there an error or not, arises, this property is relevant as it holds the answer by storing the HTTP codes.

Response Handling Example

  fetch('https://api.example.com/data').then(response => {
const statusCode = response.status;
if (!(statusCode > = 200 && statusCode < 300)) {
throw new Error("Network response was not ok");
}
return response.json();
}).then(data => {
console.log(data);
}).catch(error => {
console.error('There was a problem with the fetch operation:', error);
});


In the above example, therefore it was decided to use the `response.ok` property which returns a boolean value that is true only if the server response was ranging between 200 (successful) to 299. If this is not the case, an error is returned.

Using Fetch for POST Requests

A common applied POST request is to send data to the server, while GET is mostly applied to get a request for the server so to say the two are almost complete opposites. The Fetch API also has an option for you to set the method to POST where you can specify headers and body content.

Fetch POST Example

  const data = {
username: 'john_doe',
email: '[email protected]'
};
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log('User created:', data);
})
.catch(error => {
console.error('There was an error!', error);
});


Here we create a `data` object which consists of users' data and we use the `fetch()` function with the `POST` method and the `body` option holds the stringified JSON data and with the `headers` option we mention that we're sending data in JSON format.

Fetch API and Catching Errors

One of the important aspects of working with the Fetch API is error handling. A fetch request can fail for many reasons, for example, incorrect URL path, server malfunctioning, or network issues. Fetch API does not throw an error on its own for the failure HTTP status codes (like 404 or 500). Instead, it only throws a rejection of the promise if there is a network problem or the request has been unsuccessfully completed.

Relate Articles…