A Practical Guide to fetch API

A Practical Guide to fetch API

The XMLHttpRequest has been our most reliable way to make request, which isn’t that pretty at all. If you were using jquery then you had more concise syntax.

However, XMLHttpRequest is now getting overthrown by Fetch API, which can both be used to make network requests and also Promise-based, which enables a prettier, more concise syntax.

Using Fetch API

The fetch() method only has one mandatory argument, which is the URL of the resource you wish to fetch. We’ll be using a zip code api for the exmaples. is a zipcode API that takes in a zipcode a gives the location info Here is what a basic exmaple would look like.

  .then(res => console.log(res));

If you open your browser console you should see a Response like this:

  Response {
          type: "cors", url: "", redirected: false, status: 200, ok: true, ...}
          body: (...)
          headers: Headers {}
          ok: true
          redirected: false
          status: 200
          statusText: "OK"
          type: "cors"
          url: ""

The request was successful, but wait, it was a zip code API right? but where is the data, I mean the info on the location we requested. We requested the zipcode 07100 for Italy.

That’s where json comes in play.

Loading JSON

Like I mentioned before, Fetch API is Promise-based there for it returns a Promise, an object which represents a future result. The So how do we extract that payload from the response we got? It’s easy.

 .then(res => res.json())
 .then(data => console.log(data))

Noticed that there wasn’t a semicolon ; at the end of the fetch(), that’s because it returns a promise. We used the .then() to map the response to json and we used the other .then() to get the data (the location info).

Catching Errors

Since fetch() returns a promise, we can use the catch method to intercept any error occurring during the execution of the request.

 .then(res => res.json())
 .then(data => console.log(data))
 .catch(err => console.error(err))

Request Headers

To set the HTTP request header is essential, and we are able to do that by using the Headers object:

const headers = new Headers()
 headers.append('Content-Type', 'application/json')

To attach the headers to the request, we use the Request object, and pass it to fetch() instead of simply passing the URL.

    async function zipLocation(){
      const URL = ``;
      const fetchResult = fetch(
        new Request(URL, {
          method: 'GET', cache: 'reload'

      const response = await fetchResult;
      const jsonData = await response.json();



To round off the article, here’s a runnable example demonstrating how to get location info using a country zip code and display the info in list. Try editing the code by changing the country short code like Italy(it), USA(us) Canada(ca) etc.

See the Pen fetch-api by Anthony (@anthonystarrck) on CodePen.

comments powered by Disqus