consumir-api-rest-con-axios-y-nodejs

How to consume a Rest API with Axios and Node.js

  • 2 min

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.

Axios is easy to use and provides a simple and consistent interface for working with RESTful APIs. It’s been around for years, but it’s one of the most stable and widely used libraries.

How to use axios

First, make sure you 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/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);
  });
Copied!

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’s very, very easy 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 lets you do everything. If you have more questions, consult the library’s official documentation.

Download the code

All the code for this post is available for download on Github github-full