Google Search Console API Error 400 "parseError" - google-apps-script

I try to retrieve data from the Google Search Console from Google Apps Script. Here's the script :
var token = getAccessToken()
var siteUrl = "https%3A%2F%2Fpeachday.co"
var payload ={
"startDate": "2020-04-01",
"endDate": "2020-04-21",
"dimensions": [
"query"
]
}
var params = {
'Content-type': 'application/json',
'method':'post',
'headers': {
'Authorization': 'Bearer ' + token
},
'payload':JSON.stringify(payload)
}
var url = "https://www.googleapis.com/webmasters/v3/sites/" + siteUrl + "/searchAnalytics/query";
var response = UrlFetchApp.fetch(url, params)
Logger.log(response)
}
But I get that error
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "This API does not support parsing form-encoded input."
}
],
"code": 400,
"message": "This API does not support parsing form-encoded input."
}
}
Has someone faced that problem ?

Related

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

Cloud build API deploy:run on Google Apps Script doesn't work

I confirmed authorization with service account on GAS. "list" is work, but "run" method never work. Error msg is "source must not be empty". What kind of json should I attach?
This is on standalone GAS using GSApp library. (Apps-Script-GSApp-Library : MJ5317VIFJyKpi9HCkXOfS0MLm9v2IJHf)
function deploy() {
var jsonKey = JSON.parse(PropertiesService.getScriptProperties().getProperty("jsonKey"));
var serverToken = new GSApp.init(jsonKey.private_key, ["https://www.googleapis.com/auth/cloud-platform"], jsonKey.client_email);
var tokens = serverToken.addUser(jsonKey.client_email).requestToken().getTokens();
var url = "https://cloudbuild.googleapis.com/v1/projects/{ProjectId}/triggers/{TriggerId}:run";
var options = {
"muteHttpExceptions": true,
"method": "POST",
"headers": {
"Authorization":"Bearer "+tokens[jsonKey.client_email].token,
},
"source": {
"projectId": "{ProjectId}",
"branchName": "master",
"repoName": "repo"
}
}
Logger.log(UrlFetchApp.fetch(url,options));
}
{
"error": {
"code": 400,
"message": "source must not be empty",
"status": "INVALID_ARGUMENT"
}
}
UrlFetchApp.fetch() does not recognize "source" as a valid property. Use "payload" instead. Also you'll need to JSON.stringify() your payload and set the contentType property as application/json as follows:
var options = {
"muteHttpExceptions": true,
"method": "POST",
"contentType":"application/json",
"headers": {
"Authorization":"Bearer "+tokens[jsonKey.client_email].token,
},
"payload": JSON.stringify({
"projectId": "{ProjectId}",
"branchName": "master",
"repoName": "repo"
})
};

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.

Changing gsuite signature with apps script returns "isDefault cannot be toggled to false"

Trying to set a signature for users using Google Apps Script. I've set up a service account and made sure the scopes are right, but when I test the code it returns the following error:
"error": {
"errors": [
{
"domain": "global",
"reason": "invalidArgument",
"message": "isDefault cannot be toggled to false"
}
],
"code": 400,
"message": "isDefault cannot be toggled to false"
}
}
Code is as below:
function setUserSignature() {
var resource ={
"sendAsEmail": "email#mycompany.be",
"displayName": "Name Lastname",
"replyToAddress": "email#mycompany.be",
"signature": "Test Signature",
"isDefault": true,
"treatAsAlias": true
}
var service = serviceAccount("serviceaccount#mydomain.be");
service.reset();
if (service.hasAccess()) {
var options = {
"muteHttpExceptions":true,
"method":"PUT",
"headers": {"authorization": "Bearer " + service.getAccessToken()},
"body":resource
}
var url = 'https://www.googleapis.com/gmail/v1/users/'+ 'email#mycompany.be' +'/settings/sendAs/'+'email#alias.be';
var response = UrlFetchApp.fetch(url,options);
Logger.log(response.getContentText());
}
}
In case anyone else is having the same problem:
Apparently using PATCH instead of PUT solved the issue.

Insert post Blogger API failed in GAS

hi all iam trying insert post using GAS but failed.. can you tell me what im wrong... thx in advance....
here my code
`function sendHttpPost() {
var API_KEY = 'my api key';
var scope = "http://www.blogger.com/feeds/";
var oAuthConfig = UrlFetchApp.addOAuthService("blogger");
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "486683248036684073"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}
var options =
{
"contentType":"application/json",
"oAuthServiceName" : "blogger",
"oAuthUseToken" : "always",
"method" : "POST",
"payload" : payload
};
var respon = UrlFetchApp.fetch("https://www.googleapis.com/blogger/v3/blogs/486683248036684073/posts?key="+API_KEY, options);
and here is error message
Request failed for returned code 400. Server response: { "error": {
"errors": [ { "domain": "global", "reason": "parseError", "message":
"Parse Error" } ], "code": 400, "message": "Parse Error" } }
I believe you are trying to use oauth1 when oauth2 is required.
there already is a unanswered request about that here.
Implementing oauth 2 with Google app script is really a pain, so I made an attempt to build a library that could answer the need (dioxygen library) - it work a little bit like the oauth2 playground but it's less pretty.
With a little work you should be able to adapt it to your need with blogger.
I tried Harold's library, but after successfully retrieving OAuth token, I ended up with the same error.
But, when I issued the same JSON request as in my script through the API Explorer, it was processed:
https://developers.google.com/blogger/docs/3.0/reference/posts/insert
[UPDATE]
I am taking it back. This code works. I just replaced the payload variable and put the JSON request straight into URL fetch options. So there was some problem with passing that payload variable into options variable.
function testBlogger() {
var payload =
{
"kind": "blogger#post",
"blog": {
"id": "YOUR_BLOG_ID"
},
"title": "New post",
"content": "With content..."
};
var options =
{
"method" : "post",
"headers" : { "Authorization" : "Bearer YOUR_ACTIVE_TOKEN"},
"contentType" : "application/json",
"payload" : '{ "kind": "blogger#post", "blog": { "id": "YOUR_BLOG_ID" }, "title": "New post", "content": "With content..." }'
};
try {
var result = UrlFetchApp.fetch(
"https://www.googleapis.com/blogger/v3/blogs/YOUR_BLOG_ID/posts",
options);
Logger.log(result);
} catch (e) {
Logger.log(e);
}
}