javascriptgoogle-apps-scriptgoogle-reporting-api

How can I include a variable in a json-format API call in Apps Script (javascript)?


I'm working on a custom function for Google Sheets, that receives a cell value as input and spits out the response from an API call. Knowing thatin the current stage Google Analytics Reporting API can't be directly used with the custom function, I'm following this and this workaround.

The function that runs the API call to the Google Analytics Reporting API includes a JSON-formatted request with metrics, dimensions, filters, etc. The problem is that the dimension filter is variable and I want that to be the input from Google Sheets. However, I keep getting this error message:

GoogleJsonResponseException: API call to analyticsreporting.reports.batchGet failed with error: Field request.dimensionFilterClauses.filters.expressions is required. (line 2, file "Code")

    function plateToCampaign(plate) {
  globalThis.r = AnalyticsReporting.Reports.batchGet({
  "reportRequests":
  [
    {
      "viewId": {"my_viewId"},
      "pageSize": 1,
      "dateRanges": [
        {"endDate": "today", "startDate": "30daysAgo"}
      ],
      "metrics": [
        {"expression": "ga:pageValue"}
      ],
      "dimensions": [{"name": "ga:sourceMedium"}, {"name": "ga:campaign"}, {"name": "ga:dateHourMinute"}],
      "orderBys": {"fieldName": "ga:dateHourMinute","sortOrder": "DESCENDING"},
      "dimensionFilterClauses": [
        {
          "filters": [
            {
              "dimensionName": "ga:pagePath",
              "operator": "PARTIAL",
              "expressions": [plate]
            }
          ]
        }
      ]
    }
  ]
});
globalThis.c = r.reports[0].data.rowCount > 0? r.reports[0].data.rows[0].dimensions[0] : null
if (c === "google / cpc") {
  globalThis.x = r.reports[0].data.rows[0].dimensions[1]
  console.log(x)
  return(x)
} else {
  console.log(c);
  return(c)
}
}


function doGet(e) {
  const res = plateToCampaign(e.parameter.plate)
  return ContentService.createTextOutput(JSON.stringify(res));
}

function test(plate) {
  const url = {"my_web_app_url"}
  return UrlFetchApp.fetch(url).getContentText();  
}

If I change the variable plate to a single value then it works, ie function plateToCampaign(plate = {"fixed_value"}). However this value will be different every time. How do I fix this?


Solution

  • After correcting your json as follows

      var reportRequests = 
      [
        {
          "viewId": "my_viewId",
          "pageSize": 1,
          "dateRanges": [
            {"endDate": "today", "startDate": "30daysAgo"}
          ],
          "metrics": [
            {"expression": "ga:pageValue"}
          ],
          "dimensions": [{"name": "ga:sourceMedium"}, {"name": "ga:campaign"}, {"name": "ga:dateHourMinute"}],
          "orderBys": {"fieldName": "ga:dateHourMinute","sortOrder": "DESCENDING"},
          "dimensionFilterClauses": [
            {
              "filters": [
                {
                  "dimensionName": "ga:pagePath",
                  "operator": "PARTIAL",
                  "expressions": ["plate"]
                }
              ]
            }
          ]
        }
      ]
    

    you will be able to change plate for instance this way

    function myfunction(item) {
      var reportRequests =
        [
          {
            "viewId": "my_viewId",
            "pageSize": 1,
            "dateRanges": [
              { "endDate": "today", "startDate": "30daysAgo" }
            ],
            "metrics": [
              { "expression": "ga:pageValue" }
            ],
            "dimensions": [{ "name": "ga:sourceMedium" }, { "name": "ga:campaign" }, { "name": "ga:dateHourMinute" }],
            "orderBys": { "fieldName": "ga:dateHourMinute", "sortOrder": "DESCENDING" },
            "dimensionFilterClauses": [
              {
                "filters": [
                  {
                    "dimensionName": "ga:pagePath",
                    "operator": "PARTIAL",
                    "expressions": [""]
                  }
                ]
              }
            ]
          }
        ]
      reportRequests[0].dimensionFilterClauses[0].filters[0].expressions[0] = item
      // include reportRequests in your own script ...
    }
    

    application

    try this

    function plateToCampaign(item = 'plate') {
      var myRequest =
        [
          {
            "viewId": "my_viewId",
            "pageSize": 1,
            "dateRanges": [
              { "endDate": "today", "startDate": "30daysAgo" }
            ],
            "metrics": [
              { "expression": "ga:pageValue" }
            ],
            "dimensions": [{ "name": "ga:sourceMedium" }, { "name": "ga:campaign" }, { "name": "ga:dateHourMinute" }],
            "orderBys": { "fieldName": "ga:dateHourMinute", "sortOrder": "DESCENDING" },
            "dimensionFilterClauses": [
              {
                "filters": [
                  {
                    "dimensionName": "ga:pagePath",
                    "operator": "PARTIAL",
                    "expressions": [""]
                  }
                ]
              }
            ]
          }
        ]
      myRequest[0].dimensionFilterClauses[0].filters[0].expressions[0] = item
      globalThis.r = AnalyticsReporting.Reports.batchGet({
        "reportRequests": myRequest
      });
      globalThis.c = r.reports[0].data.rowCount > 0 ? r.reports[0].data.rows[0].dimensions[0] : null
      if (c === "google / cpc") {
        globalThis.x = r.reports[0].data.rows[0].dimensions[1]
        console.log(x)
        return (x)
      } else {
        console.log(c);
        return (c)
      }
    }