JAVASCRIPT

Implementing Graceful API Degradation with Fallbacks

Learn to implement graceful degradation for API integrations by providing fallback data or a simplified UI when primary API calls fail, improving user experience.

const fallbackProducts = [
  { id: 1, name: 'Fallback Item A', price: 10.99, description: 'Limited description for A' },
  { id: 2, name: 'Fallback Item B', price: 20.50, description: 'Limited description for B' }
];

async function getProducts() {
  const API_URL = 'https://api.example.com/products';
  try {
    const response = await fetch(API_URL);
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log('Fetched products from API.');
    return data;
  } catch (error) {
    console.error('Failed to fetch products from API, using fallback data:', error);
    // Implement additional error logging/reporting here
    return fallbackProducts; // Return predefined fallback data
  }
}

async function renderProductList() {
  const products = await getProducts();
  const productListDiv = document.getElementById('product-list');
  if (!productListDiv) return;

  productListDiv.innerHTML = ''; // Clear previous content

  if (products === fallbackProducts) {
    const warningMessage = document.createElement('p');
    warningMessage.style.color = 'orange';
    warningMessage.textContent = 'Some features may be limited due to connectivity issues.';
    productListDiv.appendChild(warningMessage);
  }

  products.forEach(product => {
    const productElement = document.createElement('div');
    productElement.innerHTML = `
      <h3>${product.name}</h3>
      <p>Price: $${product.price}</p>
      <p>${product.description}</p>
    `;
    productListDiv.appendChild(productElement);
  });
}

// Example of initial load
document.addEventListener('DOMContentLoaded', renderProductList);

// Imagine an API endpoint that sometimes fails for demonstration:
// fetch('https://broken-api.example.com/products') could be used to test fallback
How it works: This snippet illustrates how to implement graceful degradation in API integrations. When a primary API call fails (due to network issues, server errors, etc.), instead of presenting a broken experience, the application falls back to a predefined set of static data (`fallbackProducts`). This ensures that the user still sees some content, albeit potentially limited or outdated, rather than a blank page or an error message. It improves robustness and user satisfaction, signaling that the application is aware of the issue and providing a degraded but functional experience.

Need help integrating this into your project?

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

Hire DigitalCodeLabs