Skip to content
Advertisement

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

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);

Advertisement

Answer

  • 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:

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement