📜  coindeskapi ethereum - Javascript (1)

📅  最后修改于: 2023-12-03 15:30:03.096000             🧑  作者: Mango

Coindesk API Ethereum - Javascript

Coindesk provides API services for current and historical prices of various cryptocurrencies. Here, we will use the Coindesk API to fetch current prices of Ethereum using Javascript.

Prerequisites
  • Basic knowledge of Javascript
  • An API key from Coindesk (you can obtain it for free from here)
API Endpoint

First, we need to know the API endpoint for Ethereum prices. The endpoint for current price data of Ethereum is:

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

Making an API Request

We will be using the built-in fetch method in Javascript to make a GET request to the API endpoint. Here's how we can do it:

const apiEndpoint = "https://api.coindesk.com/v1/bpi/currentprice/ETH.json";
const apiKey = "YOUR_API_KEY";

fetch(`${apiEndpoint}?api_key=${apiKey}`)
  .then(response => response.json())
  .then(data => console.log(data));

Here, YOUR_API_KEY should be replaced with your own API key.

This code fetches the current price data for Ethereum from the API endpoint, and logs it to the console as a JSON object.

Parsing the Response

The response object returned by the API is quite detailed. Here's an example of what the response object looks like:

{
  "time": {
    "updated": "Apr 16, 2021 18:21:00 UTC",
    "updatedISO": "2021-04-16T18:21:00+00:00",
    "updateduk": "Apr 16, 2021 at 19:21 BST"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "$",
      "rate": "2,413.2275",
      "description": "United States Dollar",
      "rate_float": 2413.2275
    },
    "GBP": {
      "code": "GBP",
      "symbol": "£",
      "rate": "1,734.6825",
      "description": "British Pound Sterling",
      "rate_float": 1734.6825
    },
    "EUR": {
      "code": "EUR",
      "symbol": "€",
      "rate": "2,000.5793",
      "description": "Euro",
      "rate_float": 2000.5793
    }
  }
}

We can see that the data we need is stored in the bpi property of the response object. We can get the current price of Ethereum in USD like this:

fetch(`${apiEndpoint}?api_key=${apiKey}`)
  .then(response => response.json())
  .then(data => {
    const currentPrice = data.bpi.USD.rate;
    console.log(`Current price of Ethereum: ${currentPrice}`);
  });

This code logs the current price of Ethereum in USD to the console.

Conclusion

In this tutorial, we saw how to use the Coindesk API to fetch current prices of Ethereum using Javascript. We learned how to make an API request using fetch, and how to parse the response object to get the data we need.