We have already seen how to create a Rest API with Node.js and the express.js
library. Now we will learn how to consume a Rest API from a Node.js application using the popular axios
library.
axios
is a promise-based HTTP library that allows us to make HTTP requests from the client in Node.js and in the browser.
It is easy to use and provides a simple and consistent interface for working with RESTful APIs.
How to use axios
First, make sure to have axios
installed in your Node.js project:
npm install axios
Example of Consuming a RESTful API
Let’s assume we have a RESTful API that manages users and is available at the URL http://localhost:3000/users
.
Here is an example of how we can consume this API using axios
:
const axios = require('axios');
// Make a GET request to get all users
axios.get('http://localhost:3000/users')
.then((response) => {
// Handle the successful response
console.log('Users:', response.data);
})
.catch((error) => {
// Handle the error in case of failure
console.error('Error getting users:', error);
});
In this example, we are making a GET request to the URL http://localhost:3000/users
to get all users.
As we can see, it is very simple to make requests to a Rest API with axios.js
.
Then, we handle the successful response in the .then()
method and any error in the .catch()
method.
In addition to GET
, axios
supports other HTTP methods such as POST
, PUT
, DELETE
, among others, which can be used as needed. It also allows configuring HTTP headers and sending parameters in requests.
In short, it allows you to do everything. If you have more questions, consult the official documentation of the library.