Language: EN

usar-vuejs-junto-a-axios-para-consumir-un-api-rest

Using VueJs with Axios to consume a Rest API

In this post, we will see how to use the VueJs framework along with the Axios library to make Ajax requests and consume a Rest API.

In a previous post, we already saw an example of the Axios library. In this post, we will continue with this example, combining it with the use of the VueJs framework.

To do this, we will use our usual Rest API, which we created in this post, and we usually use as an example on the blog.

On the one hand, we are going to define a very simple web page for testing. This page is going to “simulate” manipulating a series of items through the Rest API.

vue-axios-example

We have buttons to get all the elements, get the filtered elements, and create a new element. In addition, each element has buttons for ‘Get’, ‘Delete’, ‘Replace’, and ‘Update’,

The ‘index.html’ file, therefore, looks as follows.

<!doctype html>
<html lang="">
 
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
 
<body>

  <!-- Our simple example APP -->
  <div id="app">
  <div>
    <button v-on:click="getAllRequest()">GetAll</button>
  </div>
  <div>
    <button v-on:click="getFilteredRequest()">Filter</button>
    <input v-model="myfilter" placeholder="filter">
  </div>
  <div>
    <button v-on:click="postRequest()">Create</button>
  </div>
    <div>
      <my-component v-for="item in myList" v-bind:my="item" v-bind:key="item.id"></my-component>
   </div>
  </div>
 
  <!-- Loading references to VUE and AXIOS from CDN-->
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  
  <!-- Loading the files that simulate our API and our Vue.JS App -->
  <script type="text/javascript" src="./API.js"></script>
  <script type="text/javascript" src="./App.js"></script>
</body>
 
</html>

Regarding the application code in ‘App.js’, we have,

Vue.component('my-component', {
    props: ['my'],
    template: '<div>{{my.text}}    <button v-on:click="getRequest(my.id)">Get</button>  <button v-on:click="patchRequest(my.id)">Update</button>   <button v-on:click="putRequest(my.id)">Replace</button>   <button v-on:click="deleteRequest(my.id)">Delete</button></div>',
    methods: {
        getRequest: function (id) {
            API_getRequest(id);
        },
        
        patchRequest: function (id) {
            API_patchRequest(id, 'NewItem');
        },
        
        putRequest: function (id) {
            API_putRequest(id, 'NewItem');
        },
        
        deleteRequest: function (id) {
            API_deleteRequest(id);
        }
    }
})

var app = new Vue({
    el: '#app',
    data: {
        myfilter: "",
        myList: [
            { id: 0, text: 'Item1'},
            { id: 1, text: 'Item2' },
            { id: 2, text: 'Item3'}
        ]
    },
    
    methods: {
        getAllRequest() {
            API_getAllRequest();
        },
        
        getFilteredRequest() {
            API_getFilteredRequest(this.$data.myfilter);
        },
        
        postRequest() {
            API_postRequest('NewItem');
        },  
    }
})

Where we see that we have defined a Vue component for each of the API elements. This component has buttons that trigger the callback actions that call the corresponding API functions.

On the other hand, we have the Vue application, where we have only defined the three “general” methods, and a series of example data. In a real application, we would obtain this data as a query to some data source.

Finally, we have the ‘Api.js’ file, which exposes the calls to the Rest API, which we will make through Axios.

function API_getRequest(id) {
    axios.get('http://localhost:8080/item/' + id)
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

function API_getFilteredRequest(filter) {
    axios.get('http://localhost:8080/item', {
        params: {
            filter: filter
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

function API_getAllRequest() {
    axios.get('http://localhost:8080/item')
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

function API_postRequest(data) {
    axios.post('http://localhost:8080/item', {
        data: data
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

function API_putRequest(id, data) {
    axios.put('http://localhost:8080/item/ ' + id, {
        data: data
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

function API_patchRequest(id, data) {
    axios.patch('http://localhost:8080/item/ ' + id, {
        data: data
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

function API_deleteRequest(id) {
    axios.delete('http://localhost:8080/item/' + id)
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
    });
}

If we run the code and click on the buttons, we can verify in the JavaScript console that the actions are being triggered correctly.

vue-axios-developers-tools

As well as in the NodeJs console that runs the Rest API.

vue-axios-console

That’s how easy it is to combine the power of VueJs with Axios, two libraries that fit perfectly together and facilitate the development of web applications.

In the next post, we will expand and finish this example, adding Vuetify to the equation. See you soon!

Download the code

All the code in this post is available for download on GitHub. github-full