axios api

How to consume RESTful APIs with axios


Knowing how to consume data from an API is very important as a front-end developer. In this article, we’ll discuss what an API is and how to consume data from it via http to give your web app superpowers.

It is assumed that you have adequate knowledge of JavaScript and how NodeJs works.

What is an API?

The word “API” is an acronym and it stands for “Application Programming Interface”.

Think of it as the waiter at a restaurant, you (the client) make requests to and the server which is the cook, receives your order from the waiter and prepares for the waiter to serve you when it’s ready.

An API is like a middle man between a server and your application.

axios APIs
a graphical analogy of how APIs work

Consuming APIs with Axios

Axios is an NPM package for making HTTP requests in our node apps, We’ll be building a demo app to fetch a list of users and output the result on our own site.

I’ll also assume that you have the project set up for this tutorial, if not you can create a new folder and run npm init -y in that directory in your terminal. This will create two files; index.js and package.json.

Next, you have to install axios by running npm install --save axios, after installation, you should notice changes in your package.json file.

Making a simple get request

First off, we need to create spin up a server to deliver the data we consumed from an external API to our web pages for users to see. we’ll use the built-in http module in node to do that. the code snippet below creates a basic server that displays “hello world” whenever a request is made.


const http = require('http');

http.createServer((req, res)=>{
  res.write"Hello world n"); // write a response
  res.end(); //end the response
}).listen(8000); // listen for requests on port 8000

If you open your browser and navigate to localhost:8000, you should see “Hello world” on the page.

Now to start making http requests to the external API, we import the axios module and make a GET request to the endpoint by using axios.get()


const http = require('http');
const axios = require('axios');

http.createServer((req, res)=>{
  res.write"Hello world n"); // write a response
  res.end(); //end the response
}).listen(8000); // listen for requests on port 8000

let users = []; // names of users will be stored here
axios.get("https://jsonplaceholder.typicode.com/users")
.then(({ data }) => {
  users = data.map(user => user.name); // get only the names of the users and store in an array
})
.catch(error=>{
  console.log(error);
});

From the official Github repository for axios here , it says:

Promise based HTTP client for the browser and node.js

axios ReadMe file

So making a request with axios returns a promise which we listen for when the data is returned using the .then() and perform our logic inside it. Basically what that means is that axios supports promises and of course, it’s possible to use async/await:


let users = []; // names of users will be stored here
(async function getNames(){
  try{
    const {data} = await axios.get("https://jsonplaceholder.typicode.com/users");
    users = data.map(user=>user.name);
  } catch(error){
    console.log(error)
  }
})()

If you noticed earlier, I was destructuring a data variable from the response passed as an argument, that’s because axios returns an object containing metadata about the request, the main result is stored as a value to a data key in the object.

Now that we’ve been able to fetch and format our data, we need to serve that up to the clients in the response.

So our entire code will look like this:


var http = require("http");
const axios = require("axios").default;

//create a server object:
http
  .createServer(function(req, res) {
    res.write(users.join("n n")); //display the list of users on the page
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080

let users = [];

(async function getNames() {
  try {
    const { data } = await axios.get(
      "https://jsonplaceholder.typicode.com/users"
    );
    users = data.map(user => user.name);
  } catch (error) {
    console.log(error);
  }
})();

There are other request methods of course

This demo only utilizes one of the various methods that axios supports, here’s a few listed:

  1. axios.put()
  2. axios.post()
  3. axios.patch()
  4. axios.patch()

You can read more about axios in their documentation here.

[epcl_columns]  [epcl_button label=”Code source” url=”https://github.com/Dunebook/RESTfulAPIswithaxios/tree/master/” type=”outline” color=”red” size=”large” icon=”fa-github” target=”_blank” rel=”dofollow”][/epcl_button]       [epcl_button label=”Project Demo” url=”https://codesandbox.io/s/consuming-apis-with-axios-demo-qbmk4?from-embed” type=”outline” color=”red” size=”large” icon=”fa-github” target=”_blank” rel=”dofollow”]    [/epcl_columns]


Share on social media

//