To consume a RESTful API in Node.js, you can use the built-in http
module or use popular third-party libraries like axios
or node-fetch
. In this example, I'll demonstrate using axios
, as it provides a simple and clean API for making HTTP requests.
First, install axios
using npm (Node Package Manager) if you haven't already:
bashnpm install axios
Now, you can use the following code to consume a RESTful API in Node.js:
javascriptconst axios = require('axios');
// Define the API endpoint
const apiUrl = 'https://api.example.com/data';
// Make a GET request
axios.get(apiUrl)
.then(response => {
// Handle the API response data
console.log('API Response:', response.data);
})
.catch(error => {
// Handle errors
console.error('Error:', error.message);
});
This is a basic example using a GET request. Depending on the API you're working with, you may need to use other HTTP methods like POST, PUT, or DELETE. Here's an example of a POST request:
javascriptconst axios = require('axios');
const apiUrl = 'https://api.example.com/data';
// Data to be sent in the POST request
const postData = {
key1: 'value1',
key2: 'value2'
};
// Make a POST request
axios.post(apiUrl, postData)
.then(response => {
console.log('API Response:', response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
Make sure to check the API documentation for the specific endpoint you are working with to understand the required HTTP methods and request payloads.
Remember to handle errors appropriately, as shown in the examples above, to ensure your application responds gracefully to issues like network problems or server errors.