Google Apps Script call Address Validation API - google-apps-script

Simple code and straightforward. It works with postman but fails with Apps Script.
function validateAddress () {
const url = 'https://addressvalidation.googleapis.com/v1:validateAddress?key=';
const apikey = '...';
let payload, options, temp;
payload = JSON.stringify({
"address": {
"addressLines": "1600 Amphitheatre Pkwy"
}
});
options = {
'muteHttpExceptions': true,
'method': 'POST',
'Content-Type': 'application/json',
'body': payload
}
temp = UrlFetchApp.fetch(url + apikey, options);
Logger.log(temp)
}
Error:
{
"error": {
"code": 400,
"message": "Address is missing from request.",
"status": "INVALID_ARGUMENT"
}
}
EDIT:
Change options to
options = {
'muteHttpExceptions': true,
'method': 'POST',
'Content-Type': 'application/json',
'payload': payload
}
Gives error:
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}\": Cannot bind query parameter. Field '{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}\": Cannot bind query parameter. Field '{\"address\":{\"addressLines\":\"1600 Amphitheatre Pkwy\"}}' could not be found in request message."
}
]
}
]
}
}
Documentation:
https://developers.google.com/maps/documentation/address-validation/requests-validate-address

From the documentation, it seems that addressLines is an array of string, not a string. Does that change something ? (I don't have a key, so I cannot try myself).
And more important, your options object is incorrect (check doc). It should be
options = {
'muteHttpExceptions': true,
'method': 'POST',
'contentType': 'application/json',
'payload': payload
}

I don't know why it works but changed options to
options = {
'muteHttpExceptions': true,
'method': 'POST',
'headers': {
'Content-Type': 'application/json'
},
'payload': payload
}
Solves the problem.

Related

How to create post using Google My Business API - Google Apps Script

I can't figure out why I'm getting the below error when I attempt to create a post with the GMB API in Google Apps Script. I'm following this documentation https://developers.google.com/my-business/content/posts-data
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.mybusiness.v4.ValidationError",
"errorDetails": [
{
"code": 2,
"field": "summary",
"message": "Standard local post must have at least a media or summary."
}
]
}
]
}
}
Here is my script
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I tried the following adaption, but it did not work
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
payload: {
languageCode: "en",
topicType: "STANDARD",
summary: "New Release!",
callToAction: {
actionType: "ORDER",
url: "https://www.artivem.com/"
},
media: {
sourceUrl: "https://untappd.akamaized.net/photos/2021_04_16/ccff4c358e362ce3c4835fcc94549a8f_640x640.jpg",
mediaFormat: "PHOTO"
}
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
Thanks in advance!
The request object needs to go into the payload. "payload" is a parameter of the options.
function callToActionPost() {
var url = 'https://mybusiness.googleapis.com/v4/accounts/123/locations/456/localPosts';
var payload = {
"languageCode": "en-US",
"summary": "New Release!",
"callToAction": {
"actionType": "ORDER",
"url": "https://www.artivem.com/"
},
"media": [{
"sourceUrl": "https://untappd.akamaized.net/photos/2021_04_16/9999999999999999.jpg",
"mediaFormat": "PHOTO"
}]
}
var options = {
headers: { Authorization: "Bearer " + getGMBService_().getAccessToken() },
method: 'POST',
muteHttpExceptions: true,
'contentType': 'application/json',
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
if (response.getResponseCode() !== 200) {
console.log("Error Code: " + response.getResponseCode());
}
}

Google calendarList not returning calendars

The following Apps Script code in a Chrome extension does not error, but return no calendars:
chrome.identity.getAuthToken({interactive: true}, function(token)
{
var init =
{
method: 'GET',
async: true,
headers:
{
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch('https://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=writer&key=' + apiKey, init)
.then(function(data)
{
log('Object ' + JSON.stringify(data));
});
});
I just get this in the console: Object {}
I saw this post and tried the suggestions, no luck. The apiKey came from the API console, and works in a different call. Thanks for any tips or pointers.
Edit #2: Here is my current manifest.json:
"oauth2": {
"client_id": "123456780416-17ur6mlc88sfot8e4s2pq05ehtkd8klh.apps.googleusercontent.com",
"scopes":[
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/contacts.readonly",
"https://www.googleapis.com/auth/calendar"
]
}
If you are passing a token into the options of the fetch request, you do not need an API key.
Modify
fetch('https://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=writer&key=' + apiKey, init)
to
fetch('https://www.googleapis.com/calendar/v3/users/me/calendarList?minAccessRole=writer', init)
and define init as
var init = {
"method":"get",
"async": true,
"muteHttpExceptions": true,
"headers": {
"Authorization": "Bearer " + token
},
"contentType": "application/json",
}
Also make sure that your token contains the necessary scopes.

Mobiledevices: action missing

I am trying to perform a POST of the action, however, when I make the request I get code 400 speaking that the action value is missing.
my code:
function mobileAPIPOST() {
var response = UrlFetchApp.fetch(
"https://www.googleapis.com/admin/directory/v1/customer/my_customer/devices/mobile/fakexQ_fake0Z0dKFdSblfakeTnnfakel7IYwixfake4ddZfakeAIvnmu/action", {
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
"Content-Type": "application/json",
},
data: {
"action": "block"
},
muteHttpExceptions: true
});
}
I updated the code following the response from #TheMaster.
My updated code:
function mobileAPIPOST() {
var response = UrlFetchApp.fetch(
"https://www.googleapis.com/admin/directory/v1/customer/my_customer/devices/mobile/fakexQ_fake0Z0dKFdSblfakeTnnfakel7IYwixfake4ddZfakeAIvnmu/action", {
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
"Content-Type": "application/json",
},
payload: {
"action": "block"
},
muteHttpExceptions: true
});
}
error pointed out:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
UrlFetchApp doesn't have a data key parameter. Use payload instead.
Reference:
UrlFetchApp
Code Snippet:
UrlFetchApp.fetch(url,
{
method: "POST",
headers: {
"Authorization": "Bearer " + ScriptApp.getOAuthToken(),
},
contentType: 'application/json',
payload: JSON.stringify({
"action": "block"
}),
muteHttpExceptions: true
});

Create new Apps Script file with the Apps Script API - Error - Invalid JSON payload received

I'm getting the error:
Invalid JSON payload received
When trying to create a new Apps Script file with the Apps Script API.
How do I fix that error?
function createNewFile() {
var d,options,payload,response,theAccessTkn,url;
theAccessTkn = ScriptApp.getOAuthToken();
//See https://developers.google.com/apps-script/api/reference/rest/v1/projects/create
url = "https://script.googleapis.com/v1/projects";
d = new Date().toString().slice(0,10);
payload = {
"title": "AA_" + d
}
options = {
"method" : "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': 'Bearer ' + theAccessTkn
},
"payload": JSON.stringify(payload)
};
response = UrlFetchApp.fetch(url,options);
Logger.log(response)
return response;
}
I have set the authorization scopes in the manifest file to avoid needing to add an OAuth library:
{
"timeZone": "America/New_York",
"oauthScopes": [
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/script.external_request"
],
"dependencies": {
},
"exceptionLogging": "STACKDRIVER"
}
I needed to add "contentType": "application/json" to the options.
options = {
"method" : "POST",
"muteHttpExceptions": true,
"headers": {
'Authorization': 'Bearer ' + theAccessTkn
},
"contentType": "application/json",
"payload": JSON.stringify(payload)
};

Posting JSON format from Google script to PandaDoc API

I am trying to create a new document in PandaDoc via de Google Scipt editor.
Everything works fine (document is created with the right name and template), but the recipients don't come through. If I post the same parameters with Postman the recipients do come through. It probably has to do with the format of the recipient parameters but I am not experienced enough to see what.
Here is my code:
function createPandaDoc() {
var formData = {
"name": "Sample Document5",
"template_uuid": "BDZRbdUt7abCbYFBBBREaL",
"recipients": [
{
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "Signer"
}
]
};
// Because payload is a JavaScript object, it will be interpreted as
// as form data. (No need to specify contentType; it will automatically
// default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options = {
'method' : 'post',
'headers' : {
Authorization : 'Bearer xxx',
contentType : 'application/json'
},
'payload' : formData
};
UrlFetchApp.fetch('https://api.pandadoc.com/public/v1/documents', options);
}
If you have any idea, please let me know!
Thanks Chris
Got it! Should have been:
function createPandaDoc() {
var formData = {
'name': 'Sample Document5',
'template_uuid': 'BDZRbdUt7abCbYFBBBREaL',
'recipients': [
{
'email': 'john#appleseed.com',
'first_name': 'John',
'last_name': 'Appleseed',
'role': 'Signer'
}
]
};
// Because payload is a JavaScript object, it will be interpreted as
// as form data. (No need to specify contentType; it will automatically
// default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options = {
'method' : 'post',
'contentType' : 'application/json',
'headers' : {
Authorization : 'Bearer xxxx'
},
'payload' : JSON.stringify(formData)
}
UrlFetchApp.fetch('https://api.pandadoc.com/public/v1/documents', options);
}