Vue Axios example – Get/Post/Put/Delete with Rest API

Axios is a promise-based HTTP Client Javascript library for Node.js and Browser. In this tutorial, we will create Vue example that use Axios to make Get/Post/Put/Delete request with Rest API and JSON data in a Vue.js component.

Related Posts:
Axios Tutorial: Get/Post/Put/Delete request example
Vue 3 Composition API tutorial with examples
Vue 3 CRUD example with Axios & Vue Router
Vue 3 Authentication with JWT, Vuex, Axios and Vue Router


Vue Axios example Overview

We will build a Vue Client with Axios library to make CRUD requests to Rest API in that:

  • Vue Axios GET request: get all Tutorials, get Tutorial by Id, find Tutorial by title
  • Vue Axios POST request: create new Tutorial
  • Vue Axios PUT request: update an existing Tutorial
  • Vue Axios DELETE request: delete a Tutorial, delete all Tutorials

vue-axios-example

This Vue Axios Client works with the following Rest API:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

You can find step by step to build a Server like this in one of these posts:

Remember that you need to configure CORS: Access-Control-Allow-Origin: *.
It helps the REST APIs can be accessed by any origin.

Vue – import Axios

There are 2 ways to import Axios into Vue Application:

Using CDN:

  • jsDelivr CDN:
  • <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  • unpkg CDN:
  • <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    

For example, open public/index.html and add HTML <script> element into <head> tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta
      name="description"
      content="Vue Axios example - GET/Post/Put/Delete"
    />
    ...
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>Vue Axios example</title>
  </head>
  <body>
    ...
  </body>
</html>

– Installing axios module:

Create Axios instance in Vue

We can create a new instance of axios using axios.create(config) method, then export it as an apiClient:

src/http-common.js

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-type": "application/json"
  }
});

In src/App.js

import apiClient from "./http-common";
...

Now we can use apiClient to send HTTP requests and receive responses.

The response for a Axios request contains:

  • data: parsed response body provided by the server
  • status: HTTP status code
  • statusText: HTTP status message
  • headers: HTTP headers (lower case)
  • config: the request config that was provided to axios
  • request: the last client request instance that generated this response
For more details about Axios (with instance creation, params, json, body, headers, error handling…), kindly visit:
Axios Tutorial: Get/Post/Put/Delete request example

Vue Axios Get JSON data

Let’s implement a Vue component to fetch JSON data from API:

  • get all Tutorials
  • get Tutorial by Id
  • find Tutorial by title
<template>
  <div id="app" class="container">
    <div class="card">
      <div class="card-header">Vue Axios GET - BezKoder.com</div>
      <div class="card-body">
        <div class="input-group input-group-sm">
          <button class="btn btn-sm btn-primary" @click="getAllData">Get All</button>

          <input type="text" ref="get_id" class="form-control ml-2" placeholder="Id" />
          <div class="input-group-append">
            <button class="btn btn-sm btn-primary" @click="getDataById">Get by Id</button>
          </div>

          <input type="text" ref="get_title" class="form-control ml-2" placeholder="Title" />
          <div class="input-group-append">
            <button class="btn btn-sm btn-primary" @click="getDataByTitle">Find By Title</button>
          </div>

          <button class="btn btn-sm btn-warning ml-2" @click="clearGetOutput">Clear</button>
        </div>   
        
        <div v-if="getResult" class="alert alert-secondary mt-2" role="alert"><pre>{{getResult}}</pre></div>
      </div>
    </div>
  </div>
</template>

<script>
import http from "./http-common";

export default {
  name: "App",
  data() {
    return {
      getResult: null,
    }
  },
  methods: {
    fortmatResponse(res) {
      return JSON.stringify(res, null, 2);
    },

    async getAllData() {
      try {
        const res = await http.get("/tutorials");

        const result = {
          status: res.status + "-" + res.statusText,
          headers: res.headers,
          data: res.data,
        };

        this.getResult = this.fortmatResponse(result);
      } catch (err) {
        this.getResult = this.fortmatResponse(err.response?.data) || err;
      }
    },

    async getDataById() {
      const id = this.$refs.get_id.value;

      if (id) {
        try {
          const res = await http.get(`/tutorials/${id}`);

          const result = {
            status: res.status + "-" + res.statusText,
            headers: res.headers,
            data: res.data,
          };

          // const result = {
          //   data: res.data,
          //   status: res.status,
          //   statusText: res.statusText,
          //   headers: res.headers,
          //   config: res.config,
          // };

          this.getResult = this.fortmatResponse(result);
        } catch (err) {
          this.getResult = this.fortmatResponse(err.response?.data) || err;
        }
      }
    },

    async getDataByTitle() {
      const title = this.$refs.get_title.value;

      if (title) {
        try {
          // const res = await instance.get(`/tutorials?title=${title}`);
          const res = await http.get("/tutorials", {
            params: {
              title: title,
            },
          });

          const result = {
            status: res.status + "-" + res.statusText,
            headers: res.headers,
            data: res.data,
          };

          this.getResult = this.fortmatResponse(result);
        } catch (err) {
          this.getResult = this.fortmatResponse(err.response?.data) || err;
        }
      }
    },

    clearGetOutput() {
      this.getResult = null;
    },
  }
}
</script>

The result will look like this:

vue-axios-get-json-data

Find tutorial by id:

vue-axios-get-json-data-search

Filter tutorials by title:

vue-axios-get-json-data-filter

Vue Axios Post

Let’s use Vue Axios POST Json data to create new Tutorial.

To send the request with Headers, we pass an option object with headers property right after the body.

<template>
    <div class="card">
      <div class="card-header">Vue Axios POST - BezKoder.com</div>
      <div class="card-body">
        <div class="form-group">
          <input type="text" class="form-control" ref="post_title" placeholder="Title" />
        </div>
        <div class="form-group">
          <input type="text" class="form-control" ref="post_description" placeholder="Description" />
        </div>
        <button class="btn btn-sm btn-primary" @click="postData">Post Data</button>
        <button class="btn btn-sm btn-warning ml-2" @click="clearPostOutput">Clear</button>

        <div v-if="postResult" class="alert alert-secondary mt-2" role="alert"><pre>{{postResult}}</pre></div>
      </div>
    </div>
  </div>
</template>

<script>
import http from "./http-common";

export default {
  name: "App",
  data() {
    return {
      postResult: null,
    }
  },
  methods: {
    fortmatResponse(res) {
      return JSON.stringify(res, null, 2);
    },

    async postData() {
      const postData = {
        title: this.$refs.post_title.value,
        description: this.$refs.post_description.value,
      };

      try {
        const res = await http.post("/tutorials", postData, {
          headers: {
            "x-access-token": "token-value",
          },
        });

        const result = {
          status: res.status + "-" + res.statusText,
          headers: res.headers,
          data: res.data,
        };

        this.postResult = this.fortmatResponse(result);
      } catch (err) {
        this.postResult = this.fortmatResponse(err.response?.data) || err;
      }
    },

    clearPostOutput() {
      this.postResult = null;
    },
  }
}
</script>

Check the result by making a Vue Axios Post Request:

vue-axios-post-example

Vue Axios Put

We’re gonna use Vue with Axios PUT request to update an existing Tutorial.

<template>
    <div class="card">
      <div class="card-header">Vue Axios PUT - BezKoder.com</div>
      <div class="card-body">
        <div class="form-group">
          <input type="text" class="form-control" ref="put_id" placeholder="Id" />
        </div>
        <div class="form-group">
          <input type="text" class="form-control" ref="put_title" placeholder="Title" />
        </div>
        <div class="form-group">
          <input type="text" class="form-control" ref="put_description" placeholder="Description" />
        </div>
        <div class="form-check mb-2">
          <input type="checkbox" class="form-check-input" ref="put_published" />
          <label class="form-check-label" for="put_published">Publish</label>
        </div>
        <button class="btn btn-sm btn-primary" @click="putData">Update Data</button>
        <button class="btn btn-sm btn-warning ml-2" @click="clearPutOutput">Clear</button>

        <div v-if="putResult" class="alert alert-secondary mt-2" role="alert"><pre>{{putResult}}</pre></div>
      </div>
    </div>
  </div>
</template>

<script>
import http from "./http-common";

export default {
  name: "App",
  data() {
    return {
      putResult: null,
    }
  },
  methods: {
    fortmatResponse(res) {
      return JSON.stringify(res, null, 2);
    },

    async putData() {
      const { put_id, put_title, put_description, put_published } = this.$refs;
      const id = put_id.value;

      if (id) {
        const putData = {
          title: put_title.value,
          description: put_description.value,
          published: put_published.checked,
        };

        try {
          const res = await http.put(`/tutorials/${id}`, putData, {
            headers: {
              "x-access-token": "token-value",
            },
          });

          const result = {
            status: res.status + "-" + res.statusText,
            headers: res.headers,
            data: res.data,
          };

          this.putResult = this.fortmatResponse(result);
        } catch (err) {
          this.putResult = this.fortmatResponse(err.response?.data) || err;
        }
      }
    },

    clearPutOutput() {
      this.putResult = null;
    },
  }
}
</script>

The result will look like this:

vue-axios-put-example

Vue Axios Delete

Now we implement a Vue component to delete data with Axios Delete method:

  • delete a Tutorial
  • delete all Tutorials
<template>
    <div class="card">
      <div class="card-header">Vue Axios DELETE - BezKoder.com</div>
      <div class="card-body">
        <div class="input-group input-group-sm">
          <button class="btn btn-sm btn-danger" @click="deleteAllData">Delete All</button>

          <input type="text" ref="delete_id" class="form-control ml-2" placeholder="Id" />
          <div class="input-group-append">
            <button class="btn btn-sm btn-danger" @click="deleteDataById">Delete by Id</button>
          </div>

          <button class="btn btn-sm btn-warning ml-2" @click="clearDeleteOutput">Clear</button>
        </div>    
        
        <div v-if="deleteResult" class="alert alert-secondary mt-2" role="alert"><pre>{{deleteResult}}</pre></div>      
      </div>
    </div>
  </div>
</template>

<script>
import http from "./http-common";

export default {
  name: "App",
  data() {
    return {
      putResult: null,
      deleteResult: null,
    }
  },
  methods: {
    fortmatResponse(res) {
      return JSON.stringify(res, null, 2);
    },

    async deleteAllData() {
      try {
        const res = await http.delete("/tutorials");

        const result = {
          status: res.status + "-" + res.statusText,
          headers: res.headers,
          data: res.data,
        };

        this.deleteResult = this.fortmatResponse(result);
      } catch (err) {
        this.deleteResult = this.fortmatResponse(err.response?.data) || err;
      }
    },

    async deleteDataById() {
      const id = this.$refs.delete_id.value;

      if (id) {
        try {
          const res = await http.delete(`/tutorials/${id}`);

          const result = {
            status: res.status + "-" + res.statusText,
            headers: res.headers,
            data: res.data,
          };

          this.deleteResult = this.fortmatResponse(result);
        } catch (err) {
          this.deleteResult = this.fortmatResponse(err.response?.data) || err;
        }
      }
    },

    clearDeleteOutput() {
      this.deleteResult = null;
    }
  }
}
</script>

The result could be like this:

vue-axios-delete-example

Conclusion

With this Vue Axios example, you’ve known many ways to make GET/POST/PUT/DELETE request using axios library (with headers, params, body…) in a Vue.js component.

Instead of Axios, you can also use Javascript Fetch API. Kindly visit:
Vue Fetch example – Get/Post/Put/Delete with Rest API

Happy Learning! See you again.

Source Code

The complete source code for this tutorial can be found at Github.

Further Reading

One thought to “Vue Axios example – Get/Post/Put/Delete with Rest API”

  1. I was searching for a node.js framework in detail and I am in your post and learning something new your post so, thank you for this post and share detail about node.js frameworks on your next post. And Thank you for this amazing information.

Comments are closed to reduce spam. If you have any question, please send me an email.