Consuming a Rest API with Axios in Vue.js - TechvBlogs

Consuming a Rest API with Axios in Vue.js

Learn how to use Axios in a Vue.js project for data management tasks like populating and pushing data. Discover techniques for creating a reusable base instance for efficient API calls.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

1 year ago

TechvBlogs - Google News

Consuming a REST API with Axios in Vue.js involves making HTTP requests to a server from a Vue application using the Axios library. Axios is a popular, promise-based HTTP client that allows you to make GET, POST, PUT, and DELETE requests. In order to use Axios in a Vue.js application, you will need to install it as a dependency. Once installed, you can import and use it in your Vue components. To make a request to a REST API, you can use the axios.get() or axios.post() methods and pass in the URL and any necessary data or headers. The response from the server can then be used to update the state or render the data in the template.

Learn how to use Axios in a Vue.js project for data management tasks like populating and pushing data. Discover techniques for creating a reusable base instance for efficient API calls.

Consuming a Rest API with Axios in Vue.js

Installing and Importing Axios

You can install Axios with npm:

npm install axios --save

Or with Yarn:

yarn add axios

When incorporating Axios into your Vue.js project, it's necessary to import it.

import axios from 'axios';

Retrieving Data using GET Request in Vue.js with Axios

Fetching Data in Vue.js Components using Axios within methods or lifecycle hooks.

<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: []
    }
  },
  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 above code is an example of how to use Axios in a Vue.js component to fetch data from an API and display it in the template.

The template uses Vue directives to render the data fetched from the API. The v-if directive is used to check if  posts and errors data properties have values, and if so, it renders the appropriate elements. The v-for directive is used to loop through the posts array and display each post's title and body.

In the script section, Axios is imported and the component's data is defined to have an empty array for posts and errors. The created() lifecycle hook is used to make the GET request to the API using the axios.get() method, passing in the API endpoint URL. The then() method is used to handle the successful response and set the posts data property to the response data. The catch() method is used to handle any errors and push them to the errors data property.

This example demonstrates how to fetch data from an API using Axios and display it in a Vue.js component. It also shows how to handle errors and display them in the template.

The async/await the version would look like this.

<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: []
    }
  },
  async created() {
    await 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>

Submitting Data to an API using POST Request with Axios in Vue.js

You can use Axios to send POSTPUTPATCH, and DELETE requests.

<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 the version would look like this:

<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.
    async postPost() {
      await axios.post(`http://jsonplaceholder.typicode.com/posts`, {
        body: this.postBody
      })
      .then(response => {})
      .catch(e => {
        this.errors.push(e)
      })
    }
  }
}
</script>

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

Creating a Reusable Axios Base Instance in Vue.js for Efficient API Calls

Axios allows you to create a base instance that can be reused throughout your Vue.js application. This can be useful if you are making many API calls to the same server or if you need to include the same headers, such as an Authorization header, in all of your requests. Creating a base instance allows you to set a common base URL and configuration that will be used for all calls to the instance, which can make your code more organized and efficient.

axios.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:

<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 './axios';

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

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

Conclusion

Axios is a powerful tool that can be used in a Vue.js project to efficiently handle data management tasks such as populating and pushing data to a REST API. By importing Axios and using it directly in your components, you can easily fetch data from a method or lifecycle hook, and handle errors in a clean and organized manner. Additionally, by creating a reusable base instance, you can share a common base URL and configuration across all calls to the instance, making your code more efficient. Using Axios in a Vue.js project can greatly simplify data management and help you to easily and effectively interact with a REST API.

Comments (0)

Comment


Note: All Input Fields are required.