JAVASCRIPT

Implement API Key Authentication in Fetch Requests

Securely integrate third-party APIs by adding API keys to request headers using JavaScript's Fetch API, ensuring authorized data access and protecting your application.

async function callAuthenticatedApi(endpoint, apiKey) {
  try {
    const response = await fetch(endpoint, {
      method: 'GET', // Or 'POST', 'PUT', etc.
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}` // Common for API keys or JWTs
        // Or 'X-API-KEY': apiKey for some APIs
      },
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API Error: ${response.status} - ${errorData.message || 'Unknown error'}`);
    }

    const data = await response.json();
    console.log('Authenticated API Response:', data);
    return data;
  } catch (error) {
    console.error('Failed to call authenticated API:', error.message);
    throw error;
  }
}

// Usage example:
// const myApiKey = 'YOUR_SECRET_API_KEY';
// callAuthenticatedApi('https://api.example.com/data', myApiKey)
//   .then(data => console.log('Data fetched:', data))
//   .catch(err => console.error('Error in usage:', err.message));
How it works: This snippet demonstrates how to include an API key in the headers of a Fetch API request. The `Authorization` header with a 'Bearer' token prefix is a common pattern for API keys or JWTs, though some APIs might use a custom header like `X-API-KEY`. Proper error handling is also included to manage network issues and API-specific error responses, ensuring robust integration.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs