JAVASCRIPT

Managing Dynamic API Versioning in a JavaScript Client

Discover how to dynamically manage and switch between different API versions within your JavaScript client application, ensuring compatibility and smooth transitions.

class ApiClient {
  constructor(baseUrl, defaultVersion = 'v1') {
    this.baseUrl = baseUrl;
    this.version = defaultVersion;
  }

  setVersion(newVersion) {
    if (!newVersion || typeof newVersion !== 'string') {
      console.error("Invalid API version provided. Keeping current version.");
      return;
    }
    this.version = newVersion;
    console.log(`API client version set to: ${this.version}`);
  }

  getEndpoint(path) {
    // Example: https://api.example.com/v1/users
    // Example: https://api.example.com/v2/products
    return `${this.baseUrl}/${this.version}/${path.startsWith('/') ? path.substring(1) : path}`;
  }

  async fetchData(path, options = {}) {
    const url = this.getEndpoint(path);
    try {
      const response = await fetch(url, options);
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error(`Failed to fetch from ${url}:`, error);
      throw error;
    }
  }
}

// Usage example:
// const client = new ApiClient('https://api.example.com');

// // Fetch data using default v1
// client.fetchData('users')
//   .then(data => console.log('Users (v1):', data))
//   .catch(err => console.error(err));

// // Switch to v2
// client.setVersion('v2');
// client.fetchData('products/123')
//   .then(data => console.log('Product (v2):', data))
//   .catch(err => console.error(err));

// // Trying to fetch with an invalid version
// client.setVersion(null);
// client.fetchData('orders')
//   .then(data => console.log('Orders (still v2):', data))
//   .catch(err => console.error(err));
How it works: This JavaScript `ApiClient` class provides a structured way to manage API versioning in client-side applications. It initializes with a base URL and a default API version. Developers can dynamically change the API version using the `setVersion` method. The `getEndpoint` method then constructs the full API URL by incorporating the currently set version, ensuring that all subsequent API calls target the correct version of the backend. This pattern helps maintain compatibility as APIs evolve and simplifies the management of multiple API versions within a single client application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs