Chapter 13: API Integration Patterns
Chapter 13 of 14
Chapter 13: API Integration Patterns
13.1 Integration Strategies
Integrating with third-party APIs requires proper error handling, retries, and rate limiting.
// Third-party API integration
const axios = require('axios');
class ThirdPartyAPI {
constructor(apiKey) {
this.client = axios.create({
baseURL: 'https://api.thirdparty.com',
headers: { 'Authorization': `Bearer ${apiKey}` },
timeout: 5000
});
}
async getData(id, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await this.client.get(`/data/${id}`);
return response.data;
} catch (error) {
if (i === retries - 1) throw error;
await this.delay(1000 * (i + 1)); // Exponential backoff
}
}
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
13.2 Webhook Implementation
// Receiving webhooks
app.post('/webhooks/payment', async (req, res) => {
const signature = req.headers['x-signature'];
const isValid = verifySignature(req.body, signature);
if (!isValid) {
return res.status(401).send('Invalid signature');
}
// Process webhook
await processPaymentWebhook(req.body);
res.status(200).send('OK');
});
// Sending webhooks
async function sendWebhook(url, payload) {
try {
await axios.post(url, payload, {
headers: { 'Content-Type': 'application/json' },
timeout: 5000
});
} catch (error) {
// Retry logic
console.error('Webhook failed:', error);
}
}
13.3 API Gateway Pattern
// Aggregate multiple API calls
app.get('/api/user-dashboard/:userId', async (req, res) => {
const { userId } = req.params;
const [user, orders, notifications] = await Promise.all([
userService.getUser(userId),
orderService.getUserOrders(userId),
notificationService.getUserNotifications(userId)
]);
res.json({ user, orders, notifications });
});