GMB API Insights Invalid JSON Payload received - google-apps-script

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

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
};

Related

Google script doPost to Twilio

I trying to use doPost in google script to get parameter from source A and get twilio to send sms.
Currently, by using the code given by twilio, I can send whatever detail in google script.
I have created the webapp exec url to put in source A so now source A and google script can communicating.
I just do not know how to do a proper script in google script to get the parameters from source A.
Can anyone help me.. thank you in advance !
I am new to coding, not sure even source A code/format is correct -_-"
Source A:(json)
data input field
output result
{
"$type": "Nirvana.Data.TaskResultWebhook, V2API",
"Headers": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.String, mscorlib]], mscorlib",
"Authorization": "Basic xxxxxxxxxxxxxxxxxx=="
},
"Payload": "{\"To\": \"+8888888888\",\"Body\": \"testing\",\"From\" : \"business\"}",
"Url": "https://script.google.com/macros/s/xxxxxxxxxx/exec",
"Verb": "Post",
"ContentType": "JSON",
"MimeType": "application/json",
"TimeoutSeconds": 180,
"MaxRetryCount": 3,
"AsyncExec": false,
"AppErrors": {
"$type": "Jeenee.DataTypes.AppErrors, Jeenee.DataTypes",
"RecordInfo": false,
"RecordWarning": true,
"AnnotateErrors": false,
"Errors": []
},
"TaskType": "Webhook",
"TaskName": "New Task"
}
Google script (code from twilio)
function doPost(e) {
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxx/Messages.json";
var payload = {
"To": "+1111111111",
"Body" : "AAAAAAAAAA",
"From" : "BBBBBBBBBB"
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxx:xxxxxxxxxxxx")
};
UrlFetchApp.fetch(messages_url, options);
}
Step 3 (twilio)
send sms
Not sure who's calling your script. If you're using it as a webhook you can get the parameters in the object passed into your doPost function when it is called.
function doPost(e) {
var params = e.parameter;
var from = params.From;
var to = params.To;
var body = params.Body;
var messages_url = "https://api.twilio.com/2010-04-01/Accounts/ACxxxxxxxxxxxx/Messages.json";
var payload = {
"To": to,
"Body" : body,
"From" : from
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxx:xxxxxxxxxxxx")
};
UrlFetchApp.fetch(messages_url, options);
}

Calling an Apps Script API Executable function with parameters from another Apps script issues

I developed an Apps Script called "sudofunctions" which execute sensitive commands using an elevated account. It is shared with the entire domain and executes as the author.
I then developed "clientFunctions" which can be run by any authenticated user and needs to invoke funcntions in sudofunctions.
sudofunctions has 2 functions so far
function test()
{
createUser("email#domain.com", "Full name")
}
function createUser(email, name)
{
console.log("Checkpoint Alpha")
}
clientFunctions then tries to call both these functions, calling test() works perfectly
var token = ScriptApp.getOAuthToken();
var options = {
"method" : "POST",
"headers": {"Authorization": "Bearer "+ token },
"payload" : {
"function": "test",
"devMode": "true"
},
muteHttpExceptions:true
}
var rest = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/ABCXYZ:run", options)
However, calling createUser fails
var token = ScriptApp.getOAuthToken();
var options = {
"method" : "POST",
"headers": {"Authorization": "Bearer "+ token },
"payload" : {
"function": "createUser",
"parameters":["john#domain.com", "John Doe"],
"devMode": "true"
},
muteHttpExceptions:true
}
var rest = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/ABCXYZ:run", options)
With the error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"parameters\": Cannot bind query parameter. 'parameters' 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 \"parameters\": Cannot bind query parameter. 'parameters' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
According to the documentation, it should work.
https://developers.google.com/apps-script/api/reference/rest/v1/scripts/run#request-body
Any ideas where I am going wrong?
Thanks for the help.
In your script, from your error message, how about the following modification?
From:
var options = {
"method" : "POST",
"headers": {"Authorization": "Bearer "+ token },
"payload" : {
"function": "createUser",
"parameters":["john#domain.com", "John Doe"],
"devMode": "true"
},
muteHttpExceptions:true
}
To:
var options = {
"method": "POST",
"headers": { "Authorization": "Bearer " + token },
"contentType": "application/json",
"payload": JSON.stringify({
"function": "createUser",
"parameters": ["john#domain.com", "John Doe"],
"devMode": "true"
}),
"muteHttpExceptions": true
}
Reference:
Method: scripts.run

Not a valid json request, from DolphinDB JSON API

I'm trying the JSON API provided by DolphinDB, following this tutorial.
And I tried the code snippet like this:
var code = "1+2";
code = encodeURIComponent(code);
paramJson = {
"sessionID": "942605602",
"functionName": "executeCode",
"params": [{
"name": "script",
"form": "scalar",
"type": "string",
"value": code
}]
}
var option = {
url: "http://localhost:9920",
async: true,
data: paramJson,
type: "POST",
dataType: "json",
success: function (data) {
var resultJson = data;
console.log(data);
}
}
$.ajax(option);
Here is the log I got from chrome:
{sessionID: "800870454", userId: "", resultCode: "1", msg: "not a valid json request [sessionID=942605602&func…type%5D=string&params%5B0%5D%5Bvalue%5D=1%252B2].", object: Array(0)}msg: "not a valid json request [sessionID=942605602&functionName=executeCode&params%5B0%5D%5Bname%5D=script&params%5B0%5D%5Bform%5D=scalar&params%5B0%5D%5Btype%5D=string&params%5B0%5D%5Bvalue%5D=1%252B2]."object: []resultCode: "1"sessionID: "800870454"userId: ""__proto__: Object
It report not a valid json request, but I don't know what's wrong with my request.
You can try serializing JSON objects before sending requests
data = JSON.stringify(paramJson)

Google Apps Script to Create Confluence Page -- Results in Status Code 500

Note: I also posted this question on the Atlassian forum here:
https://community.atlassian.com/t5/Confluence-questions/Google-Apps-Script-to-Create-Confluence-Page-HTTP-500-Error/qaq-p/1039040#M66094
I'm reaching out to a larger audience here on SO.
I'm using the following google apps script code in a Google Sheet to create a Confluence page:
headers = {"Authorization" : "Basic " + Utilities.base64Encode(user + ':' +
pswd), "Content-Type": "application/json"};
url = "https://confluence.asdf.com/rest/api/content/";
var params = {
"method":"POST",
"headers":headers,
"muteHttpExceptions": false,
"type":"page",
"title":newTitle,
"space":{"key":"DOC"},
"body":{"storage":{"value": "<p>This is <br/> a new page</p>" },
"representation":"storage"}
};
var createResponse = UrlFetchApp.fetch(url, params);
However, when I submit the request, I receive this response:
Request failed for https://confluence.atlas.asdf.com/rest/api/content/
returned code 500.
Truncated server response: {"statusCode":500,"
message":"<?> No content to map to Object due to end of
input","reason":"Internal Server Error"} (use muteHttpExceptions option to
examine full response)
I realize there are curl samples out there which I've seen but do not help me.
What am I doing wrong?
Edit: 25-March
#Tanaike
I modified the code as you suggested:
headers = {"Authorization" : "Basic " + Utilities.base64Encode(user + ':' + pswd) };
var payload = {
"type": "page",
"title": newTitle,
"space": {"key": "DOC"},
"body": {
"storage": {
"value": "<p>This is <br/> a new page</p>"
},
"representation": "storage"
}
};
var params = {
"method": "POST",
"headers": headers,
"muteHttpExceptions": false,
"payload": JSON.stringify(payload),
"contentType": "application/json"
};
var createResponse = UrlFetchApp.fetch(url, params);
I receive the same error as before.
How about this modification?
Modified script:
Please modify params as follows and test again. From the error message in your question, the request body was put in the property of payload.
var payload = {
"type": "page",
"title": newTitle,
"space": {"key": "DOC"},
"body": {
"storage": {
"value": "<p>This is <br/> a new page</p>"
},
"representation": "storage"
}
};
var params = {
"method": "POST",
"headers": headers,
"muteHttpExceptions": false,
"payload": JSON.stringify(payload)
};
Note:
This modification supposes that each value in payload and headers is correct.
"Content-Type": "application/json" in headers can be also put in params as "contentType": "application/json".
References:
UrlFetchApp
Confluence REST API examples
I cannot test this modification. So if this didn't work, can you provide the error message? I would like to think of about the issue.
Edit:
From the official document, it seems that the property of body is "body":{"storage":{"value":"<p>This is a new page</p>","representation":"storage"}}}. So please modify as follows.
Modified script:
headers = {"Authorization" : "Basic " + Utilities.base64Encode(user + ':' + pswd) };
var payload = {
"type": "page",
"title": newTitle,
"space": {"key": "DOC"},
"body": {
"storage": {
"value": "<p>This is <br/> a new page</p>",
"representation": "storage" // Modified
}
}
};
var params = {
"method": "POST",
"headers": headers,
"muteHttpExceptions": false,
"payload": JSON.stringify(payload),
"contentType": "application/json"
};
var createResponse = UrlFetchApp.fetch(url, params);
Note:
In my environment, I could confirm that the result was the same with the result from the official sample script. If this didn't work, please confirm each value of payload and headers, again.

Sending CSV data to BigQuery REST API via POST

I've been trying to upload a *.csv blob via POST request to BigQuery, but I'm having trouble determining where should I put the blob file (i.e. byte data) in the request.
If I use a client library, this code does what I need:
var job = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1,
allowQuotedNewlines: true,
quote: "'",
sourceFormat: 'CSV'
}
}
};
var job = BigQuery.Jobs.insert(job, projectId, csv);
This works perfectly, but while searching through the REST API, I don't see declared anywhere where to set the *.csv data in order to work like this, with no client library:
var job = {
configuration: {
load: {
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: tableId
},
skipLeadingRows: 1,
allowQuotedNewlines: true,
quote: "'",
sourceFormat: 'CSV'
}
}
};
var url = "https://www.googleapis.com/bigquery/v2/projects/" + projectId + "/jobs/";
var urlParams = {
"method": "POST",
"muteHttpExceptions": true,
"contentType": "application/json",
"headers": {"Authorization": "Bearer " + getBQToken()},
"responseType": "json",
payload: job,
};
var resp = UrlFetchApp.fetch(url, urlParams).getContentText();
var result = JSON.parse(resp);
How can I include my CSV data and the job configuration when using the REST API approach?
There are two ways to make upload requests: multipart upload and resumable upload. Multipart upload is “for quick transfer of smaller files and metadata; transfers the file along with metadata that describes it, all in a single request”. Resumable upload is “for reliable transfer, especially important with larger files” as described here (as #Elliott Brossard pointed). Find in the same documentation the resumable upload request for the Google BigQuery API example below:
POST /upload/bigquery/v2/projects/<projectId>/jobs?uploadType=resumable HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer your_auth_token
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: */*
X-Upload-Content-Length: 2000000
{
"configuration": {
"load": {
"sourceFormat": "NEWLINE_DELIMITED_JSON",
"schema": {
"fields": [
{"name": "f1", "type": "STRING"},
{"name": "f2", "type": "INTEGER"}
]
},
"destinationTable": {
"projectId": "projectId",
"datasetId": "datasetId",
"tableId": "tableId"
}
}
}
}