JAVASCRIPT
Fetching Data from a REST API with JavaScript's Fetch API
Learn how to make a basic GET request to a REST API using the modern Fetch API in JavaScript, handle JSON responses, and catch potential errors effectively.
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error("There was a problem with the fetch operation:", error);
throw error;
}
}
// Example usage:
// fetchData('https://jsonplaceholder.typicode.com/todos/1')
// .then(data => console.log(data))
// .catch(error => console.error('Error fetching data:', error));
How it works: This asynchronous JavaScript function demonstrates how to use the built-in `fetch` API to retrieve data from a given URL. It checks for successful HTTP responses, parses the JSON body, and includes a `try-catch` block for robust error handling during network requests or parsing. This is a fundamental pattern for consuming REST APIs in web applications.