Vue.js REST API Example With Axios [Ajax Alternative]

This Vue.js REST API example with axios will show you how to get/send the data from/to remote server, databases and third-party libraries.

You might aware that Angular has HTTP, jQuery has $.AJAX, similiarly in Vue.js we can use Axios for REST API calls to get and send the data.

Vue.js REST API Example With Axios

Vue.js Axios is an amazing HTTP client library, it uses the promises by default and runs both on client and server. That’s why it’s helpful while rendering the data from server.

It’s very easy to use API with the combination of async/await as it provides promises by default.

Now, let’s get started with an example with Axios, and see how we can install and use it with our Vue.js app.

1. Install Axios In Vue.js App

Suggested, if you’re beginner with Vue.js

There’re multiple ways to start using Axios in your Vue.js app, it completely depends on you how you install from the ways listed below.

Using npm (Recommended):

npm install axios

OR Using bower:

bower install axios

OR Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

After installing, let’s use Axios library in Vue.js components.

2. Usage of Axios in Vue.js

Now, we’re ready to use Axios in our Vue.js app to call REST API with different available methods like GET, POST, DELETE, etc

First of all, we need to import axios in our component to start using it.

import axios from 'axios';

Next, just start using the methods with axios as shown below.

3. Vue.js GET Request Example with Axios

GET request generally use to populate the data from the server to get it rendered on the client side.

The following code snippet will call the GET request with axios and call the method user with the ID as parameter.

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Now, let’s see an example how we can render the data by fetching it by axios GET request.

ExampleComponent.vue

<template>
  <ul v-if="posts && posts.length">
    <li v-for="post of posts">
      <p><strong>{{post.title}}</strong></p>
      <p>{{post.body}}</p>
    </li>
  </ul>
  <ul v-if="errors && errors.length">
    <li v-for="error of errors">
      {{error.message}}
    </li>
  </ul>
</template>

<script>
//Import axios
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  getPostsData() {
    axios.get(`http://jsonplaceholder.typicode.com/posts`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

4. Vue.js POST Method Example with Axios

Same as GET, you can use POST method with axios to push the data to the server or database.

So, let’s push the user data with multiple parameters.

axios.post('/user', {
   firstName: 'Mohit',
   lastName: 'Tanwani'
 })
 .then(function (response) {
   console.log(response);
 })
 .catch(function (error) {
   console.log(error);
 });

This post request will push the data to server at user method with users parameters, i.e. firstName and lastName.

Now, let’s take a Vue component to push the data to server using REST API.

ExampleComponent.vue

This component will post the user’s input data to the server using axios POST method.

<template>
  <input type="text" v-model="postBody" @change="postUserData()"/>
  <ul v-if="errors && errors.length">
    <li v-for="error of errors">
      {{error.message}}
    </li>
  </ul>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      postBody: '',
      errors: []
    }
  },

  // Pushes posts to the server when called.
  postUserData() {
    axios.post(`http://jsonplaceholder.typicode.com/posts`, {
      body: this.postBody
    })
    .then(response => {})
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

It’s quit easy, right?

Same as GET and POST methods, you can easily use other methods like POST, PUT, PATCH, and DELETE, find the document over here.

5. A Common HTTP Instance for Axios

Axios allows us to create a global instance and provides the ability to call the multiple methods via sharing a common signature.

Basically, it’s very useful when your all the REST API calls are to a same remote server or data, it will be very easy for you to create a common method and use the instance to call the REST API methods.

Also, you can share headers like authentication header with the common method.

Now, let’s create an HTTP instance for axios to use it throughout our Vue.js app to call REST APIs.

common.js

import axios from 'axios';

export const HTTP = axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`,
  headers: {
    Authorization: 'Bearer {token}'
  }
})

Now, to use this HTTP object, you just need to import it in your components and start using the methods.

ExampleComponent.vue

<script>
//Import HTTP global instance create in common.js
import {HTTP} from './common';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  getData() {
    HTTP.get(`posts`)
    .then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }

  saveData{
  	HTTP.post(`posts`, {
      body: this.postBody
    })
    .then(response => {})
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

That’s it! It’s the easiest way to call Vue.js REST API with axios.

Moreover, if you’d get more information, you can visit Axios GitHub Repository.

Finally, I hope you loved this Vue.js REST API example with Axios and it’s helpful to you.

Don’t forget to share with your friends on below social media!

Mohit Tanwani

Mohit Tanwani is an enthusiast Techie, a blogger, and IT geek. He has been crazily involved in the industry for 5 years.

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of