How to use the JavaScript Fetch API to get data

0 Shares
0
0
0
0

Introduction

There was a time when XMLHttpRequest was used to make API requests. It didn't include Promises and didn't produce clean JavaScript code. With jQuery, you can use the cleaner jQuery.ajax() syntax.

Now, JavaScript has its own built-in way to make API requests. It's the Fetch API, a new standard for making server requests with Promises, but it includes additional features.

In this tutorial, you will create both GET and POST requests using the Fetch API.

Prerequisites
  • A local development environment for Node.js.
  • Basic understanding of coding in JavaScript.
  • Understanding Promises in JavaScript.

Step 1 – Getting Started with Fetch API Syntax

One way to use the Fetch API is to pass the fetch() API URL as a parameter:

fetch(url)

The fetch() method returns a Promise. After the fetch() method, insert the Promise method then():

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

If the returned Promise resolves, the function inside the then() method is executed. This function contains code to handle the data received from the API.

After the then() method, insert the catch() method:

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

The API you call using fetch() may be broken or some other error may occur. If this happens, the rejected promise is returned. The catch method is used to handle the rejection. If an error occurs while calling your API, the code inside catch() will be executed.

With an understanding of the syntax for using the Fetch API, you can now move on to using fetch() on an actual API.

Step 2 – Using Fetch to Get Data from an API

The following code sample will be based on JSONPlaceholder API. Using the API, you will get ten users and display them on the page using JavaScript. This tutorial will retrieve the data from JSONPlaceholder API and display it in the list items in the author list.

Start by creating an HTML file and adding a title and an unordered list with author IDs:

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

Add script tags to the bottom of your HTML file and use a DOM selector to get the ul. Use getElementById with the authors as an argument:

<h1>Authors</h1>
<ul id="authors"></ul>
<script>
const ul = document.getElementById('authors');
</script>

Remember, the authors created the previous ul id.

Then create a list that is a DocumentFragment:

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

All attached list items will be added to the list. A DocumentFragment is not part of the active document tree structure. This has the advantage that redrawing does not have a performance impact when the document object model changes.

Create a constant variable called url that holds the API URL that returns ten random users:

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

Now, using the Fetch API, call the JSONPlaceholder API using fetch() with the url as an argument:

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

You are calling the Fetch API and passing the URL to the JSONPlaceholder API. The response is then received. However, the response you receive is not JSON, but an object with a set of methods that can be used depending on what you want to do with the information. Use the json() method to convert the returned object to JSON.

Add a then() method that contains a function with a parameter called response:

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

The response parameter takes the object value returned from fetch(url). Use the json() method to convert the response to JSON data:

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

The JSON data still needs to be processed. Add another then() statement with a function that takes an argument called data:

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

In this function, create a variable called author that is set equal to the data:

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

For each author in authors, you want to create a list item that displays their name. The map() method is suitable for this pattern:

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

In your map function, create a variable called li that is set equal to createElement with li (the HTML element) as the argument. Also create an h2 for the name and a span for the email:

<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 h2 element will contain the author's name. The span element will contain the author's email. The innerHTML attribute and string interpolation allow you to do this:

<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>

Then, append these DOM elements with appendChild:

<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>

Note that each list item is added to the DocumentFragment list. Once the map is complete, the list is added to the ul unordered list element.

With both then() functions completed, you can now add the catch() function. This function will log any possible errors to the console:

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

This is the complete code for the request you created:

<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>

You have just successfully made a GET request using the JSONPlaceholder API and the Fetch API. Next, you will make POST requests.

Step 3 – Handling POST requests

Fetch defaults to GET requests, but you can use all other request types, change headers, and send data. Let's create a POST request.

First, include a constant variable that holds the link to the JSONPlaceholder API:

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

Next, you need to set up your object and pass it as the second argument to the fetch function. This will be an object called data with the key name Sammy (or your name) and the value:

// ... let data = { name: 'Sammy' }

Since this is a POST request, you need to make it explicit. Create an object called fetchData:

// ... let fetchData = { }

This object should contain three keys: method, body, and header:

// ... let fetchData = { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }) }

The method key will have the value “POST”. The body will be set to the JSON.stringify format of the newly created data object. The headers will have the value «Content-Type»: «application/json; charset=UTF-8′.

The Headers interface is a feature of the Fetch API that allows you to perform actions on HTTP request and response headers.

By placing this code, a POST request can be made using the Fetch API. You add the url, fetchData, and arguments to your fetch POST request:

// ... fetch(url, fetchData)

The then() function contains code that handles the response received from the JSONPlaceholder API:

// ... fetch(url, fetchData) .then(function() { // Handle response you get from the API });

This is the complete code for the request you created:

const url = 'https://jsonplaceholder.typicode.com/users'; let data = { name: 'Sammy' } let fetchData = { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }) } fetch(url, fetchData).then(function() { // Handle response you get from the API });

You can also pass fetch() to a Request object.

const url = 'https://jsonplaceholder.typicode.com/users'; let data = { name: 'Sammy' } let request = new Request(url, { method: 'POST', body: JSON.stringify(data), headers: new Headers({ 'Content-Type': 'application/json; charset=UTF-8' }) }); fetch(request) .then(function() { // Handle the response you get from the API });

With this approach, the request can be used as the only argument to fetch(), replacing url and fetchData.

You now know two ways to create and execute POST requests with the Fetch API.

Result

While the Fetch API is not yet supported by all browsers, it is a great alternative to XMLHttpRequest.

[Total: 2   Average: 5/5]
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like