Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analytics API v4 Invalid json payload error

I am writing Google apps script in Google spreadsheet code editor. I want pull some data from Google Analytics that must using GA API v4. I know there is build in support for Analytics API in Google apps script but only v3 version.

So I follow this guide Google Apps Script - External API and using this library googlesamples/apps-script-oauth2 to do oauth2.

I am sure I have enabled Analytics V4 API in API console and get the right client ID and secret. After auth2 I wrote code to access data

  var payload = {'reportRequests' : [
    {
      'metrics' : [{'expression':'ga:users'}],
      'viewId' : 'xxxxxxxx',
      'dateRages' : [{'startDate':'2016-10-01','endDate':'2016-10-10'}]
    }
  ]};

  var options = {
    'method' : 'post',
    'headers': {
       'contentType': 'application/json',
       'Authorization': 'Bearer ' + service.getAccessToken()
     },
    'payload' : payload,
    'muteHttpExceptions':true
   };

  var resp = UrlFetchApp.fetch("https://analyticsreporting.googleapis.com/v4/reports:batchGet", options);
  Logger.log(resp.getContentText());

Then I got a error http response

[16-10-30 21:25:51:325 PDT] {
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"reportRequests\": Cannot bind query parameter. 'reportRequests' is a message type. Parameters can only be bound to primitive types.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "description": "Invalid JSON payload received. Unknown name \"reportRequests\": Cannot bind query parameter. 'reportRequests' is a message type. Parameters can only be bound to primitive types."
          }
        ]
      }
    ]
  }
}

What am I doing wrong? and what does the error message mean?

Thank you!

like image 215
Liu Dapeng Avatar asked Feb 13 '26 17:02

Liu Dapeng


1 Answers

Two potential issues:

  1. The error states INVALID_ARGUMENT. Your payload contains dateRages, which should be dateRanges, otherwise it will not be recognised as a valid request owing to the typo.

  2. See this answer regarding passing JSON data: If you wish to pass data of Content-Type application/json then you need to provide a string to the payload parameter, not a JS Object.

    Instead of:

    // JS Object, by default will be encoded as formdata (not desired)
    'payload' : payload
    

    Use:

    // Convert JS Object to JSON string
    'payload' : JSON.stringify(payload)
    

Hope this helps

like image 99
Bardy Avatar answered Feb 15 '26 17:02

Bardy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!