Search code examples
javascripthtmlcssjsoncryptoapi

How to get JSON data from API using Javascript?


I'm trying to get the JSON data from the website https://api.cryptonator.com/api/ticker/btc-usd

How would I go about using Javascript to extract the JSON data? Specifically I would want the price field to be outputted.

For a little context, I'm making a small Crypto project that tracks prices in real time so I would be using it with HTML like so:

    <h1> Bitcoin (BTC) </h1>

    <p> Price in USD: $<span id="price"></span>

    </p>
    <script>
      const api_url = 'https://api.cryptonator.com/api/ticker/btc-usd';

      async function getBTCPrice() {
        const response = await fetch(api_url);
        const data = await response.json();

        console.log(data.ticker.price);

        const price = data.ticker.price;

        document.getElementById('price').textContext = price;
      }

      getBTCPrice();
    </script>

Where the Price in USD (Real-time): $ would update based on the price in the API.

Any help would be appreciated, thanks!


Solution

  • You can fetch API data in javascript with the Fetch API, this contains a handy function to parse JSON downloads.

    An example of fetching the bitcoin price

    async function fetchPrice() {
      const res = await fetch('https://api.cryptonator.com/api/ticker/btc-usd');
      const data = await res.json();
      return data.ticker.price
    }
    

    This could be used to set the innerText of a DOM node

    fetchPrice().then(price => {
      document.querySelector('#price').innerText = price;
    }, console.error);