JAVASCRIPT
Managing API Versions with Request Headers or Path Parameters
Seamlessly integrate with different API versions by structuring requests with custom headers or path parameters, ensuring forward and backward compatibility.
class ApiClient {
constructor(baseUrl, defaultVersion = 'v1') {
this.baseUrl = baseUrl;
this.defaultVersion = defaultVersion;
}
// Method 1: Versioning via path parameter
async getByPath(resource, version = this.defaultVersion, options = {}) {
const url = `${this.baseUrl}/${version}/${resource}`;
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`API error (${version}): ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Error fetching ${resource} with version ${version} (path):`, error);
throw error;
}
}
// Method 2: Versioning via custom header
async getByHeader(resource, version = this.defaultVersion, options = {}) {
const url = `${this.baseUrl}/${resource}`; // No version in path
const headers = {
'X-API-Version': version, // Custom header for versioning
...options.headers
};
try {
const response = await fetch(url, { ...options, headers });
if (!response.ok) {
throw new Error(`API error (${version}): ${response.status} ${response.statusText}`);
}
return await response.json();
} catch (error) {
console.error(`Error fetching ${resource} with version ${version} (header):`, error);
throw error;
}
}
}
// Example usage:
// const apiClient = new ApiClient('https://api.example.com');
// // Fetch data using default version (v1) via path
// apiClient.getByPath('users/1')
// .then(data => console.log('User v1 (path):', data))
// .catch(error => console.error(error));
// // Fetch data using v2 via path
// apiClient.getByPath('products', 'v2')
// .then(data => console.log('Products v2 (path):', data))
// .catch(error => console.error(error));
// // Fetch data using default version (v1) via header
// apiClient.getByHeader('settings')
// .then(data => console.log('Settings v1 (header):', data))
// .catch(error => console.error(error));
// // Fetch data using v3 via header
// apiClient.getByHeader('orders', 'v3')
// .then(data => console.log('Orders v3 (header):', data))
// .catch(error => console.error(error));
How it works: This JavaScript class demonstrates two common strategies for managing API versions: via path parameters and custom request headers. It allows developers to specify which API version to target for requests, ensuring compatibility as APIs evolve. Using a client like this centralizes version control, making it easier to migrate between versions or support multiple versions simultaneously within an application.