Integrating third-party APIs into your Node.js applications can significantly enhance functionality, allowing developers to leverage existing services and data without reinventing the wheel. Below are three diverse, practical examples of using third-party APIs in Node.js applications.
In this example, we will integrate a weather API to fetch current weather data based on user location. This can be particularly useful for applications that provide local information or travel recommendations.
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;
const apiKey = 'YOUR_WEATHER_API_KEY'; // Replace with your API key
app.get('/weather', async (req, res) => {
const { city } = req.query;
if (!city) {
return res.status(400).send('City is required');
}
try {
const response = await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=\({city}&appid=}\(apiKey}`);
const weatherData = response.data;
res.json({
city: weatherData.name,
temperature: weatherData.main.temp,
description: weatherData.weather[0].description
});
} catch (error) {
res.status(500).send('Error fetching weather data');
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Integrating a payment gateway like Stripe allows you to handle transactions directly within your application. This example shows how to create a simple payment endpoint using the Stripe API.
const express = require('express');
const stripe = require('stripe')('YOUR_STRIPE_SECRET_KEY'); // Replace with your Stripe secret key
const app = express();
app.use(express.json());
app.post('/pay', async (req, res) => {
const { amount, currency, source } = req.body;
try {
const paymentIntent = await stripe.paymentIntents.create({
amount,
currency,
payment_method: source,
confirm: true
});
res.json({ success: true, paymentIntent });
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
app.listen(3000, () => {
console.log('Payment server running on port 3000');
});
This example demonstrates how to fetch recent tweets from a user’s timeline using the Twitter API. This can be useful for applications that aggregate social media content.
const express = require('express');
const { TwitterApi } = require('twitter-api-v2');
const app = express();
const client = new TwitterApi('YOUR_TWITTER_BEARER_TOKEN'); // Replace with your Bearer Token
app.get('/tweets', async (req, res) => {
const { username } = req.query;
if (!username) {
return res.status(400).send('Username is required');
}
try {
const { data } = await client.v2.userTimeline(username);
res.json(data);
} catch (error) {
res.status(500).send('Error fetching tweets');
}
});
app.listen(3000, () => {
console.log('Twitter API server running on port 3000');
});
By utilizing these examples of integrating third-party APIs in Node.js applications, developers can significantly enhance their apps’ capabilities while saving development time.