Tutorial How to Consume APIs Using Axios and Vue.js

Tutorial How to Consume APIs Using Axios and Vue.js

In this tutorial you will learn how to access the API using Vue.js and Axios.

Not only that, you will also learn how to use Vuetify so that the user interface (UI) becomes more interactive and responsive.

Today, I am going to share with you everything you need to know to access the API with the GET, POST, PUT, and DELETE methods.

(Step-by-Step)

Let’s get started.

 

#1. Preparation

This is important!

To create an application using vue.js, you can do it in 2 ways, namely by using the Vue-CLI or using the CDN/vue.js file.

In this tutorial, I will use a vue.js file to make it easier to understand for beginners.

Here are some things you need to prepare:

1. Vue.js

To get vue.js, please visit the following URL:

https://vuejs.org/js/vue.min.js

Then Select All (Ctrl + A) and Copy (Ctrl + C) all the code, save it as vue.min.js.

In this tutorial, I saved it in a directory:

C:/xampp/htdocs/api

That means I have created a "api" folder in the “htdocs” folder.

You can save it anywhere, not necessarily in "htdocs", you can even save it on the "desktop", because this application does not run on the Apache server or something like that.

2. Axios

Axios is a Promise based HTTP Client for browsers or node.js.

Axios makes it easy to handle AJAX requests.

In this tutorial, you don't need to download Axios, because we will only be using the Axios CDN.

3. Vuetify

Vuetify is a User Interface (UI) library for vue.js with an elegant design.

By using vuetify, you can quickly create an application with an elegant and responsive user interface without thinking about CSS or Javascript.

In this tutorial, you also don't need to download Vuetify, because we will only be using the vuetify CDN.

4. API

In this tutorial, I will use the API I created earlier using CodeIgniter.

If you haven't seen my previous tutorial, I recommend taking a look here: "Tutorial How to Create a RESTful API Using CodeIgniter 4."

You don't have to create it from scratch, just download the source code, then run it on your web server with the following command in terminal/cmd:

php spark serve

Let's move on!

 

#2. Create a file called "index.html"

Create a file called "index.html", at the same folder with the vue.min.js file.

In this case, I placed it in the directory:

C:/xampp/htdocs/api

Like the following picture:

api-directory

Then open the “index.html” file using a code editor, here I use Visual Studio Code and then type the following code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
    <title>Product Lists</title>
</head>

<body>
    <div id="app">
        <v-app>
            <v-main>
                <v-container>
                    <!-- Modal Add New Product -->
                    <template>
                        <v-dialog v-model="dialogAdd" persistent max-width="600px">
                            <template v-slot:activator="{ on, attrs }">
                                <v-btn color="primary" dark v-bind="attrs" v-on="on">
                                    Add New
                                </v-btn>
                            </template>
                            <v-card>
                                <v-card-title>
                                    <span class="headline">Add New Product</span>
                                </v-card-title>
                                <v-card-text>
                                    <v-container>
                                        <v-row>
                                            <v-col cols="12">
                                                <v-text-field label="Product Name*" v-model="productName" required>
                                                </v-text-field>
                                            </v-col>
                                            <v-col cols="12">
                                                <v-text-field label="Price*" v-model="productPrice" required>
                                                </v-text-field>
                                            </v-col>
                                        </v-row>
                                    </v-container>
                                    <small>*indicates required field</small>
                                </v-card-text>
                                <v-card-actions>
                                    <v-spacer></v-spacer>
                                    <v-btn color="blue darken-1" text @click="dialogAdd = false">Close</v-btn>
                                    <v-btn color="blue darken-1" text @click="saveProduct">Save</v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-dialog>
                    </template>

                    <!-- Modal Update Product -->
                    <template>
                        <v-dialog v-model="dialogEdit" persistent max-width="600px">
                            <v-card>
                                <v-card-title>
                                    <span class="headline">Update Product</span>
                                </v-card-title>
                                <v-card-text>
                                    <v-container>
                                        <v-row>
                                            <v-col cols="12">
                                                <v-text-field label="Product Name*" v-model="productNameEdit" required>
                                                </v-text-field>
                                            </v-col>
                                            <v-col cols="12">
                                                <v-text-field label="Price*" v-model="productPriceEdit" required>
                                                </v-text-field>
                                            </v-col>
                                        </v-row>
                                    </v-container>
                                    <small>*indicates required field</small>
                                </v-card-text>
                                <v-card-actions>
                                    <v-spacer></v-spacer>
                                    <v-btn color="blue darken-1" text @click="dialogEdit = false">Close</v-btn>
                                    <v-btn color="blue darken-1" text @click="updateProduct">Update</v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-dialog>
                    </template>

                    <!-- Modal Delete Product -->
                    <template>
                        <v-dialog v-model="dialogDelete" persistent max-width="600px">
                            <v-card>
                                <v-card-title>
                                    <span class="headline"></span>
                                </v-card-title>
                                <v-card-text>
                                    <v-container>
                                        <v-row>
                                            <h2>Are sure want to delete {{ productNameDelete }} ?</h2>
                                        </v-row>
                                    </v-container>
                                </v-card-text>
                                <v-card-actions>
                                    <v-spacer></v-spacer>
                                    <v-btn color="blue darken-1" text @click="dialogDelete = false">No</v-btn>
                                    <v-btn color="info darken-1" text @click="deleteProduct">Yes
                                    </v-btn>
                                </v-card-actions>
                            </v-card>
                        </v-dialog>
                    </template>

                    <template>
                        <v-simple-table>
                            <template v-slot:default>
                                <thead>
                                    <tr>
                                        <th class="text-left">#</th>
                                        <th class="text-left">Product Name</th>
                                        <th class="text-left">Price</th>
                                        <th class="text-left">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(product, index) in products" :key="product.product_id">
                                        <td>{{ index + 1 }}</td>
                                        <td>{{ product.product_name }}</td>
                                        <td>{{ product.product_price }}</td>
                                        <td>
                                            <v-btn color="info" depressed small @click="getEdit(product)">
                                                Edit
                                            </v-btn>
                                            <v-btn color="error" depressed small @click="getDelete(product)">
                                                Delete
                                            </v-btn>
                                        </td>
                                    </tr>
                                </tbody>
                            </template>
                        </v-simple-table>
                    </template>

                </v-container>
            </v-main>
        </v-app>
    </div>

    <script src="vue.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="main.js"></script>

</body>

</html>

In the code above, you can see that it's just normal html code.

There are several things you need to pay attention to in the code.

We call the vuetify CSS file via CDN with the following code:

<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

Apart from that, we also call some javascript files with the following code:

<!-- Include file vue js -->
<script src="vue.min.js"></script>
<!-- Include file vuetify js -->
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>
<!-- Include file axios js -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Include file main js -->
<script src="main.js"></script>

In the code above, we call the vue.min.jsvuetify.js (CDN), axios.min.js (CDN), and the main.js files.

The file "main.js" is a javascript file which we will create to handle all the javascript code for our application.

 

#3. Create a file called "main.js"

Create a file called "main.js", then place a folder with the files vue.min.js and index.html.

In this case, I placed it in the directory:

C:/xampp/htdocs/api

Like the following picture:

main-js

Then open the “main.js” file using a code editor and then type the following code:

new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    data: {
        products: '',
        productName: '',
        productPrice: '',
        dialogAdd: false,
        dialogEdit: false,
        dialogDelete: false,
        productIdEdit: '',
        productNameEdit: '',
        productPriceEdit: '',
        productIdDelete: '',
        productNameDelete: ''
    },
    created: function () {
        this.getProducts()
    },
    methods: {

        // Get Product
        getProducts: function () {
            axios.get('http://localhost:8080/products')
                .then(res => {
                    this.products = res.data;
                })
                .catch(err => {
                    // handle error
                    console.log(err);
                })
        },

        // Create New product
        saveProduct: function () {
            axios.post('http://localhost:8080/products', {
                    product_name: this.productName,
                    product_price: this.productPrice
                })
                .then(res => {
                    // handle success
                    this.getProducts();
                    this.productName = '';
                    this.productPrice = '';
                    this.dialogAdd = false;
                })
                .catch(err => {
                    // handle error
                    console.log(err);
                })
        },

        // Get Edit and Show data to Modal
        getEdit: function (product) {
            this.dialogEdit = true;
            this.productIdEdit = product.product_id;
            this.productNameEdit = product.product_name;
            this.productPriceEdit = product.product_price;
        },

        // Get Delete and Show Confirm Modal
        getDelete: function (product) {
            this.dialogDelete = true;
            this.productIdDelete = product.product_id;
            this.productNameDelete = product.product_name;
        },

        // Update Product
        updateProduct: function () {
            axios.put(`http://localhost:8080/products/${this.productIdEdit}`, {
                    product_name: this.productNameEdit,
                    product_price: this.productPriceEdit
                })
                .then(res => {
                    // handle success
                    this.getProducts();
                    this.dialogEdit = false;
                })
                .catch(err => {
                    // handle error
                    console.log(err);
                })
        },

        // Delete Product
        deleteProduct: function () {
            axios.delete(`http://localhost:8080/products/${this.productIdDelete}`)
                .then(res => {
                    // handle success
                    this.getProducts();
                    this.dialogDelete = false;
                })
                .catch(err => {
                    // handle error
                    console.log(err);
                })
        }
    }
})

In the code above, there are several functions, namely getProduct, saveProduct, updateProduct, and deleteProduct.

getProduct functions to retrieve data from the API with the GET method.

saveProduct functions to store data via the API with the POST method.

updateProduct functions to update data via the API with the PUT method.

deleteProduct functions to delete data via the API with the DELETE method.

 

#4. Testing

Before doing the test, make sure the API is running well and can be accessed via POSTMAN.

Then open the file "index.html" through the browser, if running with it will look like the following image:

product-lists

1. Add New Data

Click the "Add New" button to add new data, it will look like the following form:

add-product

Enter the Product Name and Price, then click the "SAVE" button to save the data.

If the data is saved successfully, you will see additional data as follows:

product-added

2. Update Data

Click on one of the "EDIT" buttons to edit the data, then a form will appear as follows:

edit-product

Edit Product Name or Price, then click "UPDATE" button to update data.

If the data is successfully updated, it will show changes in the data as follows:

product-edited

3. Delete Data

Click on one of the "DELETE" buttons to delete data, a confirmation will appear as follows:

delete-product

Click "YES" to delete data.

If the data is successfully deleted, you will see a reduction in data on the product list.

 

Conclusion:

In this tutorial, you have learned how to access the API using Vue.js and Axios.

You have also learned to use vuetify to create a beautiful user interface (UI).

So what are you waiting for, Let's Coding!

Download Source Code

Share:



Sponsorship:


Recommended for you


Comments (0)

Leave a Comment