I'm always excited to take on new projects and collaborate with innovative minds.
Kraftonnotgar@gmail.com
https://krafton.my.id
Learn how to seamlessly integrate third-party APIs in your Node.js applications for powerful data access and functionality.
APIs allow your Node.js app to connect with external services. You can pull data, send requests, and extend your project without building everything from scratch. Learning API integration is a skill every developer needs.
npm init -y to set up a package.json.axios or node-fetch for HTTP requests.Example:
npm install axios
Using Axios:
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
This fetches data from the API and logs it.
Some APIs require authentication. Store your API key securely. Use environment variables instead of hardcoding keys.
Example with .env:
API_KEY=your_api_key
In code:
require('dotenv').config();
const axios = require('axios');
axios.get(`https://api.example.com/data?key=${process.env.API_KEY}`)
.then(res => console.log(res.data))
.catch(err => console.error(err));
Example:
async function fetchData() {
try {
const res = await axios.get('https://api.example.com/data', { timeout: 5000 });
console.log(res.data);
} catch (err) {
console.error("Request failed:", err.message);
}
}
fetchData();
In an Express app, you can integrate APIs into your routes.
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/weather', async (req, res) => {
try {
const response = await axios.get(`https://api.weather.com/current?key=${process.env.API_KEY}`);
res.json(response.data);
} catch (err) {
res.status(500).json({ error: "Failed to fetch weather data" });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
Integrating APIs in Node.js lets you extend your projects with powerful features. Start small, handle errors, and always keep security in mind. With practice, APIs will become a natural part of your development workflow