Intro to Fetch API

Noa Rabin-Cohen
4 min readSep 12, 2020

In one of my previous posts, I’ve discussed the importance of the search functionality. However, what happens when you find the resources you were looking for? How do you take those data sets (which sometimes can be quite robust) and implement those into your application?

Luckily, for that exact purpose we have the Fetch API. The Fetch API provides flexible tools to fetch resources, sending requests to resources and getting response objects.

Application Programming Interface, or API, is a set of tools that allows applications to interact with each other. In a nutshell, API is a great function as it automates the developer’s and makes it much simpler and faster. Reason being is that in most cases, a developer will use API to take advantage of existing data or functions. It enables importing data in a quick manner, while adding functionality and allowing the developer to easily implement that data on their application. Fetch API is the interface for JavaScript to make HTTP requests.

JavaScript is a single-threaded language: the block of code runs sequentially. Each action starts after the action before has completed. It’s a great way to make sure that if one action depends on other’s results, no error pop. On the other hand, it could be more efficient if the code block will run all the actions at the same time, in an asynchronous way. One way to write asynchronous code is to use a promise, one of the new features of ES6.

Fetch() is a function used to fetch a resource, makes asynchronous HTTP requests using promises.

But wait, what is a promise?

A Promise is an object that represents the result value of asynchronous operations. According to the state of the promise, we can set how to handle the response. Every response initiates as pending and can be fulfilled (completed) or rejected (failed).

To read more about promises on MDN Web Docs.

When calling the fetch function, we are sending an HTTP request to a source (remote API). The method takes one argument, the URL (path to remote API) for this request:

fetch('https://remote-api-url');

Four primary methods to use with fetch:

  • GET: request for data, the default method.
  • POST: send new data.
  • PATCH : update data
  • DELETE: delete data.

Passing the second argument is necessary when the request propose is other than GET. The options argument is an object that contains details and information about the fetch request:

fetch('https://remote-api-url', options);

the information that must be specified on the options argument :

  • Method: the method for the request: POST, PATCH, DELETE (as mention, GET Is the default value and not need to be specified).
  • Headers: What is the content type that we send.
  • Body: The data to update/add.
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({name: 'Anakin Skywalker', jedi: true }),};

In a PATCH method there’s no need to send all the data, just the values we want to update:

let options = {  method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({name: 'Darth Vader'}),};

And for a delete:

let options = {   method: 'DELETE'};

The source sends an HTTP response and returns a promise that needs to be resolved. Every time that the request complete, the return is a promise, whether the status of the promise is an error or not. The response headers contain the HTTP status: successful request status code is between 200–299, or we can check if the value of response.ok is true. Then, we need to parse the body response, calling .json() on the response to convert the response body to a readable format.

One way to handle the response is to call then on the promise result:

fetch('https://remote-api-url', options).then (response => response.json()).then(data => console.log(data)

Another way is to use an async function, combined with the await keyword. The async keyword makes the function to be a promise. Using the await keyword before the async function stops the code from running until the promise fulfills. This is a new way, part of the ECMAScript 2017 JavaScript edition, and it is easier to write and read:

let response = await ('https://remote-api-url', options);let result = await response.json();

The new syntax, using the await keyword makes it even easier to read and reuse the data.

To Sum up, Fetch API makes our lives as developers much simpler. By using it, we can gather large amounts of data, send them to a remote server and integrate it into any application.

--

--

Noa Rabin-Cohen

Full-Stack Software Engineer experienced in JavaScript, Ruby on Rails, React and Redux.