Home > Enterprise >  Calling yahoofinanceapi API
Calling yahoofinanceapi API

Time:09-28

How to convert the below JAVA code to apps script?

I want the quote to be pulled into my sheet

Ticker symbol is in A2

I want the price in B2

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://rest.yahoofinanceapi.com/v6/finance/quote/AAPL"))
.header("x-api-key", "YOUR-PERSONAL-API-KEY")
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

CodePudding user response:

try the following script

const YOUR_PERSONAL_API_KEY = '... Your API KEY ...';

function fetch_yfapi(ticker_symbol){

  let urlToFetch = `https://yfapi.net/v6/finance/quote?region=US&lang=en&symbols=${ticker_symbol}`,
      options = {        
        method: 'get',
        headers: { 
          'accept'       : 'application/json',
          'X-API-KEY'    : YOUR_PERSONAL_API_KEY, },     
        muteHttpExceptions: true    
      },   
      fetched = {
        code: null,
        body: null,
      }      

  try{
    const response = UrlFetchApp.fetch(urlToFetch, options);
    fetched.code   = response.getResponseCode();
    fetched.body   = response.getContentText();
    if (fetched.code !== 200) {
      console.log(Utilities.formatString("Request failed. Expected 200, got %d: %s", fetched.code, fetched.body)) 
    } 
  } catch(e) {
    console.log('Method call error UrlFetchApp.fetch : %s',e)  
  }
  return fetched.body
}

function getTickerData(){
  let sheet = SpreadsheetApp.getActive().getSheetByName('... sheet name ...'),
      ticker_symbol = sheet.getRange('A2').getValue();

  if (ticker_symbol.length) {
    let ticker_data = fetch_yfapi(ticker_symbol);
    if (ticker_data) {
      console.log(ticker_data);
      sheet.getRange('B2').setValue(JSON.parse(ticker_data).quoteResponse.result[0].ask)
    } 
  } 

}

I didn't know exactly what price you wanted to get in the end - so I put 'ask'. In the console you can see the whole body of the returned response

  • Related