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%)
Imagine that you are building a website for a secondary school in Ibadan.
The school wants students to view:
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.
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.
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:
JavaScript can read these values and use them in a webpage.
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.
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.
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.
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log("Something went wrong:", error);
});
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.
<!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>
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.
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.
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"]
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".
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.
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.
Sometimes, an API request fails.
Possible reasons include:
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();
You are going to build a small course explorer using JavaScript.
The application will:
For this exercise, we will use sample posts from JSONPlaceholder as pretend course records. The API does not actually provide CRMNuggets courses.
<!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>
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.
Working with API data also requires good security practices.
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.
In this module, you learned:
Choose the correct answer for each question.
Which JavaScript function is commonly used to request information from an API?
What is a JavaScript object used for?
Which JavaScript structure can store multiple values in one variable?
Which method converts a JSON response body into JavaScript data?
What does forEach() do?
Which JavaScript method can return items that match a condition?
Why should a webpage display a loading message?
What is the purpose of a catch block?
Which property is generally safer for displaying untrusted plain text in an HTML element?
What does filter() help a developer do?
Build a simple student directory for a secondary school in Ibadan.
Your application should:
Save your work as student-directory.html.
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.
API Security, Authentication and Data Protection โ learn how to protect API connections, manage access, and keep private information safe.
CRMNuggets
Learn. Practice. Get Certified.