Google Apps Script - Fetch data from third party API with date parameter

让人想犯罪 __ 提交于 2021-01-29 08:05:14

问题


One of my vendors has created an API that I can use to pull data. I'm trying to use google apps script for this as I can easily schedule the data pull on it.

I've used the UrlFetchApp before but I'm lost with this as I have to pass an additional parameter in it for a date - I don't know how to do this and I would appreciate your help figuring this out.

The instructions given to me are these:

url = "https://xxxxx.com/api/leads/"
method = POST
//Request JSON format: (date format should be ‘Y-m-d’)
{"date":"2019-08-21"}

In addition to googling, I've tried various iterations of adding the date parameter to the options on UrlFetchApp as well as trying to append it to the URL string.

This is what I have so far:

function myFunction() {
  var pullDate = new Date().toISOString().split('T')[0];  
  var dateParams = {"date": pullDate};
  var url = "https://xxxxx.com/api/leads/";
  var options = {
    "method" : "POST",
    "contentType" : "application/json"
  }  

  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

This is the response i'm getting:

[19-09-09 12:44:36:586 IST] {"result":"date is empty!"}

The expected response is something like this:

{"result":[
{"count":"55","model":"ABC","date":"2019-09-09"},
{"count":"2","model":"DEF","date":"2019-09-09"},
{"count":"48","model":"XYZ","date":"2019-09-09"}
]}

I'd appreciate your help in figuring this out!


回答1:


Issue:

  • payload(or request body) is missing from the request.

Snippet:

  • You can include payload in options:
  var options = {
    "method" : "POST",
    "contentType" : "application/json",
    "payload": JSON.stringify(dateParams)
  }  


来源:https://stackoverflow.com/questions/57849398/google-apps-script-fetch-data-from-third-party-api-with-date-parameter

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