TECHY360
Everything You Need To Know About Tech

EcmaScript how to make an HTTP request using the Fetch API

0 211

ECMAScript (or ES) is a scripting-language specification by Ecma International. It was created with JavaScript to help independent implementations.

In this guide, I will show you how to use the Fetch API (ES6 +) EcmaScript to make HTTP requests to the REST API with some practical cases that you are likely to encounter.

Rest API

Note. All examples are given in ES6 (EcmaScript) with arrow functions.

A common pattern of modern web / mobile applications is to request or display any data from the server (such as users, messages, comments, subscriptions, etc.), and then manipulate them using CRUD operations (create, read, update or delete ) in EcmaScript.

For further data processing, we often use JS methods such as .map (), .filter () and .reduce ().

Here is what we will look at

  • Working with Asynchronous JavaScript
  • What Is AJAX?
  • Why Fetch API?
  • A quick introduction to the Fetch API
  • Fetch API – CRUD Examples ← Good stuff!

1. Work with asynchronous JavaScript

One of the hardest parts with understanding how JavaScript works is how to work with asynchrony, where everything happens in no particular order.

In most programming languages, we are used to the fact that operations are performed in order (sequentially). The first line must be completed before we move on to the next line.

But in JS, we have operations that are executed in the background / active mode, and therefore our web application does not freeze every time it waits for a user event.

However, sometimes things must go in order, otherwise, it will cause chaos and unexpected results. For this reason, we can use promises and callbacks for structuring. 

An example would be checking user credentials before proceeding to the next operation.

2. What is AJAX

AJAX stands for Asynchronous JavaScript and XML and allows you to update web pages asynchronously by exchanging data with the webserver while the application is running. In short, this means that you can refresh parts of a web page without reloading the entire page (the URL remains the same).

AJAX is a bit misleading. AJAX applications can use XML to transfer data, but equally transmit data as plain text or JSON text.

w3shools.com

Is ajax everywhere?

I saw that many developers, as a rule, are very worried that everything is mixed in their SPA (single page application), which leads to a lot of asynchronous pain! 

But, fortunately, we have libraries like Angular, VueJS, and React, which makes this process a little easier.

In general, it is important to have a balance between what should reload the entire page and parts of the page. And in most cases, reloading the page works great in terms of how powerful browsers have become. 

In the past, reloading the page took several seconds (depending on the server location and browser capabilities). But modern browsers are very fast, so deciding whether to perform AJAX or page reloads doesn’t really matter.

My personal experience is that it’s much easier and faster to create a search engine with a simple search button than without it. 

And in most cases, the client doesn’t care – it’s SPA or an additional page reload. Of course, do not get me wrong, I love SPA, but does it really matter in terms of productivity and development time?

In the end, it depends on the use case, but I personally feel that SPAs require more development time and headache than just reloading the page because you need to deal with their asynchrony. 

But I think the promised couple here and there will fix it, right?

3. Why Fetch API?

This allows us to perform declarative HTTP requests to the server. For each request, a Promise is created, which must be resolved according to the type of content and access to the data.

Now, the advantage of the Fetch API is that it is fully supported by the EcmaScript JS ecosystem and is also part of the Mozilla docs MDN. Last but not least, this works in most browsers (except IE). In the long run, I assume this will become the standard way to invoke the web API.

Note! I know other HTTP approaches well, such as using Observable with RXJS, and how it focuses on managing/leaking memory in terms of subscription / unsubscribe, etc. And maybe this will become the new standard way to execute HTTP requests, who knows?

4. A quick introduction to the Fetch API

The fetch () method returns a Promise that resolves the Response of our request to display the status (successful or not). 

If you ever get this message in the console output promise {}, do not panic – it basically means that Promise is working, but waiting for permission. Therefore, to solve it, we need a .then () handler (callback) to access the content.

In short, we first determine the path (Fetch), then request data from the server (Request), then determine the type of content (Body) and gain access to the data (Response).

If you are trying to understand this concept, do not worry. See the examples below.

Related Posts
1 of 26
Fetch API

5. Fetch API – HTTP Examples

If we want to access data, we need two .then () handlers (callbacks). But if we want to manipulate the resource, we need only one .then () handler. However, we can use the second one to make sure the value has been sent.

Basic Fetch API template:

Note! The example above is for demonstration purposes only. The code will not work if you execute it.

Fetch API Examples

  • User mapping
  • User List Display
  • Create a new user
  • Delete user
  • User Update

Note! The resource will not be actually created on the server but will return a fake result to simulate a real server.

1. User mapping

As mentioned earlier, the process of mapping one user consists of two .then () handlers (callbacks), the first for identifying the object, and the second for accessing data.

Note that just by reading the / users / 2 query lines we can understand/predict what the API does.

Example

Users mapping

2. Display a list of users

The example is almost identical to the previous example, with the exception of the query string/users, not / users / 2.

Example

EcmaScript Fetch List of users

3. Create a new user

This is slightly different from the previous one. If you are not familiar with the HTTP protocol, it just gives us a couple of methods, such as POST, GET, DELETE, UPDATE, PATCH, and PUT in EcmaScript. 

These methods are verbs that simply describe the type of action that should be performed, and are mainly used to manage resources/data on the server.

In any case, in order to create a new user with the Fetch API, we will need to use the HTTP verb POST. But first, we need to define it somewhere. 

Fortunately, there is an optional Init argument that we can pass along with the URL to define custom parameters such as method type, body, credentials, headers, etc.

Note. The fetch () parameters of the method are identical to the Request () parameters of the constructor.

Example

EcmaScript Create JSON

4. Removing a user

To delete a user, you first need to target the user/users / 1, and then determine the type of method – DELETE.

Example

EcmaScript Delete

5. User update

The HTTP verb PUT is used to control the target resource, and if you want to make partial changes, you will need to use PATCH. For more information on what these HTTP verbs do, see this.

EcmaScript Fetch

Conclusion

You now have a basic understanding of how to retrieve or manage data from the server using the JavaScript APIs, and how to deal with promises. 

You can use this article as a guide to structuring your API requests for CRUD operations in EcmaScript.

Personally, I think the Fetch API is declarative, and you can easily understand what happens without any technical experience.

Comments
Loading...

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More