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

Introduction

Vue.js is a front-end framework that is javaScript building user interfaces. It’s designed from the ground up to be incrementally adoptable, and it integrates well with other libraries or projects that are existing. This will make it a fit that is good little tasks including advanced single-page applications whenever used in combination with other tooling and libraries.

An API, or Application Programming Interface, is a computer software intermediary which allows two applications to speak to both. An API frequently reveals information that other designers can eat within their apps that are own 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 fit that is great eating most of these APIs.

In this guide, you are going to produce a Vue application that makes use of the Cryptocompare API to show the existing rates of two cryptocurrencies that are leading Bitcoin and Etherium. In addition to Vue, you’ll use the Axios library to make API requests and process the obtained results. Axios is a great fit it supports Promises, which leads to code that’s easier to read and debug because it automatically transforms JSON data into JavaScript objects, and. Also to make things look good, we will utilize the Foundation CSS framework.

Note: The Cryptocompare API is certified for non-commercial just use. See their certification terms in a commercial project.
( if you wish to use it******)

Prerequisites

Before you start this guide you will need the ( that is following******)

Step 1 — Creating a fundamental Vue Application

Let’s make a Vue that is basic application. We’ll build a HTML that is single with a few mocked-up information that people will in the course of time change with real time information through the API. We will utilize Vue.js to show this data that are mocked. For this step that is first we will keep most of the rule in one file.

Create a file that is new index.html utilizing your text editor.

In this file, include the HTML that is following markup 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 code that is additional have to install to begin bulding out your application.

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 prices Application</title>
</head>

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

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

The line {{ BTCinUSD }} is a placeholder the information that Vue.js will give you. This is one way Vue allows us to render data in declaritively the UI. Let us determine that information.

Right underneath the <script> label which includes Vue, include this rule that’ll produce a Vue that is new application determine an information framework which we will show regarding the web page:

index.html

...

    <script>
      const vm = brand new Vue({
              el: '#app',   
              //Mock information the value of BTC in USD
              information: { BTCinUSD: 3759.91}
            });

    </script>
...

This rule produces a Vue that is new app and attaches the instance to the element with the id of app. Vue calls this process mounting an application. We define a Vue that is new instance configure it by moving a configuration item. This item contains an el choice which specifies the id regarding the element you want to install this application on, and a data choice containing the information we would like offered to the view.

In this instance, our information model contains a key-value that is single that holds a mock value for the price of Bitcoin: { BTCinUSD: 3759.91}. This information are shown on our HTML web page, or our view, in spot in which we enclosed the important thing in dual braces that are curly this:

<div course="card-divider">
  <p>{{ BTCinUSD }}</p>
</div>

We’ll in the course of time change this value that is hard-coded real time information through the API.

Open this file within web browser. You will see the output that is following your display screen, which shows the mock information:

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

We’re showing the cost in U.S. bucks. To show it in an currency that is additional like Euros, we will include another key-value set within our information model and include another line in markup. First, replace the information model:

index.html

  <script>
  const vm = brand new Vue({
          el: '#app',
          //Mock information the value of BTC in USD
          information: { BTCinUSD: 3759.91, BTCinEURO:3166.21 }
        });

  </script>   

Then include a section that is new the markup that shows the cost in Euros underneath the existing rule.

index.html

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

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

  </div>

Now conserve the file and reload it within web browser. The application now shows the cost of Bitcoin both in Euros including in United States Dollars.

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

We’ve done all work with a file that is single. Let us separate things out to enhance maintainability.

Step 2 — splitting JavaScript and HTML for Clarity

To understand how things work, we put most of the rule in a file that is single. Now let’s separate the application code into two files that are separate index.html and vueApp.js. The index.html file will manage the markup component, plus the JavaScript file will retain the application logic. This may make our application more maintainable. We will keep both files in directory that is same

First, change the index.html file and eliminate the JavaScript rule, changing it with a hyperlink to your vueApp.js file.

Locate this element of the file:

index.html

...
    <script src="https://unpkg.com/vue"></script>
    <script  language="JavaScript">
    const vm = brand new Vue({
            el: '#app',
            // Mock information the value of BTC in USD
            information: { BTCinUSD: 3759.91, BTCinEURO:3166.21 }
          });
    </script>
...

And change it therefore it seems like this:

index.html

...
    <script src="https://unpkg.com/vue"></script>
    <script src="http://www.digitalocean.com/vueApp.js"></script>
...

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

In this file that is new spot the exact same JavaScript rule that has been initially in index.html file, without <script> tags:

vueApp.js

const vm = brand new Vue({
        el: '#app',
        // Mock information the value of BTC in USD
        information: { BTCinUSD: 3759.91, BTCinEURO:3166.21 }
      });

Save the file and reload the index.html in web browser. You will notice the result that is same saw formerly.

We desire to help more cryptocurrencies than Bitcoiin, therefore let us check how exactly we accomplish that.

Step 3 — utilizing Vue to Iterate Over Data

We’re at this time showing some data that are mock the price of Bitcoin. But let’s add Etherium too. To do this, we’ll restructure our data and modify the view to work with the data that is new

Open the vueApp.js file and change the information model therefore it seems like this:

vueApp.js

const vm = brand new Vue({
        el: '#app',
        information: {
          results: {"BTC": {"USD":3759.91,"EUR":3166.21}, 
                    "ETH": {"USD":281.7,"EUR":236.25}}
        }
      });

Our information model is becoming a bit more complex with a nested information framework. We’ve got an integral called results containing two documents; one for Bitcoin rates and another for Etherium rates. This structure that is new why don’t we reduce some replication within our view. Additionally resembles the information we will get through the cryptocompare API.

Save the file. Now let us change our markup to process the information in a far more way that is programmatic.

Open the index.html file and find this element of the file in which we show the cost of Bitcoin:

index.html

...
    <div course="columns> that is medium-4"
      <div course="card">
        <div course="card-section">
          <p> BTC in USD  </p>
        </div>
        <div course="card-divider">
          {{BTCinUSD}}
        </div>
      </div>
    </div>

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

  </div>
...

Replace it with this specific rule which iterates throughout the dataset you defined.

index.html

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

This rule makes use of the v-for directive which functions like a for-loop. It iterates overall the pairs that are key-value our information model and shows the information for every single one.

once you reload this in web browser, you will see the mocked rates:

Vue app with Bitcoin and Ethereum mock price

This modification allows us to include a currency that is new the results data in vueApp.js and have it display on the page without futher changes. Add another entry that is mocked the dataset to test this out:

vueApp.js

const vm = brand new Vue({
        el: '#app',
        information: {
          outcomes: {"BTC":{"USD":3759.91,"EUR":3166.21},
                    "ETH":{"USD":281.7,"EUR":236.25},
                    "NEW Currency":{"USD":5.60,"EUR":4.70}}
        }
      });

Don’t forget to incorporate the comma that is trailing the Etherium entry.

(you will see the new entry displayed:

If you now load the page in the web browser,******)

Vue app with Bitcoin, Ethereum and hypothetical currency mock price

Once we tackle the information programmatically, we do not have to include columns that are new the markup by hand.

Now let us fetch data that is real

Step 4 — Getting information through the API

It’s time for you change our mocked-up information with real time information through the API that is cryptocompare to the cost of Bitcoin and Ethereum regarding the website in United States Dollars and Euros.

To have the information for the web page, we will make a demand to your URL that is following requests Bitcoin and Etherium in United States Dollars and Euros:

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

This API will get back a response that is JSON. Utilize curl to produce a request to your API to start to see the reaction:

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

You’ll see production such as this:

Output

{"BTC":{"USD":11388.18,"EUR":9469.64},"ETH":{"USD":1037.02,"EUR":865.99}}

This outcome appears the same as the hard-coded information model you found in the step that is previous. All we need to do now’s replace the information by simply making a request to the URL from our app.

To result in the demand, we will utilize the***************)mounted( that is( 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 noticeable modification plus the values will be regarding the web page.

First, available index.html and load the Axios collection with the addition of a script underneath the line in which you included Vue:

index.html

...
    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
...

Save the file, then available vueApp.js and change it therefore it makes a demand to your API and fills the information model using the outcomes.

vueApp.js

   
const url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,ETH&tsyms=USD,EUR";

const vm = brand new Vue({
        el: '#app',
        information: {
          outcomes: []
        },
        mounted() {
          axios.get(url).then(reaction => {
            this.results = reaction.data
          })
        }
      });

Notice we have eliminated the standard value for results and replaced it with an array that is empty. We won’t have data when our app loads that are first but we do not wish what to break. Our HTML view is anticipating some information to iterate over with regards to loads.

The axios.get function makes use of a Promise. As soon as the API comes back information effectively, the rule in the then block is performed, plus the information gets conserved to the results adjustable.

Save the file and reload the index.html web page in browser. This time around you will see the existing rates regarding the cryptocurrencies.

If that you don’t, have a look at the tutorial utilizing the JavaScript Developer Console and make use of the console that is javaScript debug your rule.

Conclusion

In not as much as fifty lines, you created an application that is API-consuming only three tools: Vue.js, Axios, and the Cryptocompare API. You learned how to display data on a page, iterate over results, and replace data that are static outcomes from an API.

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here