How to Use the JavaScript Fetch API?

In our past time, we have used XMLHttpRequest to make requests, it has some messy code and it didn’t give us promises. To be honest it was not a clear way to write the code in JavaScript. If you were using jQuery then you used the cleaner syntax with jQuery.ajax().

Nowadays JavaScript has it’s own cleaner way to write the code for the request. It’s known as Fetch API and its a new standard to make the server requests and the good news is Fetch API has promises which we learned over the years. So let’s see how to use the JavaScript’s Fetch API to get the data from the server.

How to use the Fetch API?

One of the simple ways is to call fetch with the URL you want. The default method Fetch API uses is the GET method. So our call would be like this:

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function(response) {
    // Your code for handling the data you get from the API
})
.catch(function(error) {
    // This is where you run code if the server returns any errors
});

 

Isn’t it a very easy way to make a server request? So let’s move ahead and review the code mentioned above.

In the very first line of the code, we are calling the Fetch API and passing it to the server URL. If you see closer this method doesn’t have parameters other than URL because of its GET request. We get the response of the API in then block if the response code is 200 and in catch block if code is anything else. The response we get is not simply a JSON but an object with a collection of methods we can use depending on the operation we want to perform on our information. These methods are as mentioned below:

clone() – This method is used to create a clone of the response.
redirect() – This method creates a new response but with a different URL.
arrayBuffer() – This method returns a Promise that resolves with an ArrayBuffer.
formData() – It returns a promise that resolves with the FormData object.
blob() – This returns a promise that resolves with a Blob.
text() – This returns a promise that resolves with a string.
json() – Lastly we have the method that resolves the promise with JSON.

From these methods, the very common one is json() as it returns the json data. After applying this method the code would look like:

fetch(url)
.then((resp) => resp.json()) // Transform the data into json
.then(function(response) {
    // Your code for handling the data you get from the API
})
.catch(function(error) {
    // This is where you run code if the server returns any errors
});

 

So a simple example would look like this:

fetch('http://example.com/api/users?result=10')
.then((resp) => resp.json())
.then(function(data) {
    console.log(data);
})
.catch(function(error) {
    console.log(error);
});

 

The above-mentioned request is GET request, as there is no method specified in the code and by default, it’s GET request.

Handling POST request

So you are now familiar with the GET request using fetch API but of course, we can also do other types of requests. For other types of requests, we need to pass the object of available options as a second argument to the fetch function. So it would look like something this:

// The data we are going to send in our request
let data = {
    fname: 'John',
    lname: 'Carter'
}
// The parameters we are going to pass to the fetch function
let requestData = {
    method: 'POST',
    body: data,
    headers: new Headers()
}
fetch('http://example.com/api/users', requestData)
.then(function() {
    // Your code for handling the data you get from the API
})
.catch(function(error) {
    // This is where you run code if the server returns any errors
});

 

So isn’t it as simple as the GET method? We just added a few options to it and it’s done. Likewise, we can use other methods like PUT, DELETE, etc.

Final Thoughts
Although Fetch API is the beautiful replacement for XMLHttpRequest we really need it in our life but this is not supported by all browsers yet (IE doesn’t support it). you can use polyfills if you want to make it cross-browser supported.

Leave a Reply