NODEJS
Node.js Backend for Aggregating Multiple External APIs
Build a Node.js API gateway using Express to combine data from various external APIs into a single, unified endpoint, simplifying client-side calls and enhancing security.
const express = require('express');
const axios = require('axios'); // npm install axios
const app = express();
const PORT = 3000;
app.get('/api/aggregated-data', async (req, res) => {
try {
// Fetch data from multiple external APIs concurrently
const [usersResponse, postsResponse] = await Promise.all([
axios.get('https://jsonplaceholder.typicode.com/users/1'), // Example API 1
axios.get('https://jsonplaceholder.typicode.com/posts?userId=1') // Example API 2
]);
const aggregatedData = {
user: usersResponse.data,
posts: postsResponse.data
};
res.json(aggregatedData);
} catch (error) {
console.error('Error aggregating API data:', error.message);
res.status(500).json({ error: 'Failed to fetch and aggregate data' });
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
// To run this:
// 1. npm init -y
// 2. npm install express axios
// 3. Save as app.js and run: node app.js
// 4. Access via http://localhost:3000/api/aggregated-data
How it works: This Node.js Express snippet demonstrates how a backend can act as an API gateway to aggregate data from multiple external services. It makes concurrent requests to different APIs (using `axios` and `Promise.all`), combines their responses into a single JSON object, and sends it back to the client. This approach simplifies client-side logic, reduces the number of client requests, and can abstract away the complexity of integrating with various third-party services, providing a single, consistent endpoint.