Reputation: 71
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!
Upvotes: 3
Views: 2336
Reputation: 2170
Two potential issues:
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.
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
Upvotes: 2