Reading API Data with JavaScript
In the previous tutorial, you created a simple API using PHP.
The API returns JSON data when visited in a browser.
In this tutorial, you will use JavaScript to read data from the API and display it on a webpage.
Project Structure
Your project should contain:
api-demo
├── api.php
├── index.html
└── smart_security_data.json
Create the HTML Page
Create:
index.html
Add:
<!DOCTYPE html>
<html>
<head>
<title>API Demo</title>
</head>
<body>
<h1>API Dashboard</h1>
<div id="output"></div>
<script>
</script>
</body>
</html>
Save the file.
Read the API
Inside the <script> tags add:
fetch("api.php")
.then(response => response.json())
.then(data => {
console.log(data);
});
Save the file.
Test the API Request
Open:
http://localhost/api-demo/
Press:
F12
Open the Console tab.
You should see the JSON object displayed.
Display the Home Information
Replace:
console.log(data);
with:
document.getElementById(
"output"
).innerHTML = `
<p>
<strong>Home ID:</strong>
${data.homeId}
</p>
<p>
<strong>Location:</strong>
${data.location}
</p>
`;
Refresh the page.
You should see:
Home ID: GC-HOME-014
Location: Gold Coast
Display Device Information
Replace the existing code with:
let html = `
<h2>Devices</h2>
<table border="1">
<tr>
<th>Device ID</th>
<th>Device Type</th>
<th>Room</th>
</tr>
`;
data.devices.forEach(device => {
html += `
<tr>
<td>${device.deviceId}</td>
<td>${device.deviceType}</td>
<td>${device.room}</td>
</tr>
`;
});
html += "</table>";
document.getElementById(
"output"
).innerHTML = html;
Refresh the page.
You should now see a table of devices.
Why Use an API?
Previously, the data was loaded directly from:
fetch("smart_security_data.json")
Now the data is loaded from:
fetch("api.php")
This means the data can be:
- Generated dynamically
- Stored in a database
- Updated automatically
- Filtered before being sent
The webpage does not need to know where the data comes from. It only needs the JSON returned by the API.
Complete Page
<!DOCTYPE html>
<html>
<head>
<title>API Demo</title>
</head>
<body>
<h1>API Dashboard</h1>
<div id="output"></div>
<script>
fetch("api.php")
.then(response => response.json())
.then(data => {
let html = `
<h2>Devices</h2>
<table border="1">
<tr>
<th>Device ID</th>
<th>Device Type</th>
<th>Room</th>
</tr>
`;
data.devices.forEach(device => {
html += `
<tr>
<td>${device.deviceId}</td>
<td>${device.deviceType}</td>
<td>${device.room}</td>
</tr>
`;
});
html += "</table>";
document.getElementById(
"output"
).innerHTML = html;
});
</script>
</body>
</html>
You have successfully consumed data from an API using JavaScript.
Next tutorial: Creating a Database-Driven API with PHP and MySQL.