Axios for API Call

Axios for API Call

The React library is well known for its ability to create rich and highly scalable user interfaces. In React, there are numerous methods for fetching/consuming data from an external API.

Consuming REST APIs or APIs in a React application can be accomplished in a variety of ways, but in this tutorial, we will look at one of the most popular methods, Axios (a promise-based HTTP client).

What is Axios?

Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (it can run in the browser and nodejs with the same codebase).

We'll go over the following topics in-depth:

  • Why use Axios.

  • Installing Axios.

  • How to Request an Axios POST.

  • Axios HTTP requests for Shorthand methods.

  • What does axios.post() return?

Why Use Axios?

The most basic function of any web application is to communicate with servers using the HTTP protocol. This is simple to accomplish with Fetch or Axios. The functionality of Fetch and Axios is very similar. Because of its simplicity, some developers prefer Axios to built-in APIs. This brings us to the Whys' of Axios:

  • Axios has a URL in the request object.
  • Axios is a stand-alone third-party package that can be easily installed, compared to fetch().
  • Axios performs automatic transforms of JSON data.
  • Axios has wide browser support.
  • The ability to cancel requests.
  • Built-in XSRF protection.

Installing Axios

You can install Axios using:

  • Using npm:
    npm install axios
    
  • Using Bower:
    bower install axios
    
  • Using yarn
    yarn add axios
    
  • Using unpkg CDN
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    

Making an Axios POST Request

To "post" data to an endpoint, an Axios POST request can be made. This endpoint can then use the POST request to perform a task or initiate an event.

The HTTP post request is made by calling axios.post ().

This method usually requires the use of two parameters. First, it requires the URI of the service endpoint. Second, we should pass it to an object containing the properties that we want to send to our server.

Once Axios has been installed, a reference must be made when you need to use Axios. All you have to do is import the installed dependency using:

import axios from 'axios'

Let's look into a simple Axios POST example:

axios({
     method: 'post',
     URL: 'API-URL',
         data: {
             firstName: 'Nnamdi',
             lastName: 'Clement',
          }
});

This code simply instructs Axios to send a POST request to the 'API-URL' you provide with a key/value pair object as its data. Axios will convert the data to JSON and send it as the request body automatically.

Axios HTTP requests for Shorthand methods.

Axios also includes a set of shorthand methods for handling various types of requests. This is my favorite method of using Axios, I recommend the usage of the Shorthand method. You can choose which method works best for you, for the purpose of this tutorial I'll be using the POST request.

Data can be referred to as the pieces of information you want to send to the server, for example:

const data = {
          "firstName" : "Nnamdi",
          "lastName" :  "Clement",
          "phoneNumber" : "+2347034947199",
}

What axios.post() return

Following an HTTP POST request, Axios returns a promise that is either fulfilled or rejected based on the response from the backend service.

To handle the result using the shorthand method, you can use the then() method, like this:

axios.post('API-URL', data)
   .then( response => {
      console.log( response.data );
})
  .catch( error => {
      console.log( error.response )
})

If the promise is fulfilled, the first argument of then() will be called; if the promise is rejected, the second argument will be called. According to the documentation, the fulfillment value is an object containing the following information:

status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

status: 400,

  // `statusText` is the HTTP status message from the server response
statusText: 'Request failed'

Summary and Full code

import axios from axios;

const handleSubmit = (event) => {
       event.preventDefault();
       const data = {
             "firstName" : "Nnamdi",
            "lastName" :  "Clement",
            "phoneNumber" : "+2347034947199",
}

axios.post('API-URL', data)
      .then( response => {
            console.log( response.data );
})
     .catch ( error => {
            console.log ( error.response );
});

Wrapping Up

Axios is popular among developers for a reason: it is packed with useful features. In this post, we looked at several key Axios features and learned how to use them in practice. However, there are still many aspects of Axios that we haven't covered. So, for more information, visit the Axios GitHub page.

Do you have any pointers on how to use Axios? Feel free to leave your suggestions in the comments!