Tutorial

How to Use Vue.js and Axios to Display Data from an API

Updated on August 1, 2022
How to Use Vue.js and Axios to Display Data from an API

Introduction

Vue.js is a front-end JavaScript framework for building user interfaces. It’s designed from the ground up to be incrementally adoptable, and it integrates well with other libraries or existing projects. This approach makes it a good fit for small projects as well as sophisticated single-page applications when used with other tooling and libraries.

An API, or Application Programming Interface, is a software intermediary that allows two applications to talk to each other. An API often exposes data that other developers can consume in their own apps, without worrying about databases or differences in programming languages. Developers frequently fetch data from an API that returns data in the JSON format, which they integrate into front-end applications. Vue.js is a great fit for consuming these kinds of APIs.

In this tutorial, you’ll create a Vue application that uses the Cryptocompare API to display the current prices of two leading cryptocurrencies: Bitcoin and Ethereum. In addition to Vue, you’ll use the Axios library to make API requests and process the obtained results. Axios is a great fit because it automatically transforms JSON data into JavaScript objects, and it supports Promises, leading to code that’s easier to read and debug. And to make things look nice, we’ll use the Foundation CSS framework.

Note: The Cryptocompare API is licensed for non-commercial use only. See their licensing terms if you wish to use it in a commercial project.

Prerequisites

Before you begin this tutorial, you’ll need the following:

Step 1 — Creating a Basic Vue Application

In this step, you’ll create a basic Vue application. We’ll build a single HTML page with some mocked-up data that we will eventually replace with live data from the API. We’ll use Vue.js to display this mocked data. For this first step, we’ll keep all of the code in a single file.

Create a new file called index.html using your text editor.

In this file, add the following HTML markup, which defines an HTML skeleton and pulls in the Foundation CSS framework and the Vue.js library from content delivery networks (CDNs). By using a CDN, there’s no additional code you need to download to start building your app.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.3.1/css/foundation.min.css">
  <meta charset="utf-8">
  <title>Cryptocurrency Pricing Application</title>
</head>

  <body>
    <div class="container" id="app">
      <h3 class="text-center">Cryptocurrency Pricing</h3>
      <div class="columns medium-4" >
        <div class="card">
          <div class="card-section">
            <p> BTC in USD  </p>
          </div>
          <div class="card-divider">
            <p>{{ BTCinUSD }}</p>
          </div>
        </div>
      </div>
    </div>

    <script src="https://unpkg.com/vue@3"></script>
  </body>
</html>

The line {{ BTCinUSD }} is a placeholder for the data that Vue.js will provide, which is how Vue lets us declaratively render data in the UI. Let’s define that data.

Right below the <script> tag with Vue, add this code to create a new Vue application and define a data structure for display on the page:

index.html
...
   <script> 
        const { createApp } = Vue
        
        createApp({    
          data() {
            return {
              BTCinUSD: 3759.91
            }
          }  
        }).mount('#app')
    </script>
...

This code creates a new Vue app instance and attaches the instance to the element with the id of app. Vue calls this process mounting an application. We define a new Vue instance and configure it by passing a configuration object. To the createApp instance, we pass a data object that returns the value of BTCinUSD. Further, we have invoked the mount method of the createApp instance with argument #app that specifies the id of the element we want to mount this application on and a data option containing the data we want available to the view.

In this example, our data model contains a single key-value pair that holds a mock value for the price of Bitcoin: { BTCinUSD: 3759.91}. This data will be displayed on our HTML page, or our view, in the place where we enclosed the key in double curly braces like this:

index.html
<div class="card-divider">
  <p>{{ BTCinUSD }}</p>
</div>

We’ll eventually replace this hard-coded value with live data from the API.

Open this file in your browser. You’ll see the following output on your screen, which displays the mock data:

Vue app showing mock data for the bitcoin price in US Dollars

We’re displaying the price in U.S. dollars. To display it in an additional currency, like Euros, we’ll add another key-value pair in our data model and add another column in the markup. First, add the line for Euros to the data model:

index.html
  <script> 
        const { createApp } = Vue
        
        createApp({    
          data() {
            return { 
              BTCinUSD: 3759.91, 
              BTCinEURO: 3166.21
            }
          }  
        }).mount('#app')
    </script>

Then replace the existing <div class> section with the following lines.

index.html
  <div class="container" id="app">
      <h3 class="text-center">Cryptocurrency Pricing</h3>
      <div class="columns medium-4" >
        <div class="card">
          <div class="card-section">
            <p> BTC in USD  </p>
          </div>
          <div class="card-divider">
            <p>{{ BTCinUSD }}</p>
          </div>
        </div>
      </div>
      <div class="columns medium-4" >
        <div class="card">
          <div class="card-section">
            <p> BTC in EURO  </p>
          </div>
          <div class="card-divider">
            <p>{{ BTCinEURO }}</p>
          </div>
        </div>
      </div>
    </div>

Now save the file and reload it in your browser. The app now displays the price of Bitcoin both in Euros as well as in US Dollars.

Vue app with mock price of Bitcoin in both USD and Euros

In this step, you created your Vue app with some sample data to ensure it loads. We’ve done all the work in a single file so far, so now we’ll split things into separate files to improve maintainability.

Step 2 — Separating JavaScript and HTML for Clarity

To learn how things work, we placed all of the code in a single file. In this step, you’ll separate the application code into two separate files: index.html and vueApp.js. The index.html file will handle the markup, and the JavaScript file will contain the application logic. We’ll keep both files in the same directory.

First, modify the index.html file and remove the JavaScript code, replacing it with a link to the vueApp.js file.

Locate this section of the file:

index.html
...
    <script src="https://unpkg.com/vue@3"></script>
    <script> 
        const { createApp } = Vue
        
        createApp({    
          data() {
            return {
              BTCinUSD: 3759.91,
              BTCinEURO: 3166.21
            }
          }             
        }).mount('#app')
    </script>
...

And modify it so it looks like this:

index.html
...
    <script src="https://unpkg.com/vue@3"></script>
    <script src="vueApp.js"></script>
...

Then create the vueApp.js file in the same directory as the index.html file.

In this new file, place the same JavaScript code that was originally in the index.html file, without the <script> tags:

vueApp.js
 const { createApp } = Vue
        
createApp({    
  data() {
    return {
      BTCinUSD: 3759.91,
      BTCinEURO: 3166.21
    }
  }  
}).mount('#app')

Save the file and reload the index.html in the browser. You will see the same result you saw previously.

Here, you separated the app from the markup. Next, you’ll add more data to support more cryptocurrencies than just Bitcoin.

Step 3 — Using Vue to Iterate Over Data

In this step, you’ll restructure the data and modify the view to show prices for both Bitcoin and Ethereum.

Open the vueApp.js file and modify the return portion of the data model so it looks like this:

vueApp.js
const { createApp } = Vue
      
createApp({
  data() {
    return { 
        results: {"BTC": {"USD":3759.91,"EUR":3166.21}, "ETH": {"USD":281.7,"EUR":236.25}}
    }
  }
}).mount('#app')

Our data model has become a little more complex with a nested data structure. We now have a key called results which contains two records: one for Bitcoin prices and another for Ethereum prices. This new structure will let us reduce some duplication in our view. It also resembles the data we’ll get from the Cryptocompare API.

Save the file.

Now let’s modify our markup to process the data in a more programmatic way.

Open the index.html file and locate this section of the file where we display the price of Bitcoin:

index.html
...
    <div class="columns medium-4" >
      <div class="card">
        <div class="card-section">
          <p> BTC in USD  </p>
        </div>
        <div class="card-divider">
          {{BTCinUSD}}
        </div>
      </div>
    </div>

    <div class="columns medium-4" >
      <div class="card">
        <div class="card-section">
          <p> BTC in EURO  </p>
        </div>
        <div class="card-divider">
          {{BTCinEURO}}
        </div>
      </div>
    </div>

  </div>
...

Replace it with this code which iterates over the dataset you defined.

index.html
...
  <div class="columns medium-4" v-for="(result, index) in results">
    <div class="card">
      <div class="card-section">
        <p> {{ index }} </p>
      </div>
      <div class="card-divider">
        <p>$ {{ result.USD }}</p>
      </div>
      <div class="card-section">
        <p> &#8364 {{ result.EUR }}</p>
      </div>
    </div>
  </div>
...

This code uses the v-for directive which acts like a for-loop. It iterates over all the key-value pairs in our data model and displays the data for each one.

When you reload in the browser, you’ll see the mocked prices:

Vue app with Bitcoin and Ethereum mock price

This modification lets us add a new currency to the results data in vueApp.js and have it display on the page without futher changes.

Add another mocked entry to the dataset with the highlighted information to try this out:

vueApp.js
const { createApp } = Vue
      
createApp({
  data() {
    return {
        results: {"BTC": {"USD":3759.91,"EUR":3166.21}, 
        "ETH": {"USD":281.7,"EUR":236.25},
        "NEW Currency":{"USD":5.60,"EUR":4.70}}
    }
  }
}).mount('#app')

Include the trailing comma after the Ethereum entry. Save the file.

If you now load the page in the web browser, you will see the new entry displayed:

Vue app with Bitcoin, Ethereum and hypothetical currency mock price

Once we tackle the data programmatically, we don’t need to add new columns in the markup manually.

Here, you used sample data to view pricing for multiple currencies. Now let’s fetch real data using the Cryptocompare API.

Step 4 — Getting Data from the API

In this step, you will replace the mocked-up data with live data from the Cryptocompare API to show the price of Bitcoin and Ethereum on the webpage in US Dollars and Euros.

To get the data for our page, we’ll make a request to https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR, which requests Bitcoin and Ethereum in US Dollars and Euros. This API will return a JSON response.

Use curl to make a request to the API to see the response in a terminal session:

  1. curl 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR'

You’ll see output like this:

Output
{"BTC":{"USD":21694.18,"EUR":21407.64},"ETH":{"USD":1504.02,"EUR":1485.99}}

This result looks like the hard-coded data model you used in the previous step, but with the current values of the Bitcoin and Ethereum. All we have to do now is switch out the data by making a request to this URL from our app.

To make the request, we’ll use the mounted() function from Vue in combination with the GET function of the Axios library to fetch the data and store it in the results array in the data model. The mounted function is called once the Vue app is mounted to an element. Once the Vue app is mounted, we’ll make the request to the API and save the results. The web page will be notified of the change and the values will appear on the page.

First, open index.html and load the Axios library by adding a script below the line where you included Vue:

index.html
...
    <script src="https://unpkg.com/vue@3"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="vueApp.js"></script>
...

Save the file, then open vueApp.js.

Modify and update vueApp.js so it makes a request to the API and fills the data model with the results.

vueApp.js
const url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR";
const { createApp } = Vue
      
createApp({    
  data() {
    return {
        results:[]
    }
},
    mounted() {
        axios.get(url).then(response => {
            this.results = response.data
        })
  }
}).mount('#app')

Notice we’ve removed the default value for results and replaced it with an empty array. We won’t have data when our app first loads, but the HTML view is expecting some data to iterate over when it loads.

The axios.get function uses a Promise. When the API returns data successfully, the code within the then block is executed, and the data gets saved to our results variable.

Save the file and reload the index.html page in the web browser. This time, you’ll see the current prices of the cryptocurrencies.

If you don’t see anything, you can review How To Use the JavaScript Developer Console and use the JavaScript console to debug your code. The page may take a minute to refresh with data from the API.

You can also view this Github repository, which contains the html and js files that you can download for cross-confirmation. You can also clone the repository.

In this step, you modified your app to call live data for review.

Conclusion

In less than fifty lines, you created an API-consuming application using only three tools: Vue.js, Axios, and the Cryptocompare API. You learned how to display data on a page, iterate over results, and replace static data with results from an API.

Now that you understand the fundamentals, you can add other functionality to your application. Modify this application to display additional currencies, or use the techniques you learned in this tutorial to create another web applications using a different API.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
rkoli

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
6 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

this is awsome

this is awsome

Alhamdulillah. Thanks bro, It’s easy to learn for beginner like me

Thats Great, Wondering how can you auto-refresh this data for a set interval

That is so cool)

Perfect Mate. Recommended. :-)

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more