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 right the code in JavaScript. If you where using jQuery then you used the cleaner syntax with jQuery.ajax().

Now a days JavaScript has it’s own cleaner way to right the code for request. Its 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 way is call fetch with the URL you want. Default method Fetch API uses is the GET method. So our call would be like this:

 

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 the server URL. If you see closer this method doesn’t have parameters other than URL because its GET request. We get the response of the API in then block if response code is 200 and in catch block if code is anything else. 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 method’s 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 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:

 

So a simple example would look like this:

 

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 familier 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:

 

So isn’t it as simple as GET method? We just added 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

Your email address will not be published. Required fields are marked *