API Basics Lesoon Intro
How To Handle API data
Handling API Data
In this lesson you will learn how to get API data from public APIs that DONT need an API key.
- What Is Fetch?
- What Is Response?
- How To Use Response
- Using Simple User Input
Throught this lesson the code below will be referred to as a simple example to work with
https://api.dictionaryapi.dev/api/v2/entries/en/INSERT_WORD_HERE
%%html
<html>
<body>
<input type="text" id="search" placeholder="Search for a word">
<button onclick="FetchData()">Search</button><br>
<div id="result"></div>
<script>
async function FetchData() {
document.getElementById("result").innerHTML = "";
try {
const word = document.getElementById("search").value.toLowerCase();
if (!word) {
alert("Please enter a word to search.");
return;
}
if (word.includes(" ")) {
document.getElementById("result").innerHTML = "<p>Please enter a single word without spaces.</p>";
return;
}
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
if (response.status === 404) {
document.getElementById("result").innerHTML = "<p>Word not found.</p>";
throw new Error("word not found");
return;
}
if (response.status === 429) {
document.getElementById("result").innerHTML = "<p>Too many requests. Please try again later.</p>";
throw new Error("Too many requests. Please try again later.");
return;
}
if (response.status === 500) {
document.getElementById("result").innerHTML = "<p>Server error. Please try again later.</p>";
throw new Error("Server error. Please try again later.");
return;
}
if (!response.ok) {
console.log(response)
throw new Error("Network response was not ok");
}
const data = await response.json();
const meaning = data[0].meanings[0];
const input = document.getElementById("search");
const resultDiv = document.getElementById("result");
console.log(data)
console.log("Definition:", meaning.definitions[0].definition);
resultDiv.innerHTML = `
<h2>Word: ${data[0].word}</h2>
<p><strong>Definition:</strong> ${meaning.definitions[0].definition}</p>
<p><strong>Part of Speech:</strong> ${meaning.partOfSpeech}</p>
`;
}
catch (error) {
console.error("Fetch error:", error);
}
}
</script>
</body>
</html>