JAVASCRIPT

Authenticated API Requests with API Key Header in JavaScript

Shows how to securely include an API key in the HTTP Authorization header when making requests to external APIs using the modern Fetch API in JavaScript.

async function makeAuthenticatedApiRequest(url, apiKey, method = 'GET', data = null) {
  const headers = {
    // Use 'x-api-key' or 'Authorization: Bearer <API_KEY>' as per API documentation
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json' 
  };

  const options = {
    method: method,
    headers: headers,
  };

  if (data) {
    options.body = JSON.stringify(data);
  }

  try {
    const response = await fetch(url, options);

    if (!response.ok) {
      // Handle HTTP errors
      const errorData = await response.json().catch(() => ({ message: response.statusText }));
      throw new Error(`API Error: ${response.status} - ${errorData.message}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Failed to make authenticated API request:', error);
    throw error; // Re-throw to allow caller to handle
  }
}

// Example Usage (in a client-side environment or Node.js with a fetch polyfill):
// const API_ENDPOINT = 'https://api.example.com/v1/profile';
// const YOUR_API_KEY = 'your_secret_api_key'; // In client-side, consider proxying to hide key

// Fetch user profile
// makeAuthenticatedApiRequest(API_ENDPOINT, YOUR_API_KEY)
//   .then(profile => console.log('User Profile:', profile))
//   .catch(error => console.error('Error fetching profile:', error));

// // Create a new resource
// const newPost = { title: 'New Post', content: 'Hello API!' };
// makeAuthenticatedApiRequest('https://api.example.com/v1/posts', YOUR_API_KEY, 'POST', newPost)
//   .then(response => console.log('New Post Created:', response))
//   .catch(error => console.error('Error creating post:', error));
How it works: This JavaScript snippet demonstrates how to make authenticated API requests using the modern Fetch API. The `makeAuthenticatedApiRequest` function takes a URL, API key, HTTP method, and optional data. It constructs the request headers, including the API key in the `Authorization` header as a 'Bearer' token (a common practice, though some APIs might use `x-api-key`). It handles JSON serialization for POST/PUT requests and includes basic error handling for network issues or non-successful HTTP responses, parsing error details if available.

Need help integrating this into your project?

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

Hire DigitalCodeLabs