Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Introduction to APIs for Data ยท Lesson 7 of 9

Module Six

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
7
Module 6 - Working with API Data Using JavaScript
MODULE 6 OF 8

Working with API Data Using JavaScript

Welcome to Module 6! In the previous modules, you learned what APIs are, how REST APIs work, and how applications communicate with servers.

Now it is time to do something exciting. You will learn how to collect information from an API and display it on a webpage using JavaScript.

Course progress: 6 out of 8 modules (75%)

What you will learn:
  • How JavaScript receives information from an API.
  • How to work with API responses.
  • How to display API data on a webpage.
  • How to use arrays and objects from API responses.
  • How to search and filter API data.
  • How to handle loading messages and errors.
  • How to build a simple application that uses API data.

1. What Does It Mean to Work with API Data?

Imagine that you are building a website for a secondary school in Ibadan.

The school wants students to view:

  • Available courses.
  • Teachers' names.
  • Student information.
  • Examination results.
  • School announcements.

The information is stored on a server. Your website needs to request the information and display it to visitors.

JavaScript can help you do this.

Simple example:

A student opens the school website and clicks "View Teachers". JavaScript sends a request to the API, receives the teachers' information, and displays their names on the screen.

2. Understanding API Responses

When an application sends a request to an API, the server sends back a response.

The response may contain information in JSON format.

For example, imagine an API returns this information about a student:

{
  "id": 1,
  "name": "Adebayo James",
  "class": "SS2",
  "school": "Bright Future College",
  "score": 85
}

This is JSON data.

It contains different pieces of information:

  • id: The student's identification number.
  • name: The student's name.
  • class: The student's class.
  • school: The student's school.
  • score: The student's examination score.

JavaScript can read these values and use them in a webpage.

3. Understanding JavaScript Objects

An object is a JavaScript structure used to store related information using names and values.

For example:

const student = {
    name: "Adebayo James",
    age: 15,
    class: "SS2"
};

console.log(student.name);
console.log(student.age);
console.log(student.class);

The output will be:

Adebayo James
15
SS2

Notice how we use a dot (.) to access a value inside an object.

Remember: An API response can contain objects. JavaScript allows you to access individual values inside those objects.

4. Understanding JavaScript Arrays

An array is used to store multiple values in one variable.

Imagine that a school wants to store the names of five students.

const students = [
    "Adebayo",
    "Chidinma",
    "Fatima",
    "Emeka",
    "Tunde"
];

console.log(students[0]);
console.log(students[1]);
console.log(students[2]);

The output will be:

Adebayo
Chidinma
Fatima

JavaScript arrays start counting from zero.

Position Student
0 Adebayo
1 Chidinma
2 Fatima
3 Emeka
4 Tunde

Many APIs return arrays when an application requests a list of records.

5. Receiving API Data with JavaScript Fetch

JavaScript provides a function called fetch() that can send requests to APIs.

Let's use JSONPlaceholder, a public testing API.

Our sample API address:

https://jsonplaceholder.typicode.com/users

This endpoint returns a list of sample users.

Our First API Request

fetch("https://jsonplaceholder.typicode.com/users")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log("Something went wrong:", error);
    });

Understanding the Code

  • fetch(): Sends a request to the API.
  • response: Contains the server's response.
  • response.json(): Reads the response body and converts JSON into JavaScript data.
  • data: Contains the information returned by the API.
  • catch(): Handles errors that occur during the request or processing.

6. Displaying API Data on a Webpage

Receiving information from an API is not enough. We often want to display that information on a webpage.

Let's build a simple webpage that displays sample user names.

Complete HTML and JavaScript Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>API User List</title>
</head>

<body>

    <h1>Sample Users</h1>

    <div id="users">Loading users...</div>

    <script>
    async function loadUsers() {

        const container = document.getElementById("users");

        try {
            const response = await fetch(
                "https://jsonplaceholder.typicode.com/users"
            );

            if (!response.ok) {
                throw new Error("Unable to load users");
            }

            const users = await response.json();

            container.innerHTML = "";

            users.forEach(user => {

                const paragraph = document.createElement("p");

                paragraph.textContent =
                    user.name + " - " + user.email;

                container.appendChild(paragraph);

            });

        } catch (error) {

            container.textContent = error.message;

        }
    }

    loadUsers();
    </script>

</body>
</html>

What Is Happening Here?

  1. The webpage creates a heading called Sample Users.
  2. A container is created to hold the information.
  3. JavaScript sends a request to the API.
  4. The API returns a list of users.
  5. JavaScript goes through the list one user at a time.
  6. The name and email address of each user are displayed.
Real-life connection: This is similar to how an online learning platform can request a list of available courses and display them to students.

7. Understanding forEach()

The forEach() method allows JavaScript to perform an action for every item in an array.

For example:

const courses = [
    "Cyber Security",
    "Data Analytics",
    "Web Development",
    "Digital Marketing"
];

courses.forEach(course => {
    console.log(course);
});

JavaScript will display every course name.

This is useful when an API returns many records.

8. Searching API Data with JavaScript

Imagine that CRMNuggets has 100 courses. A learner wants to find a course called Cyber Security.

Instead of reading all 100 course names, the learner can use a search box.

JavaScript can search through the information and display matching results.

Simple Search Example

const courses = [
    "Cyber Security",
    "Data Analytics",
    "Web Development",
    "Digital Marketing",
    "Artificial Intelligence"
];

const searchTerm = "cyber";

const results = courses.filter(course =>
    course.toLowerCase().includes(searchTerm.toLowerCase())
);

console.log(results);

The output will be:

["Cyber Security"]

Understanding filter()

The filter() method checks items in an array and returns only the items that match a condition.

In our example, JavaScript searches for course names containing the word "cyber".

Remember:
  • forEach() performs an action for every item.
  • filter() returns items that match a condition.
  • includes() checks whether text contains another piece of text.

9. Sorting API Data

Sometimes, information needs to be arranged in a particular order.

For example, a school may want to arrange examination scores from the highest to the lowest.

const scores = [65, 90, 45, 78, 88];

scores.sort((a, b) => b - a);

console.log(scores);

The result will be:

[90, 88, 78, 65, 45]

The sort() method helps arrange information.

The comparison function tells JavaScript how to order the numbers.

10. Handling Loading Messages

API requests may take some time. This can happen because of slow internet connections or a busy server.

Imagine that a student clicks "View Courses" and nothing appears for several seconds.

The student may think that the website is broken.

A loading message helps explain what is happening.

async function loadCourses() {

    const output = document.getElementById("courses");

    output.textContent = "Loading courses...";

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts"
        );

        if (!response.ok) {
            throw new Error("Could not load data");
        }

        const data = await response.json();

        output.textContent = "Courses loaded successfully!";

    } catch (error) {

        output.textContent = "Unable to load information.";

    }
}

The application displays a loading message before the information arrives.

11. Handling API Errors

Sometimes, an API request fails.

Possible reasons include:

  • The internet connection is unavailable.
  • The API server is not responding.
  • The endpoint is incorrect.
  • The application does not have permission to access the data.
  • The server returns an error response.

JavaScript allows us to handle these situations using try and catch.

async function getData() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/users"
        );

        if (!response.ok) {
            throw new Error("The API returned an error");
        }

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.log("Error:", error.message);

    }
}

getData();
Important: The fetch() function does not automatically treat HTTP error responses such as 404 or 500 as rejected promises. Checking response.ok helps you detect unsuccessful HTTP responses.

12. Practical Project: Build a Simple Course Explorer

You are going to build a small course explorer using JavaScript.

The application will:

  • Request sample information from an API.
  • Display the information on a webpage.
  • Allow users to search through the displayed records.

For this exercise, we will use sample posts from JSONPlaceholder as pretend course records. The API does not actually provide CRMNuggets courses.

Complete Project Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>Simple Course Explorer</title>

    <style>
        body {
            padding: 20px;
        }

        .container {
            max-width: 700px;
            margin: auto;
            padding: 20px;
            border-radius: 10px;
        }

        input {
            width: 100%;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .course {
            padding: 15px;
            margin-bottom: 12px;
            border-radius: 6px;
        }

        h1 {
            }
    </style>

</head>

<body>

<div class="container">

    <h1>Course Explorer</h1>

    <p>Search through the sample learning records.</p>

    <input
        type="text"
        id="search"
        placeholder="Search for a course..."
    >

    <div id="courses">Loading information...</div>

</div>

<script>

let allCourses = [];

async function loadCourses() {

    const container = document.getElementById("courses");

    container.textContent = "Loading information...";

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts"
        );

        if (!response.ok) {
            throw new Error("Unable to load information");
        }

        const data = await response.json();

        allCourses = data;

        displayCourses(allCourses);

    } catch (error) {

        container.textContent = error.message;

    }
}

function displayCourses(courses) {

    const container = document.getElementById("courses");

    container.innerHTML = "";

    if (courses.length === 0) {
        container.textContent = "No matching records found.";
        return;
    }

    courses.forEach(course => {

        const card = document.createElement("div");

        card.className = "course";

        const heading = document.createElement("h3");
        heading.textContent = course.title;

        const description = document.createElement("p");
        description.textContent = course.body;

        card.appendChild(heading);
        card.appendChild(description);

        container.appendChild(card);

    });
}

document.getElementById("search").addEventListener(
    "input",
    function() {

        const searchTerm = this.value.toLowerCase();

        const filteredCourses = allCourses.filter(course => {

            return course.title
                .toLowerCase()
                .includes(searchTerm);

        });

        displayCourses(filteredCourses);

    }
);

loadCourses();

</script>

</body>
</html>

How the Project Works

  1. The webpage opens and displays a loading message.
  2. JavaScript sends a request to JSONPlaceholder.
  3. The API returns sample records.
  4. The records are stored inside the allCourses variable.
  5. The displayCourses() function shows the records.
  6. When someone types in the search box, JavaScript filters the records.
  7. Only matching records are displayed.
Try this:

Save the project as course-explorer.html and open it in a modern web browser with an internet connection.

Search for words such as "qui", "est", or "autem" to see how the results change.

13. Important Security Lessons When Working with API Data

Working with API data also requires good security practices.

  • Do not expose secret API keys in public JavaScript files.
  • Do not assume that information from an API is always trustworthy.
  • Use textContent when displaying untrusted text.
  • Validate information before saving it to a database.
  • Use HTTPS when communicating with APIs.
  • Check that users have permission to access private information.
Security example:

Avoid placing untrusted API text directly into innerHTML. It can create security risks if the text contains harmful HTML or JavaScript. Use textContent for ordinary text whenever possible.

14. Module Summary

In this module, you learned:

  • How JavaScript communicates with APIs.
  • How to receive JSON data from an API.
  • How JavaScript objects and arrays work.
  • How to display API information on a webpage.
  • How to use forEach() to process lists.
  • How to use filter() to search information.
  • How to sort information using sort().
  • How to display loading messages.
  • How to handle API errors.
  • How to build a simple application using API data.

15. Knowledge Assessment

Choose the correct answer for each question.

Question 1:

Which JavaScript function is commonly used to request information from an API?




Question 2:

What is a JavaScript object used for?




Question 3:

Which JavaScript structure can store multiple values in one variable?




Question 4:

Which method converts a JSON response body into JavaScript data?




Question 5:

What does forEach() do?




Question 6:

Which JavaScript method can return items that match a condition?




Question 7:

Why should a webpage display a loading message?




Question 8:

What is the purpose of a catch block?




Question 9:

Which property is generally safer for displaying untrusted plain text in an HTML element?




Question 10:

What does filter() help a developer do?




16. Practical Assignment

Your assignment:

Build a simple student directory for a secondary school in Ibadan.

Your application should:

  1. Request sample user information from a public API.
  2. Display the names and email addresses of the users.
  3. Include a search box.
  4. Allow users to search for a particular name.
  5. Display a message when no matching record is found.
  6. Display an error message if the API request fails.

Save your work as student-directory.html.

Congratulations!

You have completed Module 6: Working with API Data Using JavaScript.

You can now request information from an API, process the response, display information on a webpage, and allow users to search through the data.

Coming Next: Module 7

API Security, Authentication and Data Protection โ€” learn how to protect API connections, manage access, and keep private information safe.

CRMNuggets

Learn. Practice. Get Certified.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’