JAVASCRIPT
Basic Data Fetching from a REST API with JavaScript Fetch
Learn to fetch JSON data from a REST API using the JavaScript Fetch API, including basic error handling for network issues and server responses.
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();
console.log('Fetched data:', data);
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
// Example usage:
fetchData('https://jsonplaceholder.typicode.com/posts/1')
.then(data => console.log('Data processed:', data))
.catch(err => console.error('Failed to process data:', err));
How it works: This snippet demonstrates how to perform a GET request to a REST API using the native JavaScript `fetch` API. It includes an `async/await` structure for cleaner asynchronous code and basic error handling to catch network errors and non-2xx HTTP responses, ensuring your application can gracefully manage API communication issues.