0
0
Rest APIprogramming~5 mins

Graceful degradation in Rest API

Choose your learning style9 modes available
Introduction

Graceful degradation helps your API keep working even if some parts fail. It avoids total crashes and gives users useful responses.

When a part of your API depends on an external service that might be slow or down.
When you want to provide partial data instead of failing completely.
When you want to show a simple message if a feature is temporarily unavailable.
When you want to keep your API responsive during high traffic or errors.
When you want to improve user experience by handling errors smoothly.
Syntax
Rest API
try {
  // call external service or risky code
  return full response;
} catch (error) {
  // fallback response or partial data
  return degraded response;
}
Use try-catch or error handling to detect failures.
Return simpler or partial data instead of full failure.
Examples
This example tries to get data from an external API. If it fails, it returns a simple message instead of an error.
Rest API
try {
  const data = await fetchExternalAPI();
  return { status: 200, data };
} catch {
  return { status: 200, data: { message: 'Partial data available' } };
}
If fetching orders fails, the API still returns user info with an empty orders list.
Rest API
try {
  const user = await getUserFromDB();
  const orders = await getOrdersFromDB();
  return { user, orders };
} catch {
  return { user: null, orders: [] };
}
Sample Program

This simple REST API tries to get data from a service. If the service fails, it returns partial data instead of an error. This keeps the API working smoothly.

Rest API
import express from 'express';
const app = express();

// Simulate external service call
async function fetchExternalService() {
  if (Math.random() < 0.5) {
    throw new Error('Service down');
  }
  return { info: 'Full data from service' };
}

app.get('/data', async (req, res) => {
  try {
    const data = await fetchExternalService();
    res.status(200).json({ success: true, data });
  } catch (error) {
    // Graceful degradation: return partial data
    res.status(200).json({ success: true, data: { info: 'Partial data due to service issue' } });
  }
});

app.listen(3000, () => console.log('API running on http://localhost:3000'));
OutputSuccess
Important Notes

Always return a success status if you provide useful fallback data.

Log errors internally to fix issues later, but don't expose them to users.

Test your graceful degradation by simulating failures.

Summary

Graceful degradation keeps your API working even when parts fail.

It returns simpler or partial data instead of errors.

This improves user experience and reliability.