Although there are multiple ways once can consume a REST Api in VueJS like using javascript fetch API, vue resource, jquery's ajax api, However a third-party library named Axios is usually the most recommended and most used way to communicate with the API's in VueJS.

Axios is a great HTTP client library. Similar to javascript fetch API, it uses Promises by default. It’s also quite easy to use with Vue.

In this post let's see how easy it is to consume a REST API using Axios.

Installation

Axios can be installed using Yarn or NPM

#yarn
yarn add axios

#npm
npm install axios

Populating Data with a GET Request

For the demonstration, I will be using jsonplaceholder API. jsonplaceholder is an fake online test API. If you hit the URL it's /posts endpoint, it returns 100 posts in the JSON format.

[
    {
    userId: 1,
    id: 1,
    title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    body: "quia et suscipit
    suscipit recusandae consequuntur expedita et cum
    reprehenderit molestiae ut ut quas totam
    nostrum rerum est autem sunt rem eveniet architecto"
    },
    {
    userId: 1,
    id: 2,
    title: "qui est esse",
    body: "est rerum tempore vitae
    sequi sint nihil reprehenderit dolor beatae ea dolores neque
    fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis
    qui aperiam non debitis possimus qui neque nisi nulla"
    },
    ...
    ...

Once the page is loaded we will make use of axios to get the posts from the API, once we have the posts available we use the v-for directive to loop through the posts and print their title.

<template>
<div>
    <div v-for="post in posts" :key="post" class="post">
        {{post.title}}
    </div>
</div>
</template>

<script>
import axios from 'axios';


export default {
    name: 'consume-rest-api',
    data(){
        return{
            posts: null
        }
    },

    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>

<style scoped>
.post{
    margin: 20px;
}
</style>

Since Axios is promise-based library, we make a promise of what needs to be done if we get a successful response from the API and also we define a catch block if we receive an error response.

loop through result rest api vuejs

Comments