Search code examples
google-apps-scriptgoogle-my-business-api

GMB API Insights Invalid JSON Payload received


I am trying to get some insights of our locations using Google Apps Script and the Google My Business Api.

Getting Reviews and stuff was no big deal.

The code worked out well in the OAuth2 Playground.

Here is the request:

var myBusinessService = getMyBusinessService();

var payload ={
  "locationNames":["accounts/116447162401331885225/locations/10722475831894877870"],
  "basicRequest": {
    "metricRequests": [{
      "metric": "ALL"
    }],
    "timeRange": {
      "startTime": "2017-01-01T00:00:01.045123456Z",
      "endTime": "2017-01-31T23:59:59.045123476Z"
    }
  }
};

var options = {
  "headers":{
    "Authorization": 'Bearer ' + myBusinessService.getAccessToken()
  },
  "method": "POST",
  "payload": payload,
  "muteHttpExceptions": true
};
var response = UrlFetchApp.fetch('https://mybusiness.googleapis.com/v4/accounts/116447162401331885225/locations:reportInsights', options);

The response:

{error={code=400, details=[Ljava.lang.Object;@3116fd89, message=Invalid JSON payload received. Unknown name "basicRequest": Cannot bind query parameter. 'basicRequest' is a message type. Parameters can only be bound to primitive types., status=INVALID_ARGUMENT}}

Hope someone might help me with this.

Regards

Thies


Solution

  • You're sending payload as a JavaScript object. As per the error message ("message=Invalid JSON payload received."), you need to send it as JSON. Use JSON.stringify() to make payload a JSON string.

    var options = {
      "headers":{
        "Authorization": 'Bearer ' + myBusinessService.getAccessToken()
      },
      "method": "POST",
      "payload": JSON.stringify(payload),
      "muteHttpExceptions": true
    };