JAVASCRIPT
Fetching Data from an API with GET Request (Async/Await)
Learn how to asynchronously fetch data from a REST API using JavaScript's modern `fetch` API with `async/await` for clean, readable code and basic error handling.
async function fetchDataFromAPI(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);
return null;
}
}
// Usage example:
// fetchDataFromAPI('https://api.example.com/data')
// .then(data => {
// if (data) {
// // Process your data here
// console.log('Data processed:', data);
// }
// });
How it works: This snippet demonstrates how to perform a GET request using the `fetch` API with `async/await` for cleaner asynchronous code. It includes basic error handling for network issues and non-OK HTTP responses, parses the JSON response, and logs the fetched data to the console, making it a foundational pattern for API integration.