John John
John John

Reputation: 1455

fetching web api with axios

How to fetch "high" and "low" price from the following web api using AXIOS. Here you will find the following code, but obviously I need to change to make it work properly for all dates.

axios.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=TUVR')
.then(response => {
  console.log(response.data['Time Series (Daily)']['2018-10-18']['2. high']);
  console.log(response.data['Time Series (Daily)']['2018-10-18']['3. low']);

})
.catch(error => {
  console.log(error);
});

sample of the original data I am trying to extract

{
  "Meta Data": {
    "1. Information": "Weekly Prices (open, high, low, close) and Volumes",
      "2. Symbol": "MSFT",
        "3. Last Refreshed": "2018-10-18",
          "4. Time Zone": "US/Eastern"
  },
  "Weekly Time Series": {
    "2018-10-18": {
      "1. open": "108.9100",
        "2. high": "111.8100",
          "3. low": "106.9468",
            "4. close": "108.5000",
              "5. volume": "122020154"
    },
    "2018-10-12": {
      "1. open": "111.6600",
        "2. high": "113.0800",
          "3. low": "104.2000",
            "4. close": "109.5700",
              "5. volume": "228861873"
    },
    "2018-10-05": {
      "1. open": "114.7500",
        "2. high": "116.1800",
          "3. low": "110.6400",
            "4. close": "112.1300",
              "5. volume": "120208912"
    },
    "2018-09-28": {
      "1. open": "113.0300",
        "2. high": "115.1000",
          "3. low": "112.2175",
            "4. close": "114.3700",
              "5. volume": "110093609"
    }
  }
}

Upvotes: 0

Views: 295

Answers (2)

Meow3301
Meow3301

Reputation: 75

In JS, Assign your data to some var say "myData" and Try this:

function getHighAndLow(){

  var myData = {your example data};

  var weeklyTimeSeries = myData["Weekly Time Series"];
  var series = [];

  for (var i in weeklyTimeSeries) {
      series.push(weeklyTimeSeries[i]);
  }

  var high = series.map(function (a) { return a["2. high"] });

  var low = series.map(function (a) { return a["3. low"] });
}

Hope it'll help :)

Upvotes: 1

eheisler
eheisler

Reputation: 124

I did not add the axios wrapper, but you can probably translate it pretty easily from a normal fetch:

fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=TUVR')
  .then(resp => resp.json())
  .then(response => {
    const highLow = Object.keys(response['Time Series (Daily)']).map(date => {
      return {
        date,
        high: response['Time Series (Daily)'][date]['2. high'],
        low: response['Time Series (Daily)'][date]['3. low']
      }
    })
    console.log(highLow);
  })
  .catch(error => {
    console.log(error);
  });

Upvotes: 2

Related Questions