Connecting Multiple Services Together
How to connect multiple services together to orchestrate calls across systems with AI
Summary
Example: Making and integrating multiple API callouts using generative AI
Prompt
Demonstrate how to connect multiple services, such as a weather API and a payment gateway, in a Node.js application. Show the project structure using controllers and provide examples of API call outs.Response
// Project Structure:
- src
- controllers
- weatherController.js
- paymentController.js
- services
- weatherService.js
- paymentService.js
- app.js
- index.js
// weatherService.js
const axios = require('axios');
const fetchWeather = async (location) => {
const apiKey = process.env.WEATHER_API_KEY;
const response = await axios.get(`https://api.weather.example.com/data?location=${location}&apiKey=${apiKey}`);
return response.data;
};
module.exports = {
fetchWeather,
};
// paymentService.js
const axios = require('axios');
const processPayment = async (paymentDetails) => {
const apiKey = process.env.PAYMENT_API_KEY;
const response = await axios.post('https://api.payment.example.com/charge', paymentDetails, {
headers: { Authorization: `Bearer ${apiKey}` },
});
return response.data;
};
module.exports = {
processPayment,
};
// weatherController.js
const weatherService = require('../services/weatherService');
const getWeather = async (req, res) => {
const location = req.query.location;
try {
const weatherData = await weatherService.fetchWeather(location);
res.json(weatherData);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
module.exports = {
getWeather,
};
// paymentController.js
const paymentService = require('../services/paymentService');
const processPayment = async (req, res) => {
const paymentDetails = req.body;
try {
const paymentResult = await paymentService.processPayment(paymentDetails);
res.json(paymentResult);
} catch (error) {
res.status(500).json({ error: error.message });
}
};
module.exports = {
processPayment,
};
// app.js
const express = require('express');
const weatherController = require('./controllers/weatherController');
const paymentController = require('./controllers/paymentController');
const app = express();
app.use(express.json());
app.get('/weather', weatherController.getWeather);
app.post('/payment', paymentController.processPayment);
module.exports = app;
// index.js
const app = require('./app');
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});Discussion
Last updated