
One of the most common tasks in web development is using JavaScript to fetch data from an API and display it on a web page. In this lesson, we’ll cover how to do this using the fetch() function provided by modern browsers.
Objective: Fetch data from a sample API and display it in a webpage.
Prerequisites:
- Basic understanding of HTML and JavaScript.
- A code editor and a web browser.
Step 1: Set up the HTML
First, let’s create a basic HTML structure. Save this as index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Lesson</title>
</head>
<body>
<h1>API Data Fetch Example</h1>
<button id="fetchButton">Fetch Data</button>
<div id="apiData"></div>
<script src="script.js"></script>
</body>
</html>
Step 2: JavaScript to Fetch Data
Create a file named script.js:
document.getElementById("fetchButton").addEventListener("click", fetchData);
function fetchData() {
// Define the API endpoint
const apiEndpoint = "https://jsonplaceholder.typicode.com/posts/1";
// Use the fetch function to get data from the API
fetch(apiEndpoint)
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => {
const apiDataDiv = document.getElementById("apiData");
apiDataDiv.innerHTML = `
<h2>${data.title}</h2>
<p>${data.body}</p>
`;
})
.catch(error => {
console.error("There was a problem with the fetch operation:", error.message);
});
}
Here, we’re fetching a sample post from jsonplaceholder, which is a free fake online REST API for testing.
Step 3: Running the code
- Open
index.htmlin a web browser. - Click on the “Fetch Data” button.
- You should see the title and body of the post from the API displayed below the button.
Key Concepts:
- fetch() function: Native browser function to make HTTP requests. It returns a promise.
- Promises: Represent a value which might be available now, or in the future, or never. They have methods like
then()andcatch()to handle success and error respectively. - json() method: Used to parse the response as JSON.
Further Study:
- Explore other HTTP methods like POST, PUT, DELETE using the fetch API.
- Look into error handling for better user experience.
- Learn about
asyncandawaitfor cleaner asynchronous code.
This lesson gives you a basic introduction to fetching data from an API using JavaScript. As you become more advanced, you can explore more complex tasks, such as sending data to APIs, handling different types of responses, and working with more advanced data structures.
Leave a comment