JAVASCRIPT

Handling API Versioning with Custom Accept Headers

Discover how to explicitly request a specific API version using custom `Accept` headers, a common and flexible strategy for integrating with evolving external APIs.

async function fetchDataWithApiVersion(url, apiVersion, options = {}) {
  const headers = {
    'Content-Type': 'application/json',
    // Example: 'application/vnd.yourapi.v1+json'
    // 'application/vnd.mycompany.service.v2+json'
    'Accept': `application/vnd.yourapi.v${apiVersion}+json`,
    ...options.headers, // Allow overriding or adding other headers
  };

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

    if (!response.ok) {
      const errorBody = await response.text();
      throw new Error(`API Versioning Error! Status: ${response.status}, Body: ${errorBody}`);
    }

    return response.json();
  } catch (error) {
    console.error("Error fetching data with API version:", error);
    throw error;
  }
}

// Example Usage:
// const API_BASE = 'https://api.example.com';
// const AUTH_TOKEN = 'YOUR_AUTH_TOKEN';

// (async () => {
//   try {
//     // Fetch data using API version 1
//     const dataV1 = await fetchDataWithApiVersion(`${API_BASE}/resource`, 1, {
//       headers: { 'Authorization': `Bearer ${AUTH_TOKEN}` }
//     });
//     console.log('Data from API V1:', dataV1);

//     // Fetch data using API version 2 (if available)
//     const dataV2 = await fetchDataWithApiVersion(`${API_BASE}/resource`, 2, {
//       headers: { 'Authorization': `Bearer ${AUTH_TOKEN}` }
//     });
//     console.log('Data from API V2:', dataV2);

//   } catch (error) {
//     console.error('API call failed:', error.message);
//   }
// })();
How it works: This JavaScript snippet demonstrates a common method for handling API versioning using the `Accept` header. By sending a custom `Accept` header (e.g., `application/vnd.yourapi.v1+json`), the client can explicitly request a specific version of an API's resource representation. This approach allows API providers to introduce breaking changes while maintaining backward compatibility for older clients, making integrations more stable and manageable during API evolution.

Need help integrating this into your project?

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

Hire DigitalCodeLabs