NODEJS
Batching Multiple REST API Requests in a Single Call (Backend Proxy)
Optimize client-server communication by consolidating multiple independent REST API calls into a single batched request using a simple Node.js proxy server.
// server.js (using Express)
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;
app.use(express.json()); // Middleware to parse JSON bodies
// Example client-side request structure for batching
/*
[
{ "method": "GET", "path": "/users/1" },
{ "method": "GET", "path": "/products?limit=5" },
{ "method": "POST", "path": "/analytics", "body": { "event": "page_view", "page": "/dashboard" } }
]
*/
app.post('/batch', async (req, res) => {
const requests = req.body; // Array of request objects from client
if (!Array.isArray(requests) || requests.length === 0) {
return res.status(400).json({ error: 'Request body must be an array of API requests.' });
}
const results = await Promise.all(
requests.map(async (request) => {
const { method, path, body } = request;
const targetUrl = `https://api.example.com${path}`; // Replace with your actual target API base URL
try {
const apiResponse = await axios({
method: method || 'GET',
url: targetUrl,
data: body, // For POST/PUT requests
headers: {
// Add any necessary headers for your target API (e.g., Authorization)
// 'Authorization': `Bearer ${process.env.API_KEY}`
}
});
return { status: apiResponse.status, data: apiResponse.data, success: true };
} catch (error) {
// console.error(`Error processing batched request to ${targetUrl}:`, error.message);
return {
status: error.response ? error.response.status : 500,
data: error.response ? error.response.data : { message: 'Internal proxy error' },
success: false,
request: { method, path } // Include original request for context
};
}
})
);
res.json(results);
});
app.listen(PORT, () => {
console.log(`Batch API proxy listening on http://localhost:${PORT}`);
});
// Client-side usage example (e.g., with Axios)
/*
// const clientRequests = [
// { method: 'GET', path: '/users/1' },
// { method: 'GET', path: '/products?limit=2' }
// ];
//
// axios.post('http://localhost:3000/batch', clientRequests)
// .then(response => {
// console.log('Batch results:', response.data);
// // response.data will be an array like:
// // [
// // { status: 200, data: { ...user1 }, success: true },
// // { status: 200, data: [ ...products ], success: true }
// // ]
// })
// .catch(error => console.error('Batch request failed:', error));
*/
How it works: This Node.js snippet provides a backend proxy endpoint (`/batch`) that allows a client to send multiple independent API requests in a single HTTP call. The proxy receives an array of request definitions (method, path, body), executes each one against the actual target API (e.g., `api.example.com`), and then aggregates all the individual responses into a single JSON array returned to the client. This pattern reduces network overhead, especially for clients that need to fetch data from several endpoints to render a single view, mimicking some benefits of GraphQL for traditional REST APIs.