Search code examples
jqueryjson

How to get BTC current price data from Coinbase API?


I am trying to get BTC current price from the following API endpoint:

https://api.coindesk.com/v1/bpi/currentprice.json

function CoinbaseBTCPrice(){
    $.ajax({
    url: "https://api.coindesk.com/v1/bpi/currentprice.json",
    success: function(bitcoinPrice){
        console.log(bitcoinPrice.bpi.USD.rate)
        }
    })
}

When I try to do this it says that the data I am looking for is undefined.


Solution

  • You need to parse the returned JSON string first using JSON.parse. Find out more in here.

    CoinbaseBTCPrice();
    
    function CoinbaseBTCPrice(){
        $.ajax({
        url: "https://api.coindesk.com/v1/bpi/currentprice.json",
        success: function(bitcoinPrice){
            console.log(JSON.parse(bitcoinPrice).bpi.USD.rate)
            }
        })
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


    For shorter version, you can you $.getJSON instead.

    $.getJSON("https://api.coindesk.com/v1/bpi/currentprice.json", function(currentPriceInfo){
      console.log(currentPriceInfo.bpi.USD.rate)
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>