How to Fetch API using JavaScript

2 views and you’re just in time for more!

Hey guys, welcome. In this tutorial, we will be learning how to fetch data from an API and using HTML5 and JavaScript. Now, before we get started, you need to know HTML5 & CSS3, and you should also know how to work with JavaScript.

If you don’t know any of those, you can learn them both from my courses:

Now, that the basics are out of the way, let’s get started of How to Fetch API using JavaScript.

How to Fetch API using JavaScript

Step 1: Set up Your Project

Before we start fetching data, ensure you have a basic HTML setup where you will run your JavaScript code.

HTML File (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch API Example</title>
</head>
<body>
    <h1>Users List</h1>
    <ul id="users-list"></ul>
    <script src="script.js"></script>
</body>
</html>

Step 2: Write JavaScript to Fetch API Data

Now, let’s create the JavaScript file (script.js) where we will fetch data using the fetch() API.

JavaScript File (script.js):

// Step 1: Define the API URL
const apiURL = 'https://jsonplaceholder.typicode.com/users';
// Step 2: Fetch data from the API
fetch(apiURL)
  .then(response => {
    // Step 3: Check if the response is successful
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // Step 4: Convert the response to JSON
    return response.json();
  })
  .then(data => {
    // Step 5: Process the fetched data
    displayUsers(data);
  })
  .catch(error => {
    // Step 6: Handle any errors
    console.error('There was a problem with the fetch operation:', error);
  });

// Step 7: Display the fetched data
function displayUsers(users) {
  const usersList = document.getElementById('users-list');
  // Step 8: Loop through the users and create a list item for each user
  users.forEach(user => {
    const listItem = document.createElement('li');
    listItem.textContent = `${user.name} - ${user.email}`;
    usersList.appendChild(listItem);
  });
}

Step-by-Step Explanation

Step 1: Define the API URL

We start by defining the URL of the API we want to fetch data from. In this case, the URL is:

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

Step 2: Fetch Data from the API

We use the fetch() method to make a GET request to the API:

fetch(apiURL)

fetch() returns a Promise that resolves to a Response object.

Step 3: Check If the Response Is Successful

In the .then() block, we check whether the response from the server was successful by examining the .ok property of the Response object:

if (!response.ok) {
    throw new Error('Network response was not ok');
}

If the response is not successful, we throw an error that will be caught in the .catch() block.

Step 4: Convert the Response to JSON

Once we confirm the response is successful, we convert it to JSON format using .json():

return response.json();

This also returns a Promise that resolves to the actual data.

Step 5: Process the Fetched Data

The fetched data (which is in JSON format) is passed into another .then() block where we call a function to display the users:

displayUsers(data);

Step 6: Handle Any Errors

In case of any errors during the fetch process (e.g., network failure), we handle them in the .catch() block:

.catch(error => {
    console.error('There was a problem with the fetch operation:', error);
});

Step 7: Display the Fetched Data

We create a function displayUsers() that takes the fetched data and appends it to an unordered list (<ul>) in the HTML file:

function displayUsers(users) {
    const usersList = document.getElementById('users-list');
    users.forEach(user => {
      const listItem = document.createElement('li');
      listItem.textContent = `${user.name} - ${user.email}`;
      usersList.appendChild(listItem);
    });
}

Here, we use the forEach() method to loop through the array of users returned by the API and create a list item (<li>) for each user, displaying their name and email.

Step 8: Test the Project

  1. Open the index.html file in your browser.
  2. You should see a list of users displayed, each showing the user’s name and email.

Disclaimer: This tutorial was generated with the assistance of ChatGPT, an AI language model.


Discover more from Prime Inspire

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from Prime Inspire

Subscribe now to keep reading and get access to the full archive.

Continue reading