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.
If you open your browser console you should see a Response like this:
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.
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.
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).
Since fetch() returns a promise, we can use the catch method to intercept any error occurring during the execution of the request.
To set the HTTP request header is essential, and we are able to do that by using the Headers object:
To attach the headers to the request, we use the Request object, and pass it to fetch() instead of simply passing the URL.
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.