Tutorial

How To Configure Vue.js REST API Consumption with Axios

Updated on January 11, 2021
authorauthor

Joshua Bemenderfer and Bradley Kouchi

How To Configure Vue.js REST API Consumption with Axios

Introduction

In Vue 2.0, the developers decided that having a built-in HTTP client module was rather redundant and could be better serviced by third-party libraries. The alternative most frequently recommended is Axios.

Axios is an HTTP client library. It uses promises by default and runs on both the client and the server, which makes it appropriate for fetching data during server-side rendering. Because it uses promises, you can combine it with async/await to get a concise and easy-to-use API.

In this article, you’ll explore adding Axios to a Vue.js project for tasks involving populating data and pushing data. You will also learn about creating a reusable base instance.

Prerequisites

To follow along with this article, you will need:

Installing and Importing axios

To begin, you must install Axios.

You can install Axios with npm:

  1. npm install axios --save

Or with Yarn:

  1. yarn add axios

When adding Axios to your Vue.js project, you will want to import it:

import axios from 'axios';

Next, we will use axios.get() to make a GET request.

Populating Data with a GET Request

You can use Axios directly in your components to fetch data from a method or lifecycle hook:

ExampleComponentGet.vue
<template>
  <div>
    <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>
  </div>
</template>

<script>
import axios from 'axios';

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

  // Fetches posts when the component is created.
  created() {
    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>

The async/await version would look like this:

ExampleComponentGet.vue
<!-- ... template code ... -->

<script>
import axios from 'axios';

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

  // Fetches posts when the component is created.
  async created() {
    try {
      const response = await axios.get(`http://jsonplaceholder.typicode.com/posts`)
      this.posts = response.data
    } catch (e) {
      this.errors.push(e)
    }
  }
}
</script>

This code will retrieve "posts" from JSONPlaceholder and populate an unordered list with the "posts". Any "errors" encountered will appear in a separate unordered list.

Next, we will use axios.post() to make a POST request.

Pushing Data with a POST Request

You can use Axios to send POST, PUT, PATCH, and DELETE requests.

Note: You will not want to send requests on every input event. Consider using throttling or debouncing.

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

<script>
import axios from 'axios';

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

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

The async/await version would look like this:

ExampleComponentPost.vue
<!-- ... template code ... -->

<script>
import axios from 'axios';

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

  methods: {
    // Pushes posts to the server when called.
    async postPost() {
      try {
        await axios.post(`http://jsonplaceholder.typicode.com/posts`, {
          body: this.postBody
        })
      } catch (e) {
        this.errors.push(e)
      }
    }
  }
}
</script>

This code creates an input field that will submit content to JSONPlaceholder. Any errors encountered will appear in an unordered list.

Next, we will use axios.create() to make a base instance.

Creating a Common Base Instance

A frequently overlooked but very useful capability Axios provides is the ability to create a base instance that allows you to share a common base URL and configuration across all calls to the instance. This comes in handy if all of your calls are to a particular server or need to share headers, such as an Authorization header:

http-common.js
import axios from 'axios';

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

You can now use HTTP in your component:

ExampleComponentBase.vue
<template>
  <div>
    <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>
  </div>
</template>

<script>
import { HTTP } from './http-common';

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

  created() {
    HTTP.get(`posts`)
    .then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

This code uses the configuration established in http-common.js and connects to JSONPlaceholder with the Authorization header. It retrieves the posts and catches any errors.

Conclusion

In this article, you were introduced to using Axios for populating data and pushing data. And also how to create a reusable base instance. That’s just scratching the surface of what Axios can do.

Visit the GitHub repository for more information and documentation on Axios.

If you’d like to learn more about Vue.js, check out our Vue.js topic page for exercises and programming projects.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Joshua Bemenderfer

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.