The web is progressing fast with new technologies and libraries emerging every few months. Vue.js is one of the Javascript frameworks gaining immense popularity over the last few years. Initially launched in 2014, it derives inspiration from Angular but is very lightweight and ideal for building single-page web applications.
In this blog post, we are going to take a dig at integrating public APIs with a simple Vue.js application to fetch and display data on UI. In case you are wondering, here is an article on the concept of APIs that also covers the various types and categories of APIs supported by us at RapidAPI.
What is Vue.js?
According to the official documentation, Vue is a progressive framework for building user interfaces. It supports augmented rendering of the HTML markup through a template declaration bound to a data model. When the data model is updated, the browser’s HTML DOM also changes accordingly. Vuejs is a frontend-end framework, and hence it is implemented only in the view layer.
Evan You, a former Google and Meteor employee, created Vue.js. He wanted to extract the good parts of Angular, such as data binding and the data-driven way of dealing with the DOM (Document Object Model), without the heavy structure of Angular code. After close to two years of working on it, Evan You shared it on GitHub, in February 2014. Vue.js now boasts of over 160K stars on GitHub. It is one of the fastest-growing frameworks used in front-end web development.
Vue.js Components
Each Vue.js project is composed of smaller components. These form the individual building blocks of the complete application and enable abstraction and code reuse.
Here is an example of a Vue.js component.
A Vue.js Component consists of 3 parts;
- The HTML declaration
- The component definition
- The component style
The HTML Declaration
The HTML markup of the component is part of the HTML declaration. Usually, a <template> tag defines it and contains one or more child tags.
The Component Definition
Every Vue.js component has an Options object. It is a JSON object containing the following properties:
- el: This property contains the CSS selector of the DOM element, which is attached to the Vue component.
- data: The data defines an object that represents the internal data of the Vue component. It can also be a function that returns the data object.
- methods: The methods object contains a key-value pair of method names and their function definition. These are part of the Vue component’s behavior which the other component can trigger.
- computed: This contains an object which defines the getter and setter functions for computed properties of the Vue component. Computed properties affect a reactive update on the DOM whenever their value changes.
- props: This contains an array or object of properties specific to the Vue.js component, set at the time of invocation.
- watch: This object keeps track of changes in the value of any of the properties defined as part of ‘data‘ by setting up functions to watch over them.
For a complete list of the available properties for the Options object, check out the official Vue API docs.
The Vue.js component can be defined as a separate .vue file or within the <script> tag.
The Component style
This is pretty straight forward. The CSS rules for the elements of the component live here. These styles can either be scoped (limited to a particular component) or global.
Component Lifecycle
Vue.js follows a phased approach to initialize components through a set of lifecycle events. The Vue.js framework allows you to define hooks for performing tasks as part of these lifecycle events. The following “Lifecycle hooks” are some of the common lifecycle events of the components, starting even before creation, to post destruction.
Common Lifecycle hooks
- beforeCreate : This is the first lifecycle state. You can’t interact with any part of the component yet
- created : This is just after the creation of the component instance. You can now interact with the component, ie. the data properties, watchers, computed properties, but you still can’t access the DOM. Usually, data is fetched from your database or API in this lifecycle hook.
- beforeMount : The component is compiled at this stage, but it is yet to be rendered on to the screen.
- mounted : This is after the component has been mounted. Now, you can access the $el method and play around with the content inside HTML elements. At this stage the component becomes fully interactive.
- beforeUpdate : Whenever changes are made to data or the DOM, right before that, this lifecycle hook is called. This is helpful when you need to log changes.
- updated : This is right after the changes are made to the DOM or the data. Here you can perform operations dependent on the change in the DOM.
- beforeDestroy : This is right before the component is destroyed and is the last instance of the fully functional DOM. You can do the necessary closing operations.
- destroyed : This is kind of similar to the beforeCreate hook where the component is not functional and no data properties, watchers, computed properties, events can be accessed.
For a complete list of lifecycle hooks, see the official Vue API docs.
How To Make an API Call with Vue.js (Fetch Data from API using Vue.js)
We will now build a simple app to show you how to make an API call with Vue.js. Let’s start with the prerequisites.
Prerequisites
Let’s make sure that you are fully prepared to advance and build out API calls using Vue.js.
Below are a few prerequisites:
- RapidAPI account. It’s free to sign-up, and the API we use in the example below is free as well!
- An internet connection and a browser that isn’t Internet Explorer. IE has some compatibility issues that can be easily avoided. It is recommended to use Firefox or Google Chrome.
- A reputable code editor such as Sublime Text.
- A general understanding of HTML, CSS, and Javascript.
1. Create the Basic Skeleton Of a Web Application
First, you need to create a basic HTML declaration that serves as the frontend UI of the web application.
Start with a new project directory named vue-api-call. This directory is the root directory under which all the source files of the project will reside.
Open the code editor and create a new file ‘index.html’ inside the root directory and add the following code.
<!DOCTYPE html> <html lang="en"> <head> <!-- Responsive + Encoding Meta Tag --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Stylesheet --> <link href = "styles.css" rel = "stylesheet"> <!-- Title --> <title>Vue.JS API Call</title> </head> <body> <div id="main"> <h1> Vue.JS API Call Example</h1> </div> </body> <!-- Vue and Custom JavaScript --> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> <script src = "scripts.js"></script> </html>
This HTML declaration defines a web page with a <div> tag containing an <h1> title tag.
It also imports a stylesheet named ‘styles.css’ and a JavaScript file named ‘scripts.js’.
Additionally, it also imports the Vue.js library from the official CDN location.
2. Create the Basic Vue.js Component
A separate file ‘scripts.js’ defines the Vue.js component. Create a new file named ‘scripts.js’ in the root directory and add the following code.
const app = new Vue({ el: '#main', data: { result: “ ”, responseAvailable: false, apiKey: '<YOUR_RAPIDAPI_KEY>' }, methods: { fetchAPIData( ) { } } })
This is a barebones Vue.JS component definition with an Options object containing the ‘el’, ‘data’ , and ‘methods’ properties.
The ‘el’ property points to the “#main” selector which is the id of the top-level <div> element in the HTML.
The ‘data’ contains three data variables that you will use later for displaying text returned from the API in the HTML.
The ‘methods’ property defines a single function fetchAPIData( ). This is currently left blank but will be defined in the subsequent steps.
With the ‘el’ bound to the CSS selector of the top-level <div> element, this Vue.js component is attached to the <div> element.
3. Create the Stylesheet for the Vue Component
Create a new file named ‘styles.css’ in the root directory. Leave the file empty for now. We will come back to it later.
4. Add API call to Vue.js Component
You will now edit the ‘script.js’ file to add the API call to the Vue.js component.
Before that, you must decide on the API. The choice of API is dependent on the application that you are building, or the API functionality that you are relying upon to be fulfilled by the API.
For this Vue.js example, we have chosen the Jokes Database API. It returns a joke every time you call it and is very simple to use. The idea here is to have a simple web page that can display a joke every time the user clicks on a button.
You can access the API console and subscribe to the API by opting for the Basic subscription that gives you 100 calls to this API per month. However, this API enforces a rate limit of one call per hour. If you want to have some fun with jokes while building this Vue.js app, then you can subscribe to the unlimited Mega plan for only $USD 1.50 per month.
The Jokes Database API supports a single endpoint.
Upon triggering this API, it retrieves a random joke from the Jokes Database and returns that in the API response.
If you take a look at the code snippets provided by the API console, you can see the sample code for invoking an AJAX call on this API using the Javascript fetch( ) function.
Vue.js does not provide its internal API for AJAX calls. It doesn’t need to since it’s a component framework for building web applications. It can still rely on the standard W3C JavaScript APIs or third-party libraries to provide supporting features.
You can use the JavaScript fetch( ) call within the Vue.js component to make the API call. Open the ‘scripts.js’ file and add the following code inside the fetchAPIData( ) method.
this.responseAvailable = false; fetch("https://jokes-database.p.rapidapi.com/", { "method": "GET", "headers": { "x-rapidapi-host": "jokes-database.p.rapidapi.com", "x-rapidapi-key": this.apiKey } }) .then(response => { if(response.ok){ return response.json() } else{ alert("Server returned " + response.status + " : " + response.statusText); } }) .then(response => { this.result = response.body; this.responseAvailable = true; }) .catch(err => { console.log(err); });
The fetch( ) call returns a Promise. In case of a success response, you retrieve the API response as a JSON object by calling the json( ) on the response object, which returns yet another Promise.
This Promise resolves to the response object which retrieves the joke from the body property of the API response object and assigns it to the result data variable of the Vue.js component.
Another thing to note is the use of responseAvailable variable. This is used as a flag to indicate the availability of the API response. It is reset to false at the beginning. It is also used to control the display of the joke on the UI, as you will see in the next step.
Now that the API integration is done, you need a way to trigger this API. Our goal is to display a joke upon pressing a button on the web page. Since the API is part of the fetchAPIData( ) method, you can update the HTML declaration to define a button and assign the “click” event of the button to fetchAPIData( ) method.
Open the ‘index.html’ file and add the following lines below the <h1> tag.
<button type = "button" id = "get-joke" @click = "fetchAPIData">Get a Joke!!</button>
Save the file and open it in a web browser.
Upon clicking on the button, the fetchAPIData( ) method is triggered, which will, in turn, invoke the Jokes Database API. You can verify this by checking the Network tab on your browser’s developer console.
5. Display API Data In Vue.js Component
Now you know how to trigger the Vue.js component through user interaction. Then comes the last part on updating the Vue.js component’s UI based on the data retrieved from API.
As you saw in the fetchAPIData( ) method, the API response is stored in the result variable under the data object.
You have to display the content of the result variable in the HTML. Vue.js framework follows the Angular way of declarative control flow syntax to decide on the rendering of HTML.
In the Vue.js Component that you have defined, the responseAvailable flag is set whenever the API response is received. Hence, you can use this flag to decide on rendering the result string containing the joke.
Open the ‘index.html’ file and add the following HTML snippet below the <button> tag.
<div v-if = "responseAvailable == true"> <hr> <p> <i>{{result}}</i> </p> <hr> </div>
Vue.js defines a few directives for conditional rendering of the HTML elements. In this case, the directive that you just used is v-if. It is like the if condition available in almost all programming languages.
As per the above HTML code, the <div> element, including all of its child elements, will be rendered only if the responseAvailable value is true.
The result containing the joke string is substituted with its value using the {{ }} syntax.
Save the ‘index.html’ and open it in the browser. Now you should see a joke pop up every time you hit the “Get a Joke !!” button.
6. Styling the Vue.js Component
You have already defined the ‘styles.css’ file earlier and imported it into ‘index.html’. This file can contain the standard CSS selectors to style the individual elements.
For now, to keep things simple, let’s add a blue color to the joke text so that it stands out.
Open the ‘styles.css’ file and add the following CSS style for the <p> tag.
p { color:blue; }
Refresh the browser tab to reload ‘index.html’. Now you should see the joke text in blue.
Further Considerations
The example Vue.js app shown in this tutorial is for demo purposes, and it omits many complexities in building a real-world app. Hence, it is worthwhile to list them so that you are aware of them while embarking upon building a complete Vue.js based application.
- Vue.js project structure – This app uses a single Vue component. However, while building complete Vue.js based single-page applications, you will have several Vue.js components. In such cases, using the Vue CLI to provide the scaffolding for the entire project and generating individual *.vue files for each component is the best option.
- Security – The API key is a private credential that belongs to you as the app developer. You must not expose it by just defining it as a data variable in the code. To solve this problem, you should either consider server side rendering, or some form of obfuscation, which can secure the key from being revealed as plain text.
Vue.js API Call Examples
You can also check out some of our published API tutorial posts with Vue.js
This is a simple Vue.js app that uses the Mashvisor API to search and display AirBnB rentals in a given city.
Single Page Application with Vue.js
This is a SPA built with Vue.js. It uses the Vue CLI and has multiple Vue.js components to render a Currency conversion app using the Fixer Currency API.
Conclusion
Adding APIs to Vue.js is not that complex. After all, you are using the same techniques that are available in Javascript. The only additional things to learn are the Vue.js component structure and the rendering directives.
The example used in this tutorial was straightforward, but we hope you can sharpen your skills with the help of the other links and the Vue.js documentation references shared above.
If you have any questions, please leave a comment!
FAQ
What is Vue.js?
According to the official documentation, Vue is a progressive framework for building user interfaces. It supports augmented rendering of the HTML markup through a template declaration bound to a data model. When the data model is updated, the browser’s HTML DOM also changes accordingly. Vuejs is a frontend-end framework, and hence it is implemented only in the view layer.
What are Vue.js Components?
Each Vue.js project is composed of smaller components. These form the individual building blocks of the complete application and enable abstraction and code reuse. A Vue.js Component consists of 3 parts; The HTML declaration, The component definition, and The component style.
How to Make an API Call with Vue.js?
1. Create basic Skeleton of Web Application, 2. Create the basic Vue.js Component, 3. Create the Stylesheet for the Vue Component, 4. Add API call to Vue.js Component, 5. Display API data in Vue.js Component, 6. Style the Vue.js Component
kldsklsddskljfsdkj says
Please provide full source code, ie: a zip file.
John Pitchko says
This was really helpful, thanks!
Note I received a `Illegal syntax` error around the `result: “”` line when I pasted your code into my editor. I think the double-quotes are using the wrong unicode character. I deleted them and replaced them with single quotes and the error disappeared.
Shyam Purkayastha says
Thanks John. Glad that it was of some help to you.
Really appreciate your effort in pointing the error.
Cameron says
The Jokes API link in this article gives a 404.
Jolly says
What would be useful for me is what if you have a REST backend on the same server as the vuejs front-end? My impression is that routing will require a fair amount of extraneous stuff to get it to work.