Vus JS is an amazing front end JavaScript framework that is adopted widely by developers. While calling an API from within a VueJS application we either use fetch API or axios. The fetch API is used for AJAX requests and it’s more flexible and powerful as compared to the old XMLHttpRequest. However, Axios is the more popular and easy to adapt as compared to the fetch API. In this article I will share with you how to handle GET, POST, PUT, and DELETE requests with Vue Axios.

We have 2 ways to use Axios. One is to use it directly and another one is to use the VueAxios plugin. In this article let’s use the first option.

Vue axios HTTP requests

First, we need to install axios in our VueJS project as follows.

# NPM
$ npm install axios --save

# Yarn
$ yarn add axios

Once it’s installed we are ready to use it in our project. This tutorial is all about VueJS axios so we will not be using any backend code instead we will use JSONPlaceholder.

This API supports all types of requests however the POST, PUT, and DELETE requests are faked. The data inside the server will be persistent and not update with our calls but we will get a fake response to virtualize.

Vue axios GET request

First of all, let’s create our template to render all the users fetched with API call.

<template>
  <div>
    <button @click="getUsers">Get users</button> <br />

    <div class="users" v-for="user in users" :key="user.id">
      <h2>{{ user.name }}</h2>
      <p>{{ user.email }}</p>
  </div>
</template>

In the above template, we have a button that will trigger the getUsers method. That method will call the API and fetch users. Once the users are fetched we will be able to render our loop.


<script>
import axios from "axios";
export default {
  name: "App",
  data() {
    return {
      users: []
    };
  },
  methods: {
    async getUsers() {
      try {
        const users = await axios.get(
          "https://jsonplaceholder.typicode.com/users"
        );

        this.users = users.data;
      } catch (e) {
        console.log(e);
      }
    },
  },
};
</script>

Here you can see we are using async-await for API calls with vue axios. The API calls are triggered from within the try block and if there is an error we will resolve it in the catch block.

Once we send a get request we will be able to access the data returned from the API by using users variable. Along with the data, it will also contain some other values like headers and etc. So in order to fetch the JSON data returned from the server access the data property of users object.

Now, let’s move to the next part – update user data.

Vue axios POST request

So far we have accessed all the users from API with vue axios. Now in this section, we will create a form in our template to let the users submit data to the server from the front end.

<div class="user-add">
  <h2>Add user</h2>
  <input type="text" v-model="name" /> <br />
  <input type="text" v-model="email" /> <br />

  <button @click="storeUser">Store</button>
</div>

I have added a div and inside that, we have one headline, two inputs, and a button to store the user data. Now we need to add two new variables into the data section and those are name and email.

email: '',
name: '',

Once the data is added we are ready to proceed with the storeUser method.

async storeUser() {
  try {
    const user = await axios.post(
      "https://jsonplaceholder.typicode.com/users", 
      {
        name: this.name,
        email : this.email
      }
    );

    console.log(user)
  } catch(e) {
    console.log(e);
  }
},

Inside the methods add the above code to handle POST requests with vue axios. Basically, in POST request we change the method from GET to POST and pass a second parameter to the method.

The second parameter holds the object that we want to pass to the server. In our case, it's name and email.

Once the request is sent to the server we will also get some response and can access that using the variable. In our case, it's the user here.

Vue axios PUT request

A PUT request is used to update data in the server with an API call. Here in our case, we need to add a form to let the users update existing users information using that.

<div class="user-update">
  <h2>Update user</h2>
  <input type="text" v-model="user.name" /> <br />
  <input type="text" v-model="user.email" /> <br />

  <button @click="updateUser">Update</button>
</div>

In the above markup, you can see it's very identical to the add user div. Except for the headline content, button method, button content, and v-model values.

Instead of using the name and email, we are using user.name and user.email. We could use the previous block and add a condition to toggle between add and edit.

However in order to make it simple and clear to understand we have divided this into two parts add or store and edit or update section.

Now, let's handle the updateUser method.

async updateUser() {
  try {
    const user = await axios.put(
      "https://jsonplaceholder.typicode.com/users/" + this.user.id,
      {
        name: this.user.name,
        email: this.user.email,
      }
    );

    console.log(user.data);
    alert("User updated!");
  } catch (e) {
    console.log(e);
  }
},

The PUT and POST request structure is very similar except the method name. Here we will pass the updated name and email to the server.

If you closely take a look at the URL you can see we need to pass the user id. So that the server can use that parameter to update the right user.

In order to make it work, we need to know which user is being updated right now. That can be done by using a new variable called user inside our data.

Our data section will look something like below.

data() {
  return {
    users: [],
    user: {},
    email: '',
    name: '',
  };
},

Also, we need to add a button for each user to edit the information. Simply add a button with a method to assign data to edit as follows inside div class users.

<button @click="editUser(user)">Edit</button>

Now the editUser method has access to the user object so we can just set our user data inside the method.

async editUser(user) {
  this.user.name = user.name;
  this.user.email = user.email;
  this.user.id = user.id;
},

That's it for the PUT request, Now we have access to the user, and once the edit button is clicked our update form will be prefilled to edit the values and update.

Vue axios DELETE request

In order to perform a delete request with vue axios, we need another button after the edit button.

<div class="users" v-for="user in users" :key="user.id">
  <h2>{{ user.name }}</h2>
  <p>{{ user.email }}</p>

  <button @click="editUser(user)">Edit</button>
  <button @click="deleteUser(user.id)">Delete</button>
</div>

Here you can see the updated final look of the div with class users. Now, let's handle the deleteUser method.

async deleteUser(id) {
  let x = window.confirm("You want to delete the user?");

  if (x) {
    const user = await axios.delete(
      "https://jsonplaceholder.typicode.com/users/" + id
    );

    console.log(user);
    alert("User deleted!");
  }
},

One can always click on a delete button by mistake. So make sure to protect it using a confirm action.

If the user clicks on ok of a confirm window then we will submit a DELETE request. Otherwise, nothing will happen.

The DELETE request is similar to GET except for the method name and the URL. In case of delete, we need to pass the id at the end of the URL.

Here is the sandbox link to get the entire code.

Point to note: The above URL structure follows the REST API architecture. In your case, the API server may or may not follow it. So the URL pattern may be similar or different. However, we have presented the use of Axios with Vue js with a real-world example. Hope this article has helped you to understand Vue Axios.