JAVASCRIPT
Fetching Data from a REST API with Async/Await
Learn to fetch data from a REST API using modern JavaScript async/await syntax and the built-in Fetch API for robust web applications.
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("Error fetching data:", error);
throw error; // Re-throw to allow caller to handle
}
}
// Example usage:
// fetchData('https://api.example.com/posts/1')
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch:', error));
How it works: This JavaScript snippet demonstrates how to perform an asynchronous GET request to a REST API using the native Fetch API combined with async/await syntax. The `fetchData` function takes a URL, awaits the response, checks for HTTP errors, and then parses the response body as JSON. It includes robust error handling using a `try...catch` block, making it a reliable pattern for fetching data in modern web applications.