JavaScript Fetch | How to use Fetch API to get the data

JavaScript Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest. Lets start to look into JavaScript Fetch

In a very simple manner all you really do is call fetch with the URL you want, by default the Fetch API uses the GET method, so a very simple call would be like this:

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

So first we are calling the Fetch API and passing it the URL we defined as a constant above and since no more parameters are set this is a simple GET request. Then we get a response but the response we get is not JSON but an object with a series of methods we can use depending on what we want to do with the information, these methods include:

  • json() – Lastly we have the method to that resolves the promise with JSON.
  • text() – In this case it resolves with a string.
  • blob() – This is one resolves with a Blob.
  • arrayBuffer() – In here we return a promise that resolves with an ArrayBuffer.
  • clone() – As the method implies this method creates a clone of the response.
  • redirect() – This method creates a new response but with a different URL.
  • formData() – Also returns a promise but one that resolves with FormData object.

Example to Load JSON

Now let’s see how we can extract the JSON payload from that response once the request completes:

fetch('https://www.reddit.com/r/javascript/top/.json?limit=5')
.then(res => res.json())
.then(json => console.log(json));

We start the request by calling fetch(). When the promise is fulfilled, it returns a Response object, which exposes a json method. Within the first then() we can call this json method to return the response body as JSON.

However, the json method also returns a promise, which means we need to chain on another then(), before the JSON response is logged to the console.

And why does json() return a promise? Because HTTP allows you to stream content to the client chunk by chunk, so even if the browser receives a response from the server, the content body might not all be there yet!

Async … await

The .then() syntax is nice, but a more concise way to process promises in 2018 is using async … await — a new syntax introduced by ES2017. Using async Ú await means that we can mark a function as async, then wait for the promise to complete with the await keyword, and access the result as a normal object. Async functions are supported in all modern browsers (not IE or Opera Mini) and Node.js 7.6+.

Here’s what the above example would look like (slightly expanded) using async … await:

async function fetchTopFive(sub) {
  const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
  const fetchResult = fetch(URL)
  const response = await fetchResult;
  const jsonData = await response.json();
  console.log(jsonData);
}

fetchTopFive('javascript');

Not much has changed. Apart from the fact that we’ve created an async function, to which we’re passing the name of the subreddit, we’re now awaiting the result of calling fetch(), then using await again to retrieve the JSON from the response.

That’s the basic workflow, but things involving remote services doesn’t always go smoothly.

Change the Request Method and Headers

Looking at the example above, you might be wondering why you couldn’t just use one of the existing XMLHttpRequest wrappers. The reason is that there’s more the fetch API offers you than just the fetch() method.

While you must use the same instance of XMLHttpRequest to perform the request and retrieve the response, the fetch API lets you configure request objects explicitly.

For example, if you need to change how fetch() makes a request (e.g. to configure the request method) you can pass a Request object to the fetch() function. The first argument to the Request constructor is the request URL, and the second argument is an option object that configures the request:

async function fetchTopFive(sub) {
  const URL = `https://www.reddit.com/r/${sub}/top/.json?limit=5`;
  try {
    const fetchResult = fetch(
      new Request(URL, { method: 'GET', cache: 'reload' })
    );
    const response = await fetchResult;
    const jsonData = await response.json();
    console.log(jsonData);
  } catch(e){
    throw Error(e);
  }
}

fetchTopFive('javascript');

Here, we specified the request method and asked it never to cache the response.

You can change the request headers by assigning a Headers object to the request headers field. Here’s how to ask for JSON content only with the 'Accept' header:

const headers = new Headers();
headers.append('Accept', 'application/json');
const request = new Request(URL, { method: 'GET', cache: 'reload', headers: headers });

You can create a new request from an old one to tweak it for a different use case. For example, you can create a POST request from a GET request to the same resource. Here’s an example:

const postReq = new Request(request, { method: 'POST' });

You also can access the response headers, but keep in mind that they’re read-only values.

fetch(request).then(response => console.log(response.headers));

Request and Response follow the HTTP specification closely; you should recognize them if you’ve ever used a server-side language. If you’re interested in finding out more, you can read all about them on the Fetch API page on MDN.

One Comment

  1. ปั๊มไลค์ said:

    Like!! Thank you for publishing this awesome article.

    May 26, 2020
    Reply

Leave a Reply

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