Vue Axios Tutorial – How To Create REST API with Vue and Axios

1633
views

Vue is one of the most popular and growing JavaScript frameworks. It comes with many awesome features that make it one of the best competitors in the current market. On the other side, APIs are one of the major parts of web development nowadays. Axios provides a really easy way to create an API. So in this Vue Axios tutorial, we will learn how to create REST API with Vue and Axios.

Vue Axios Tutorial

First of all, I am assuming you are familiar with Vue Js and Axios. So, I am just going to focus on Vue-Axios. However, if you are new to Vue or want to explore the features it provides, then I would suggest you to read this explanatory article, Vue Js advantages. It will not only explain the features of Vue Js but it will also give you reasons to love Vue.

Before starting, it is mentionable that Vue and Axios both are different. So, in order to bring the features of Axios to the Vue developers, a vue-axios module has been created. It works as a mediator between Vue and Axios.

Now, let’s move to the coding part.

Download & Setup Vue-Axios

First, create a new project and download the dependencies as follows.

vue init webpack myapp
cd myapp
npm install axios vue-axios --save

The first command will create a new project directory inside the current directory. In our case, we have named it myapp. However, this command will ask some questions before it starts to create the directory. Fill them properly and once it is created, go into the newly created project directory. Make sure that the router and all the required node modules are installed. Now, we need to install two dependencies first to use Axios inside of our Vue project.

Our project is now ready to work with. Now go to the src folder and open the main.js file in your favorite text editor. We need to import Vue and Vue-Axios here in order to access them globally in every component. You can import them as follows.

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

As you can see from the above code first we have imported two of those then we have registered them by using the use method.

So now our Vue-Axios project is set up and ready to proceed with. Now, let us create an API and see how it works.

Create the Vue-Axios API

First of all, remove the predefined Hello World component as we don’t need it.

Now, create two new components inside the components directory called display posts and view post. Both should have the extension vue.

Now open the display item file and paste the following code there.

<template>
<div class="posts">
<h1>Vue axios</h1>
<ul>
<li v-for="post in posts">
<div class="thumbnail">
<h3>{{ post.title }}</h3>
<p>{{ post.body }}</p>
<a v-bind:href="'/posts/'+ post.id" class="btn btn-primary">Read More</a>
</div>
</li>
</ul>
</div>
</template>

<script>
export default {
name: 'home',
data() {
return {
posts: []
}
},
created() {
this.axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
this.posts = res.data;
})
}
}
</script>

As you can see from the above code. First, come to the script part of the code. We have used the Axios inside of the created method so that it can be fired as soon as the component loads. Next, the Axios is sending a “get request” to a URL. The URL will return posts that are JSON formatted. Now, once it gets the data then we’ll be storing the data to a variable called posts.

‘Posts’ is an array type variable and the response that we are getting by the Axios request is an object-type. So, we use the object notation to get the data from the response and store it into posts array.

Web Design for Everybody (Basics of Web Development and Coding) from Coursera

Note that, actually its storing the data into a variable, however it’s just the front end part so the data will be removed once we refresh it or close the site. If you want to store the data permanently then you have to use a database.

Once we get the data we display it inside of the template. You can simply use the v-for directive to loop through the data in posts.

Now that this is done, let us extend it further to get a single post within our view post component.

Extending the vue axios API

Open the “view post component” and paste the following code and finally save it.

<template>
<div class="post">
<h1>Vue axios</h1>
<div class="thumbnail">
<h3>{{ post.title }}</h3>
<p>{{ post.body }}</p>
<a href="/" class="btn btn-primary">Back</a>
</div>
</div>
</template>

<script>
export default {
name: 'ViewPost',
data() {
return {
post: {}
}
},
created() {
// set the url of the API request
var postId = window.location.pathname.split("/").pop();
var url = "https://jsonplaceholder.typicode.com/posts/" + postId;
this.axios.get(url).then(res => {
this.post = res.data;
})
}
}

Okay, so, first of all, come to the created method inside of the script tag. We go to the current URL first, then we split it and used the “pop method” to get the last segment of the current URL.

Suppose that if you have clicked on post 4, then it will send a request to localhost:8000/posts/4. Hence, it is not what we want. What we really need, is to send a request to the https://jsonplaceholder.typicode.com/posts/4.

At the first line we are storing the post id the user has clicked. As we are running it locally and we want to send request to JSON place holders’ website, so we need to change the URL with the required one. Now as we want a post which has the id we have stored in the postId variable so we need to add the postId at the end of request url.

Finally, we have sent a “get request” to that URL and set the response data to our post variable. In this case, we are requesting a single post, so we have set the variable to object-type. Hence, we can now display the post inside of our template as shown above.

So that’s all guys, we have made our first API with Vue-Axios. Now, the one thing that we have missed is that we haven’t changed the router index.js file yet. So, open that file and update it as follows.

import Vue from 'vue'
import Router from 'vue-router'
import DisplayPosts from '@/components/DisplayPosts'
import ViewPost from '@/components/ViewPost'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'DisplayPost',
component: DisplayPost
},
{
path: '/posts/:id',
name: 'ViewPost',
component: ViewPost
}
]
}
)

So, as you can see we have imported the components and added them to the “routes array”. However, make sure the mode is set to “history”, otherwise the trailing characters will appear and your API wouldn’t work as expected.

Finally, run the command npm run dev and there you go.

I hope you love to work with Vue Js. So don’t forget to check out best frameworks for building mobile apps with vue.

I hope you have enjoyed this short yet informative Vue Axios tutorial. Feel free to leave your opinion in the comments section. Your opinion can help me to improve the content and help more people to learn.

Also Read: 10 Best Tech Gift Ideas for 2018!