How to Fetch Data from an API in Simple JavaScript
APIs play a crucial role in modern web development, allowing applications to communicate and exchange data. Whether you're building a weather app, a search engine, or an e-commerce site, you’ll likely use APIs. In this tutorial, we’ll walk through how to fetch data from an API using simple JavaScript, step by step.
To make things practical, we’ll use an example API that provides information about cats. You’ll learn how to fetch the data, display it, and even use query parameters to customize the results.
Step 1: The Basics of Fetching Data
In JavaScript, the fetch
function is the simplest way to interact with an API. It sends a request to the API and returns a promise containing the response. Let’s start with a basic example to fetch all cat data.
Here’s the endpoint we’ll use:
GET http://localhost:3000/api/v1/cats
fetch('http://localhost:3000/api/v1/cats')
.then((response) => response.json()) // Parse the JSON from the response
.then((data) => console.log(data)) // Log the data to the console
.catch((error) => console.error('Error fetching data:', error));
When you run this code, you’ll see an array of cat objects in the console, each containing properties like id, name, origin, temperament, colors, and more.
Step 2: Displaying the Data on a Web Page
Let’s make it more interactive by displaying the fetched data in a simple web page. We’ll create an HTML structure and dynamically populate it using JavaScript.
Here’s the complete example:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cat List</title>
</head>
<body>
<h1>Cat List</h1>
<ul id="cat-list"></ul>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js)
const catList = document.getElementById('cat-list');
fetch('http://localhost:3000/api/v1/cats')
.then((response) => response.json())
.then((data) => {
data.forEach((cat) => {
const listItem = document.createElement('li');
listItem.textContent = `${cat.name} - ${cat.origin}`;
catList.appendChild(listItem);
});
})
.catch((error) => console.error('Error fetching data:', error));
When you open this page in your browser, you’ll see a list of cats with their names and origins.
Step 3: Using Query Parameters
Limiting Results
What if you only want to fetch a limited number of cats? You can use the ?limit query parameter. Here’s how:
fetch('http://localhost:3000/api/v1/cats?limit=5')
.then((response) => response.json())
.then((data) => console.log('Limited results:', data))
.catch((error) => console.error('Error:', error));
This will fetch only 5 cat objects.
Searching for Cats
To filter the results based on a search query, use the ?search parameter. For example, to find cats with “British” in their name or description:
fetch('http://localhost:3000/api/v1/cats?sort=name&order=desc')
.then((response) => response.json())
.then((data) => console.log('Sorted results:', data))
.catch((error) => console.error('Error:', error));
Posted on 11/26/2024