Using the New JavaScript Fetch HTTP API

Sharing is Caring

With web and mobile applications, it’s really common to request and show data received from another server. The data could be anything like users, posts, make payments, or display a map – all of this is done through using APIs. (See blog post What is An API)

Fetch is a browser API that allows us to retrieve or submit remote data using the fetch() function. The Fetch API provides a function that returns a promise that lets us do something with the response from the request we sent.

Benefits of the Fetch API

Recently, the new Fetch API became available in a lot of modern browsers. The Fetch API’s massive benefit is that it’s much easier to make asynchronous requests and handle responses than the old AJAX way (XMLHttpRequest). The Fetch API uses promises and allows us to avoid callback hell. 🙂

And of course, the other benefit is that it removes the need for libraries that abstract away the XMLHttpRequest. No point in shipping need less code to the client.

The fetch API is a very developer-friendly and simple Promise based API for making requests and getting responses. The simple definition makes it really to use.

Fetch API – Basic Example

The fetch method has one required argument which is the URI of the resource we need to fetch. Here’s a fairly basic example of us fetching data using the Open Weather Map’s API.

Fetch API – More Sophisticated Example

Our options object can accept quite a few more parameters like Headers, Body (in the case of a PUT or POST request). We might even need to do Authorization.

Reasons to Consider Not Using Fetch

As with everything in development, there are trade-offs that have to be made. Right now, there isn’t a fully supported way of aborting a fetch request though it can be done using an experimental API available in Chrome and Firefox.

Streams can’t be used because of the use of promises which means progress indicators aren’t possible. If you need stream support the axios library or using XMLHttpRequest might be better options.

Wrapping It Up

Fetch is a great potential alternative for simple use cases as it abstracts away a lot of the potential pain of XMLHttpRequest and reduces the size of our bundles.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.