How to Use the JavaScript Fetch API to Get Data

Spread the love

There was a time when JavaScript Fetch API I requests were made using XMLHttpRequest. It lacked Promises and resulted in unclean JavaScript code. You could use the cleaner syntax of jQuery instead. ajax().

JavaScript now has its built-in method for making api requests. This is the Fetch api, a new standard for making server requests using Promises that includes extra features.

Fetch api to create GET and POST requests.

This task aims to demonstrate how to use the Fetch api to retrieve data from an api. For example, I will use a fictitious api containing employee information. I’ll demonstrate how to get data using the Fetch () api method.

The Fetch () method in JavaScript is modern and versatile, and modern browsers widely support it. It can send network requests to the server and load new information without reloading the browser.

The Fetch () method takes only one mandatory argument, which is the URL of the resource to be retrieved.

([response = fetch(api url, [other parameters])

Awaiting JavaScript Async: In this example, we will use the Async Await method in conjunction with the To make promises more concisely, use the Fetch () method. All modern browsers support async functions.

Prerequisites

You will need the following items to complete this tutorial:

  • A Node js local development environment. Follow How to Install Node.js and Create a Local Development Environment.
  • You have a fundamental understanding of JavaScript coding, which you can learn more about by visiting the How to In the JavaScript series and writing code.
  • An understanding of JavaScript Promises. Read the Promises section of this article on JavaScript’s event loop, callbacks, Promises, and async/await.

Step 1: Understanding Fetch api syntax

One method for using the Fetch api is to pass the URL of the api as a parameter to

fetch(url)

A Promise is return by the fetch() method. Include the Promise method then() after the fetch() method:

fetch(url) .then(function(){ // handle the response })

If the Promise returned is resolved, the then() method’s function is executed. This function contains the code for dealing with the api data.

Include the catch() method after the then() method:

fetch(url)
  .then(function() {
    // handle the response
  })
.catch(function() {    // handle the error
  });

The api you call with Fetch () may be unavailable, or other errors may occur. So, if this occurs, the reject promise is return. To handle rejection, the catch method is use. If an error occurs while calling the api of your choice, the code within the catch() will be execute.

You can now use Fetch () on a real api after you’ve mastered the syntax for using the Fetch api.

Step 2 — Obtaining Data from an api using Fetch


The JSONPlaceholder api will be use in the following code samples. So, you will get ten users from the api and use JavaScript to show them on the page. This tutorial will pull information from the JSONPlaceholder api and show it in the form of list items within the framework of the author’s list.

Begin by creating an HTML file and inserting a heading and an unordered list with the authors’ ids:

Authors.html

<h1>Authors</h1>

<u1 id=”authors”></u1>

And show them on the document using JavaScript. This tutorial pulls data from the JSONPlaceholder api and displays it.

Authors.html

<h1>Authors</h1> <u1 id=”authors”></u1>

<script> conset u1 = document.getElement Byld ( ‘authors’ ); </script>

Remember that the author is the id for the previously create ul.

Create a list that is a Document Fragment next:

Authors.html

<script>
  // ...
   
  const list = document.createDocumentFragment();
</script>

All attached list items will be included in the list. Then the active document tree structure does not include a DocumentFragment. When the Document Object Model is changed, this prevents performance-impacting redraws.

Create a constant variable called url that will hold the JavaScript Fetch API URL for returning ten random users:

Authors.html

<script>
  // ...

  const url = 'https://jsonplaceholder.typicode.com/users';
</script>

Now, using Fetch api, use Fetch () with the reasoning url to call the JSONPlaceholder api:

Authors.html

<script> // … fetch(url) </script>

You’re using the JavaScript Fetch API. You could use the cleaner syntax to get the URL for the JSONPlaceholder API. Then there is a response. However, the response is an object with a series of methods that can be used depending on what you want to do with the information rather than JSON. Use the JSON () method to convert the returned object to JSON.

Add the then() method, which will contain a function with a response parameter:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {})
</script>

The cost of the component is the object return from fetch (url). To convert the answer into JSON data, use the JSON() process:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
</script>

The JSON data must still be process. Add another then() statement with a function with a data argument:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {})
</script>

Create a variable called authors within this function and set it to data:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;
    })
</script>

Then Create a list item that displays the author’s name for each author in authors. However this pattern is well-suited to the map() method:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;
  
      authors.map(function(author) {
  
      });
    })
</script>

Within your map function, because create a thing called li that will be set equal to createElement with li (the HTML element) as the argument. Then create an h2 for the name and a span for the email:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');
      });
    })
</script>

The author’s name will appear in the h2 element. The author’s email address will be display in the span element. Then this is possible thanks to the inner HTML property and string interpolation:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');

        name.innerHTML = ${author.name}`;        email.innerHTML = ${author. Email}`;      });
    })
</script>

Next, use appendChild to relate these DOM elements:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');

        name.innerHTML = `${author.name}`;
        email.innerHTML = `${author.email}`;
       
        li.appendChild(name);
        li.appendChild(email);
        list.appendChild(li);

      });
    })

  ul.appendChild(list);
</script>

It should be noted that each list item is append to the DocumentFragment list. Once the map is finish, the list is appended to the ul unordered list element.

Because after you’ve finished both the () functions, you can add the catch() function. This function will print the following error message to the console:

Authors.html

<script>
  // ...

  fetch(url)
    .then((response) => {
      // ...
    })
    .then((data) => {
      // ...
    })
    .catch(function(error) {
      console.log(error);
     });
  
  // ...
</script>

This is the complete code for the request you create:

Authors.html

<h1>Authors</h1>
<ul id="authors"></ul>

<script>
  const ul = document.getElementById('authors');
  const list = document.createDocumentFragment();
  const url = 'https://jsonplaceholder.typicode.com/users';

  fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      let authors = data;

      authors.map(function(author) {
        let li = document.createElement('li');
        let name = document.createElement('h2');
        let email = document.createElement('span');

        name.innerHTML = `${author.name}`;
        email.innerHTML = `${author.email}`;

        li.appendChild(name);
        li.appendChild(email);
        list.appendChild(li);
      });
    }).
    .catch(function(error) {
      console.log(error);
    });

  ul.appendChild(list);
</script>

Then you just completed a GET request with the JSONPlaceholder api and the Fetch api.

Conclusion

While not all browsers support the Fetch api, it is a great alternative to XMLHttpRequest. So, if you like to know how to utilize React to call Web apis, you should read this article.

31 thoughts on “How to Use the JavaScript Fetch API to Get Data”

Leave a Comment