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

Using VueJs with Axios to consume a Rest API

  • 4 min

In this post, we will see how to use the VueJs framework together 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 this example, combining it with the use of the VueJs framework.

For this, we will use our usual REST API, which we created in this post, and often use as an example on the blog.

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

vue-axios-example

We have buttons to get all items, get filtered items, and create a new item. In turn, each item has buttons for ‘Get’, ‘Delete’, ‘Replace’, and ‘Update’.

The ‘index.html’ file, therefore, looks like this.

<!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>
Copied!

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');
        },  
    }
})
Copied!

Where we see that we have defined a Vue component for each of the API items. This component has buttons that trigger 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 some 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 () {
    });
}
Copied!

If we run the code and press 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 running the REST API.

vue-axios-console

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

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

Download the Code

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