How to Call an API Continuously from Server Side Itself in Node.js/Express.js ?
Last Updated :
10 Jul, 2024
To call an API continuously from the server side in a Node.js/Express.js environment, you can implement a periodic task that executes at regular intervals. This is typically done using functions such as setInterval
, which is built into Node.js for scheduling repeated operations.
There are multiple ways to make API calls from a Node.js server, depending on the level of abstraction you prefer. The easiest method is to use the Axios library.
Set Up a Continuous API Call
You can use setInterval
to call the API at regular intervals. The following example will request data from an API every 10 seconds.
// server.js
const express = require('express');
const axios = require('axios');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('API caller is running');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
// Function to call the API
const callApiContinuously = async () => {
try {
const response = await axios.get('https://api.example.com/data');
console.log('API Response:', response.data);
// You can handle the response here (e.g., save to database)
} catch (error) {
console.error('Error calling API:', error);
}
};
// Call the API every 10 seconds
setInterval(callApiContinuously, 10000);
Note: Replace 'https://api.example.com/data'
with the actual API endpoint you want to call.
Steps to Setup Project to call an API
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 3:Â Install the necessary packages/libraries in your project using the following commands.
npm install express axios
Project Structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
"axios": "^1.7.2",
}
Example: Implementation to show to call an API continuously from server side.
Node
// app.js
const express = require('express')
const axios = require('axios')
const app = express()
// Post ID tracker
let num = 0
setInterval(() => {
// Increment post tracker
num++
console.log('Wait for 2 second...')
// Make GET Request on every 2 second
axios.get(
`https://jsonplaceholder.typicode.com/posts/${num}`)
// Print data
.then(response => {
const { id, title } = response.data
console.log(`Post ${id}: ${title}\n`)
})
// Print error message if occur
.catch(error => console.log(
'Error to fetch data\n'))
}, 2000)
Explanation: In the above example, NodeJS call an API in 2-second intervals to fetch data. If the promise is resolved, then the block will be executed and print data. If a promise rejects, catch block will be executed and print an Error message. Â
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.js
Output:

Example: Implementation to show to call an API continuously from server side doing with POST request.
Node
// app.js
const express = require('express')
const axios = require('axios')
const app = express()
// Dummy database
const posts = [
{
title: 'Headline 1',
id: 1,
body: `sint suscipit perspiciatis velit dolorum
rerum ipsa laboriosam odio`,
userId: 1
},
{
title: 'Headline 2',
id: 2,
body: "fugit voluptas sed molestias voluptatem provident",
userId: 1
},
{
title: 'Headline 3',
id: 3,
body: "voluptate et itaque vero tempora molestiae",
userId: 1
}
]
// Loop over the posts
posts.forEach(post => {
// Post data to API endpoint
axios.post('https://jsonplaceholder.typicode.com/posts/', {
body: post,
})
// Print response
.then(response => {
const { id, title } = response.data.body
console.log(`Post ${id}: ${title}`)
})
// Print error message if occur
.catch(error => console.log(error))
})
Explanation: In the above example, we have created dummy user data. NodeJS makes a POST request to send these data to the API endpoint and print either the response's data or the error message.
Step to Run Application:Â Run the application using the following command from the root directory of the project
node app.js
Output:
Similar Reads
How to Send Response From Server to Client using Node.js and Express.js ?
In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. T
4 min read
How to Implement Search and Filtering in a REST API with Node.js and Express.js ?
Search and filtering are very basic features that an API must possess to serve data to the client application efficiently. By handling these operations on the server-side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance.In this
5 min read
How to Deploy Node.js Express Application on Render ?
Deploying a Node.js Express application on Render is straightforward and involves a few key steps to set up your project, configure deployment settings, and manage your application on the Render platform. Render provides an easy-to-use platform for deploying applications, offering features like auto
4 min read
How to Create a Simple Server in Node.js that Display Hello World ?
We will create a simple server in Node.js that returns Hello World using an express server. Node.js is a powerful JavaScript runtime built on Chrome's V8 engine, commonly used to build scalable network applications. One of the fundamental tasks when learning Node.js is creating a simple server that
2 min read
How to Separate Routers and Controllers in Node.js ?
In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the appli
4 min read
How to Manage Sessions and Cookies in Express JS?
Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of
4 min read
How to Push Data to Array Asynchronously & Save It in Node.js ?
Node.js is a powerful environment for building scalable and efficient applications, and handling asynchronous operations is a key part of its design. A common requirement is to collect data asynchronously and store it in an array, followed by saving this data persistently, for instance, in a databas
7 min read
How to Configure Socket.IO with Demo-Chat App in Node.js ?
For making a chat app, it is required that the server sends data to the client but the client should also respond back to the server. This can be done by making use of the Websockets. A WebSocket is a kind of communication pipe opened in two directions. Prerequisite: Node.js: It is an open source Ja
5 min read
How to Connect to Telnet Server from Node.js ?
Connecting to a Telnet server from Node.js involves creating a client that can communicate using the Telnet protocol. Telnet is a protocol used to establish a connection to a remote host to execute commands and transfer data. In Node.js, you can use various packages to facilitate the connection to a
4 min read
How to Dynamically Call Router Function in Node.js ?
In Node.js Dynamically calling a router function means that the function is selected at runtime based on the request parameters, instead of being explicitly defined in the code. This can be useful when you want to handle a large number of similar requests without having to define a separate function
4 min read