
In this tutorial, you will learn how to invoke data from external APIs using Express, a popular Node.js web framework. Interacting with external APIs allows you to fetch data from third-party services and integrate it into your application.
We will utilize the Axios library to make HTTP requests and retrieve data from the external API. By the end of this tutorial, you will have a solid understanding of how to invoke data from external APIs using Express.
Prerequisites
- Basic knowledge of JavaScript and Node.js
- Familiarity with Express framework
Setting up the Project
1. Create a new directory for your project.
2. Open the terminal and navigate to the project directory.
3. Run npm init -y to initialize a new Node.js project.
4. Install Express by running npm install express.
5. Create an index.js file as the entry point of your application.
Installing Dependencies
Run npm install axios to install the Axios library, which will be used to make HTTP requests.
Invoking Data from an External API
1. Open the index.js file and import the necessary modules.
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;
2. Calling external API with axios
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;
app.get('/api/data', async (req, res) => {
try {
const data = await fetchData();
res.json(data);
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ error: 'Failed to fetch data' });
}
});
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
return response.data;
} catch (error) {
throw new Error('Failed to fetch data from API');
}
}
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
In the updated code, we define a new function called fetchData that encapsulates the logic to call the function API using axios.get. This function is marked as async, indicating that it will return a promise.
Within the route handler for /api/data, we use await to asynchronously call the fetchData function. If the API call is successful, the returned data is sent as a JSON response. If an error occurs during the API call, we catch the error and send an appropriate error response to the client.
Make sure to replace ‘https://api.example.com/data’ with the actual URL of the function API you want to call.
By using the async/await syntax, we can handle asynchronous operations in a more readable and sequential manner, making the code easier to understand and maintain.
3. Making a post request to external API with some payload
async function fetchData() {
try {
let payload = {
"city": "Kanpur",
"temperature": "C"
};
const response = await axios.post('https://api.example.com/data', payload);
return response.data;
} catch (error) {
throw new Error('Failed to fetch data from API');
}
}
4.. Handling API Response
If the API request is successful, we retrieve the response data and send it back as a JSON response to the client.
If an error occurs during the API request, we log the error and send an appropriate error response to the client.
5. Error Handling
Proper error handling is crucial when calling external APIs with payloads. In the code above, we catch any errors that occur during the API request and send an appropriate error response to the client. Customize the error handling logic based on your application’s requirements.
By following this tutorial, you now have the knowledge and tools to invoke data from external APIs using Express in a seamless and efficient manner.
