Interacting with a REST API from Node.js often involves using the npm package “axios”. This is a promise based HTTP client for the browser and node.js. Here’s a basic example of how to interact with a REST API using this package.
You can start by installing “axios” via npm:
```
npm install axios
```
Then you can require the installed package:
```
const axios = require(‘axios’);
```
Afterwards, you’re set to make your API calls:
```
//Making a GET request
axios.get(‘https://api.github.com/users/username’)
.then(function (response) {
// handle success
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
});
//Making a POST request
axios.post(‘https://api.example.com/data’, {
firstName: ‘Fred’,
lastName: ‘Flintstone‘
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
```
Here we make GET and POST requests using axios.get and axios.post respectively.
In the .then() block you receive a response object from which you can extract the requested data.
Any errors that occur during the request will be caught in the .catch() block.