Javascript Fetch API Simplified

Javascript Fetch API Simplified

2022-08-05

0

35

Javascript Fetch API Simplified

One of the most usages of javascript is making Requests to backends using Ajax without Page Reload. The ancient way of doing request is use XMLHttpRequest API, that was just fine but requires long code and not really simple to achieve. JQuery came to solve complexity of XMLHttpRequest and provided an API to make Ajax Requests which we so popular for long period of time. So Today we going to learn the most modern way using Fetch API.

Fetch API Compared to jQuery Ajax

  • Fetch API is native to javascript, thats means it doesn’t add more load to your application as jQuery do, also it makes it usable whatever JavaScript Framework you are using as it has no dependencies.
  • Fetch API Promise won’t fail or reject on HTTP error response like 404 … etc, instead it will just continue and set ok value to false, but it will only fails and reject on Network errors.
  • jQuery Ajax is just a wrapper for XMLHttpRequest so it’s safer to use on very old Browsers for competabiliy but almost every modern browser now supports Fetch API.
  • Fetch API won’t send Cookies by default, so some authentication processes may fail but of course you can set the cookies manually with initial options.
  • Fetch API doesn’t support timeouts, which means request will keep going trying yo get response until browser decides not to. For sure you can overcome this using Promise.race() . We will learn more about this.

Get Started

In this tutorial we going to use JSONPlaceHolder API as for demonstration purposes, it’s Free and more than enough for our tutorial

Fetch API is totally native to Javascript so we don’t need to add any packages or libraries, just a typical HTML document to work with

HTTP GET Request

Now we going to learn how to issue a GET request to get list of posts

EndPoint : jsonplaceholder.typicode.com/posts

Code Explainations

  • First we wrapped our code within DOMContentLoaded event to make sure code executes once Page fully loaded to avoid any further issues.
  • fetch function is used to issue ajax request, it takes 2 arguments. First argument indicates the endpoint or url you are issuing request to, second arguments is initial options where you can specify more options regarding your request and we don’t use it here as we has nothing special. Note : fetch by default consider you are making a GET request unless you specify something else.
  • fetch will always return a Promise that’s why we used then method to chain execution after request is done
  • After request completed we chained it with a callback to extract Response Body as Json using response.json() which also will return a Promise.
  • Finally we chained another callback to console.log the Json Response to the console.

Another Example

Let’s try again to get a single post item and console.log its title

EndPoint : jsonplaceholder.typicode.com/posts/1

HTTP POST Request

Since we now know how to make GET requests then POST request won’t be any hard, it’s almost similar with only few points

  • We need to tell Fetch API that we are using POST instead of GET
  • Mostly with POST requests we need to pass Data to the request
  • Optionally some APIs requires some headers to be sent with the Request
  • Also you may need to work on APIs that requires authentication and authorization. This Points can be achieved easily using the second argument of fetch method, actually it expects an object with some options modifier, so we gonna use method and body options, Optionally : we can use headers option.

EndPoint : jsonplaceholder.typicode.com/posts

HTTP PUT Request

Its similar to POST request but we set method option to PUT, PUT Requests usually used to update a resources.

EndPoint : jsonplaceholder.typicode.com/posts/1

HTTP DELETE Request

DELETE Request is usually used to delete a resource on server

EndPoint : jsonplaceholder.typicode.com/posts/1

Extra Bonus

Now since we can work well with Fetch API it’s time for some bonus tips and tricks

Timeouts

As we said before Fetch doesn’t support timeouts , so how we can handle timeouts ? Well it’s totally simple since fetch return a Promise so we can use race .

Final Code

shape shape

Join our newsletter!

Enter your email to receive our latest newsletter.

Don't worry, we don't spam