In this tutorial, we’ll look at how to use Axios in VueJS to contact the get and post method APIs. We will use a fake data for interacting with the API
Get Started:
Step 1:
Install Vue in your system and create a new project using CLI.
npm install -g @vue/cli
vue create api-call-demo
Step 2:
Install Axios in your project.
npm install axios
Step 3:
After that, import Axios into your component.
import axios from 'axios';
Step 4:
Call the API on the component creation lifecycle hook.
We’re going to use the GET method to make our first API call. To obtain data from an API, utilize the GET method.
created() { axios.get("https://fakestoreapi.com/products").then((response) => { this.products = response.data }); },
Your entire GET method API call code looks like this,
Call the POST method API:
axios.post("https://fakestoreapi.com/products", product).then((response) => { // 'product' = A product which you want to add this.products = response.data; });
Your entire POST method API call code looks like this,
After calling the API, We can now use the v-for directive to loop over the posts and show the data in the template.