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 library axios
.
axios
is a promise-based HTTP library that allows us to **make HTTP requests from the client in Node.js and in the browser.
Axios
is easy to use and provides a simple and consistent interface for working with RESTful APIs. It has been around for a while, but it is one of the most stable and widely used libraries.
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
Suppose we have a RESTful API that manages users and is available at the URL http://localhost:3000/usuarios
.
Let’s see 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/usuarios')
.then((response) => {
// Handle the successful response
console.log('Users:', response.data);
})
.catch((error) => {
// Handle the error in case of failure
console.error('Error fetching users:', error);
});
In this example, we are making a GET request to the URL http://localhost:3000/usuarios
to get all users.
As we can see, it is very easy to make requests to a REST API with axios.js
.
Then, we handle the successful response in the .then()
method and any errors in the .catch()
method.
In addition to GET
, axios
supports other HTTP methods like POST
, PUT
, DELETE
, among others, which can be used according to your needs. It also allows you to configure HTTP headers and send parameters in requests.
In short, it can do almost everything. If you have more questions, consult the official documentation of the library.
Download the code
All the code from this post is available for download on Github