Making sense of the Fetch API

Ryan Hutzley
Nerd For Tech
Published in
5 min readMay 31, 2021

--

I have recently started down the long and winding road to becoming a software engineer. To be honest, the road still seems daunting at times, but I have fallen in love with the hands-on problem-solving component of software engineering that comprises the day-to-day. I have also immensely enjoyed the material that I’ve learned thus far. One topic that I kept coming back to over the last few days and weeks has been the Fetch API. In this blog, I will go over the basics of the Fetch API. First, however, I will explain what an API is and how it works, as well as the data transferral process pre-fetch(). This will help highlight the unique functionalities of the Fetch API, especially relative to its AJAX predecessor XMLHttpRequest.

What is an API?

API stands for Application Programming Interface. IBM, on its website, explains an API as “a set of defined rules that explain how computers or applications communicate with one another. APIs sit between an application and the web server, acting as an intermediary layer that processes data transfer between systems” (see IBM site here). As a beginner software developer, this idea makes sense — the idea of an API serving as the “intermediary layer” that allows data to be passed from one system to another. IBM, once again, offers a simple, but effective description of how a basic API functions.

1. A client application initiates an API call to retrieve information — also known as a request. This request is processed from an application to the web server via the API’s Uniform Resource Identifier (URI) and includes a request verb, headers, and sometimes, a request body.

2. After receiving a valid request, the API makes a call to the external program or web server.

3. The server sends a response to the API with the requested information.

4. The API transfers the data to the initial requesting application.

(these steps are taken from this site)

Now that we have a basic understanding of what an API is and how it works, let’s look at how this request-response style of data transfer occurred before the advent of fetch().

The Internet Pre-fetch()

The creation of the Fetch API and its predecessor, XMLHttpRequest were founded upon the development and implementation of a revolutionary concept called AJAX (Asynchronous JavaScript and XML). In essence, AJAX allowed web pages to be updated asynchronously. This meant that specific parts of the web page could be updated while data was being exchanged “behind the scenes.” Pre-AJAX, a data exchange that required even the smallest update to the web page necessitated a full page refresh, making AJAX a tremendous breakthrough for both the enhancement of user experience as well as data transferral capabilities. The XMLHttpRequest object became one of the first ways to create AJAX requests — to retrieve data from a URL and to update just part of the web page without having to refresh. XMLHttpRequest objects can retrieve any type of data (not just XML as its name implies).

The Fetch API

Fetch is a native JavaScript API developed after XMLHttpRequest that utilizes AJAX programming. Below is the structure of a basic fetch request taken from MDN:

fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));

Let’s go over what is happening in this code. First, the fetch is retrieving data from the URL http://example.com/movies.json . The fetch then returns a Promise (for more information on Promises check out this very useful article by Jake Archibald, found here). Regardless of whether the data is successfully retrieved, the fetch will return a Promise object. The Promise then resolves to a response object. Next, the first .then function will take this response object and convert it into JSON using the built-in .json() method (check out this page for more info on JSON). Lastly, the second .then takes the object converted to JSON in the previous .then and console.log’s that object. Additionally, a .catch() function can be added to the above code to receive an error object in the event that the request fails.

The fetch() method also accepts an optional second parameter — a configuration (or init) object. The configuration object allows for the retrieval and manipulation of back-end data in many different ways. MDN provides a useful example of a fetch request using a configuration object (found here). At its core, however, the configuration object allows fetch() to not only retrieve data, but to create, read, update, and delete data (CRUD for short). We expect modern APIs to be able to perform CRUD functions. The fetch() method meets these expectations through the designation of a “request verb, headers, and sometimes, a request body” as explained earlier. For example, data can be created using fetch() with a configuration object containing the request verb POST, read by including the request verb GET, updated by including PATCH, or deleted by including DELETE. There exist other types of requests but these four are the most basic. I have relied on these requests almost exclusively when completing challenges and building mini-projects.

What Makes the Fetch API Better Than XMLHttpRequest?

Other blogs have been dedicated to this question alone, but I will briefly outline the main advantages of using fetch() over XMLHttpRequest. Firstly, the Fetch API is just simpler than using an XMLHttpRequest object. It requires less logic to be hardcoded into the request (specifically when handling responses and errors). Additionally, the use of Promises and well-defined request and response objects within the Fetch API lend itself to the crafting of cleaner, easier to understand code relative to equivalent XMLHttpRequest code. Overall, the Fetch API “provides a more powerful and flexible feature set” relative XMLHttpRequest (see MDN Fetch API). If you are interested in a closer comparison of fetch() and XMLHttpRequest please check out Swapnil Bangare’s blog, The Fetch API, along with this relevant Google Developers Documentation.

Conclusion

In this blog, I touched on a few different topics — all centered around the Fetch API. First, I provided a basic understanding of APIs in general. Second, I situated the Fetch API in the broader context of the request-response cycle that characterizes how we, as clients, engage with websites to both access and manipulate data. With the advent of AJAX, this cycle is now asynchronous. Third, I gave an overview of the basics of fetch(). And lastly, I briefly compared fetch() to its predecessor XMLHttpRequest. I hope that you learned something about the Fetch API from my blog. I enjoyed learning about APIs and how data is transferred from one system to another, and as I continue to learn and grow as a software engineer I look forward to posting regularly about whatever new software engineering idea or topic it is that has inspired me!

--

--

Ryan Hutzley
Nerd For Tech

Princeton University '20, B.A., Flatiron School Software Engineering Graduate