Trying to pull stock quote info from TDAmeritrade with Google Script with API needing authentication

。_饼干妹妹 提交于 2020-05-15 05:45:26

问题


I'm using an API from TD Ameritrade to pull stock ticker information. The script needs authentication to pull real time data. The CURL command is as follows:

curl -X GET --header "Authorization: " --header "Authorization: Bearer " "https://api.tdameritrade.com/v1/marketdata/AAPL/quotes?apikey="

I'm using a Google Script to read the data from the API, do some calculations, and then write the data to a Google Sheet. Below is the script to authenticate, and it doesn't work. Note that my access token and APIkeys are not displayed here and the text is noted by and . The script does not give an error message, and pulls (delayed) data. I can tell the authentication isn't working right, because the data is delayed. Testing on the TD Ameritrade site with authentication returns real time data. So does running the CURL in a DOS box on my PC.

var ticker = "AAPL"
var options = {
    "method" : "GET",
    "Authorization" : "Bearer <access token>"
     }
var calltoAPI = UrlFetchApp.fetch("https://api.tdameritrade.com/v1/marketdata/"+ticker+"/quotes?apikey=<APIkey>",options);

I'm fairly new at this and would appreciate any help

UPDATE: HERE IS THE CODE THAT WORKS

    var ticker = "APPL"

    var headers = {"Authorization":" Bearer <access token>"}
    var options = {"headers":headers}

    var calltoAPI=urlFetchApp.fetch("https://api.tdameritrade.com/v1/marketdata/"+ticker+"/quotes?apikey=<apikey>",options);

回答1:


  • You want to convert the following curl command to Google Apps Script.
    • curl -X GET --header "Authorization: " --header "Authorization: Bearer " "https://api.tdameritrade.com/v1/marketdata/AAPL/quotes?apikey="
    • You have already confirmed that this curl command works fine.

If my understanding is correct, how about this answer? When --header "Authorization: Bearer " is used for Google Apps Script, please put it to the header object. So please modify as follows.

From:

var options = {
    "method" : "GET",
    "Authorization" : "Bearer <access token>"
     }

To:

var options = {
  "method" : "GET",
  "headers": {"Authorization" : "Bearer <access token>"}
};

Reference:

  • fetch(url, params)

The requests of both your curl command and the modified script are the same. But if this didn't work, please confirm the tokens.



来源:https://stackoverflow.com/questions/58945513/trying-to-pull-stock-quote-info-from-tdameritrade-with-google-script-with-api-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!