NODEJS
Server-Side Aggregation of Multiple External APIs
Combine and aggregate data from various external APIs on your Node.js backend to create a unified endpoint, simplifying frontend consumption and reducing requests.
const express = require('express');
const fetch = require('node-fetch'); // For Node.js, install with `npm install node-fetch@2` for CommonJS or @3 for ES Modules
const app = express();
app.use(express.json());
// External API configurations
const API_CONFIGS = {
products: {
url: 'https://api.externalproducts.com/v1/products',
token: 'PRODUCT_API_KEY' // Replace with actual API key/token
},
reviews: {
url: 'https://api.externalreviews.com/v1/reviews',
token: 'REVIEW_API_KEY'
},
shipping: {
url: 'https://api.externalshipping.com/v1/shipping-costs',
token: 'SHIPPING_API_KEY'
}
};
/**
* Aggregates data from multiple external APIs for a single product ID.
* This endpoint fetches product details, reviews, and shipping costs concurrently.
*/
app.get('/api/product-details/:productId', async (req, res) => {
const productId = req.params.productId;
try {
// Make concurrent requests to external APIs
const [productRes, reviewsRes, shippingRes] = await Promise.all([
fetch(`${API_CONFIGS.products.url}/${productId}`, {
headers: { 'Authorization': `Bearer ${API_CONFIGS.products.token}` }
}),
fetch(`${API_CONFIGS.reviews.url}?productId=${productId}`, {
headers: { 'Authorization': `Bearer ${API_CONFIGS.reviews.token}` }
}),
fetch(`${API_CONFIGS.shipping.url}?region=US&productId=${productId}`, {
headers: { 'Authorization': `Bearer ${API_CONFIGS.shipping.token}` }
})
]);
// Check responses and parse JSON
if (!productRes.ok) throw new Error(`Product API error: ${productRes.statusText}`);
if (!reviewsRes.ok) throw new Error(`Reviews API error: ${reviewsRes.statusText}`);
if (!shippingRes.ok) throw new Error(`Shipping API error: ${shippingRes.statusText}`);
const productData = await productRes.json();
const reviewsData = await reviewsRes.json();
const shippingData = await shippingRes.json();
// Aggregate the data into a single response object
const aggregatedData = {
product: productData,
reviews: reviewsData.results || [], // Assuming reviews API returns { results: [...] }
shipping: shippingData.cost || null, // Assuming shipping API returns { cost: X }
lastUpdated: new Date().toISOString()
};
res.json(aggregatedData);
} catch (error) {
console.error('Error during API aggregation:', error.message);
res.status(500).json({ error: 'Failed to aggregate data from external services.', details: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Aggregation service running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates a server-side API aggregation pattern. It defines an endpoint (`/api/product-details/:productId`) that, when called, concurrently fetches data from multiple distinct external APIs (e.g., product details, reviews, shipping costs). By using `Promise.all`, it executes these requests in parallel, significantly reducing the overall response time compared to sequential calls. The fetched data is then combined and transformed into a single, unified JSON response, simplifying frontend development by providing all necessary information from one optimized endpoint, while also abstracting external API complexities.