VueJoy

About

VueJs REST API using Axios

Nowadays, a common architecture for a web application is the client/server model. A framework like Angular has a built-in HTTP API called the HTTP module. With VueJs, you must use a third-party library. Axios is a great HTTP client library that is highly recommended for that. It uses promises by default and runs on both the client and the server.

Installation

First, install Axios:

yarn add axios

We will use dummy data from jsonplaceholder, a service to fake a server, that will help us manipulate dummy data. Our data are posts with comments.

Get Posts with a GET request

let's see an example of GET request to get all the posts.

import axios from 'axios'

export default {
  name: 'app',
  data () {
    return {
      posts: []
    }
  },
  created() {
    axios.get('http://jsonplaceholder.typicode.com/posts').then((response) => {
      this.posts = response.data
    })
    .catch((e) => {
      console.error(e)
    })
  }
}

We are making a GET request using Axios in the created hook, which means that when the component is created, we are doing the request, then with the response of the request, we are setting post.

In our template, we are displaying each post's title and body:

<ul v-if="posts && posts.length">
  <li v-for="post of posts" v-bind:key="post.id">
    <p><strong>{{post.title}}</strong></p>
    <p>{{post.body}}</p>
  </li>
</ul>

Great, we have succeed to get all the posts!

Add a new post with a POST request

Now, let's see how to create a post thanks to a POST request.

We will use a small form to create a post. Add this to your template:

<input type="text" v-model="postTitle" placeholder="title"/>
<input type="text" v-model="postBody" placeholder="body"/>
<input type="button" @click="createPost()" value="submit">

In the component data, add this:

postBody: null,
postTitle: null,

And to finish, the most important thing, the createPost method:

createPost () {
  axios.post('http://jsonplaceholder.typicode.com/posts', {
    title: this.postTitle,
    body: this.postBody
  }).then((response) => {})
  .catch((e) => {
    console.error(e)
  })
}

And that's it! You can do the same for a PATCH, PUT or DELETE request.

Create a base instance

Axios offer the possibility to create a base instance, that is useful to share a common base URL and configuration in an instance. In our example, we won't need to repeat the URL. In another case, you can use a base instance to pass a token.

Example:

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

So let's adapt our example, add this to your main.js file:

import axios from 'axios'

const base = axios.create({
  baseURL: 'http://jsonplaceholder.typicode.com'
})

Vue.prototype.$http = base

This will allow us to use Axios in our component this.$http and without needing to type the whole URL, that is really convenient!

We can now change our component:

created() {
  this.$http.get('posts').then((response) => {
    this.posts = response.data
  })
  .catch((e) => {
    console.error(e)
  })
},
methods: {
  createPost () {
    this.$http.post('posts', {
      title: this.postTitle,
      body: this.postBody
    }).then((response) => {})
    .catch((e) => {
      console.error(e)
    })
  }
}

That's it for Axios! As always, you can find the source code on Github.