JAVASCRIPT
Authenticating API Requests with an API Key
Learn to securely send an API key with your HTTP requests, typically in the `Authorization` header or as a query parameter, for authenticating web service calls.
const API_BASE_URL = 'https://api.example.com'; // Replace with your API base URL
const API_KEY = 'YOUR_SECRET_API_KEY'; // IMPORTANT: For client-side, consider environmental variables or server-side proxy
// Method 1: API Key in Request Header (most common and recommended)
async function fetchDataWithApiKeyHeader(endpoint, options = {}) {
const headers = {
'Content-Type': 'application/json',
'Authorization': `ApiKey ${API_KEY}`, // Or `X-API-Key`, depends on API
...options.headers
};
const response = await fetch(`${API_BASE_URL}/${endpoint}`, { ...options, headers });
if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
// Method 2: API Key as a Query Parameter (less secure, but sometimes required)
async function fetchDataWithApiKeyQuery(endpoint, options = {}) {
const url = new URL(`${API_BASE_URL}/${endpoint}`);
url.searchParams.append('apiKey', API_KEY); // 'apiKey' can vary
// Merge existing query parameters from options.params if needed
if (options.params) {
Object.keys(options.params).forEach(key => url.searchParams.append(key, options.params[key]));
}
const response = await fetch(url.toString(), options);
if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
return await response.json();
}
// Usage Example:
/*
(async () => {
try {
// Replace with actual API endpoint that uses API Key auth
// For demonstration, using a placeholder endpoint
// const headerAuthData = await fetchDataWithApiKeyHeader('secure-data');
// console.log('Data with header API key:', headerAuthData);
// const queryAuthData = await fetchDataWithApiKeyQuery('public-data', { params: { user_id: 123 } });
// console.log('Data with query API key:', queryAuthData);
console.log("To run, replace API_BASE_URL and API_KEY, and uncomment usage examples.");
} catch (err) {
console.error('API Key auth failed:', err.message);
}
})();
*/
How it works: This snippet illustrates two common methods for authenticating API requests using an API key in JavaScript. The first and generally more secure method involves including the API key in a custom HTTP header, such as `Authorization` or `X-API-Key`. The second method appends the API key as a query parameter to the URL. While the query parameter method is simpler, it's less secure as the key might be logged or exposed in URLs. Developers should always strive to use header authentication and consider environment variables or a server-side proxy to protect sensitive API keys, especially in client-side applications.