JAVASCRIPT
Fetch Data from an Authenticated API Endpoint
Learn how to make a basic GET request to an API endpoint using JavaScript's `fetch` API, including how to pass an API key in the Authorization header for authentication.
async function fetchData(url, apiKey) {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}` // Or 'x-api-key': apiKey
}
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(`HTTP error! Status: ${response.status}, Message: ${errorData.message || 'Unknown error'}`);
}
const data = await response.json();
console.log('Fetched data:', data);
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
// Example usage:
const API_URL = 'https://api.example.com/data';
const MY_API_KEY = 'your_secret_api_key'; // Replace with your actual API key
fetchData(API_URL, MY_API_KEY)
.then(data => {
// Process your data here
console.log('Successfully processed:', data);
})
.catch(error => {
console.error('Failed to process data:', error.message);
});
How it works: This snippet demonstrates how to make a GET request to an API using JavaScript's `fetch` API with `async/await`. It includes setting common headers like `Content-Type` and, importantly, an `Authorization` header for API key or token-based authentication. The `response.ok` check ensures proper handling of non-2xx HTTP status codes, and the `try...catch` block provides robust error management for network issues or API-specific errors returned in the response body.