Learn to use API in Vue Js with Axios by making this simple quote web app
As you dive deep into programming you’ll see that API is used almost everywhere, so it’s important to know how to integrate API in your Vue js project.
In this article, we are going to learn how to fetch data from a third party API in Vue js with Axios by making a simple “quote of the day” web app.
Here project is simple and divided into two parts:
- first, we will use a quotes website API to fetch the data i.e, “quote” from their website.
- and second, we will display it into the webpage with Axios and Vue js.
I’m pretty sure most of you probably don’t know about Axios, so before we start, let me explain to you first …
What is Axios?
Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser. You can use this to fetch requests instead of the function.
To get the Quote we’ll use this API, which gives one new quote every day. It’s like a “quote of the day” thing.
http://quotes.rest/qod.json?category=inspire
If you access this URL in your browser you’ll see some data in JSON format, something like this:
We’ll access and filter the data and then display it on the webpage.
To use Axios and Vue Js, we have to first import them, here we’ll use their CDN to import them.
Paste this script tags in your head of your HTML file.
<!-- Vue js CDN --><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><!-- Axios CDN --><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
After that, we’ll create a div with id name app and under that, a Child div with a paragraph. here we’ll assign the paragraph tag with id name “author”.
Here in the h1 tag of div id=” app”, we have placed {{info}}
whose data value is assigned null now, and the same with {{author}}
as well.
So currently this HTML piece of code won’t show anything on the browser.
<body>
<div id="app"> <h1>{{ info }}</h1> <div> <p id="author"> - {{author}}</p> </div></div>
</body>
Now we’ll create a Vue instance
Here in the data section of Vue Js, there are two values
info
and author
, both values are null
right now.
Before we go any further we have to first understand…
what is mounted function is Vue JS
mounted()
is a predefined function called every time your component is loaded to the browser
Now in the methods section of Vue Js, when the mounted()
of VueJs activates Axios will make a GET request to API and from the API's response we’ll save quote’s value and author’s value into info
and author
.
The result will look something like this:
You can make it more awesome and lively by adding some CSS, here try this:
This will be the final result after adding CSS:
This is the whole code, you can go copy and run this code to see for yourself.
Happy Coding ❤
For any query you can message me on my Instagram at @slim.python