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. Zippopotam.us is a zipcode API that takes in a zipcode a gives the location info Here is what a basic exmaple would look like.

        
          fetch(`http://api.zippopotam.us/it/07100`)
          .then(res => console.log(res));
        
      

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

        
        Response {
          type: "cors", url: "http://api.zippopotam.us/it/07100", redirected: false, status: 200, ok: true, ...}
          body: (...)
          headers: Headers {}
          ok: true
          redirected: false
          status: 200
          statusText: "OK"
          type: "cors"
          url: "http://api.zippopotam.us/it/07100"
        
      

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 question remain, how do we extract that payload from the response we got.

Here is how:

        
        fetch(`http://api.zippopotam.us/it/07100`)
        .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.

        
          fetch(`http://api.zippopotam.us/it/07100`)
          .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 = `http://api.zippopotam.us/it/07100`;
      const fetchResult = fetch(
        new Request(URL, {
          method: 'GET', cache: 'reload'
        })
      )

      const response = await fetchResult;
      const jsonData = await response.json();
      console.log(jsonData);
    }

    zipLocation();

  

Conclusion

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.

  

  

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

Try editing the code by changing the country short code like Italy(it), USA(us) Canada(ca) Exmaple:

  
    fetch(`http://api.zippopotam.us/us/90002`)
    //us for USA -- zipcode: Los Angeles
    //by default the URL is api.zippopotam.us
    //so just add a / and place the country short code followed by the zip code
  

See how many countries they support