Get data from Google Ads API using App Script - javascript

I wanna get out campaigns reports using Google Rest API and it does'nt work in Google ads Apps script.
My code:
function main() {
const API_VERSION = "12";
const CUSTOMER_ID = "***"; //contais real custommer ID
const DEVELOPER_TOKEN = "***"; //contais real developper ID
const MANAGER_CUSTOMER_ID = "***"; //contais real manager ID
const OAUTH2_ACCESS_TOKEN = ""; //contais real ACCES TOKEN
const data = {
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
};
const url = `https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
body: JSON.stringify(data),
"muteHttpExceptions": true
};
Logger.log(UrlFetchApp.fetch(url, options));
}
Result error:
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.ads.googleads.v12.errors.GoogleAdsFailure",
"errors": [
{
"errorCode": {
"queryError": "UNEXPECTED_END_OF_QUERY"
},
"message": "Error in query: unexpected end of query."
}
],
"requestId": "zKBR9-dJoG9NWAx3iJea2g"
}
]
}
}
But query is valid https://developers.google.com/google-ads/api/fields/v11/query_validator
enter image description here
Could you plese help?
Thanks
I wanna get out campaigns reports using Google Rest API and it does'nt work. My code and result is above.

Based on the documentation of UrlFetchApp, 'body' is not the correct option for passing in the query. You want 'payload'.
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
payload: JSON.stringify(data),
"muteHttpExceptions": true
};

Related

Sending media parameter is not working while sending it to kaleyra api through code

https://developers.kaleyra.io/docs/send-a-media-template-message-through-whatsapp
I am trying to send a media to kalerays api through my code. But it is not working when I pass from code. But When I hit the API from postman then it works fine.
async whatsappAPIWithAttachment(requestBody) {
let api_key = "";
if (requestBody.campaign) {
api_key = "x";
} else {
api_key = "Y";
}
var data = qs.stringify({
from: "xyz",
to: "xyz",
type: "mediatemplate",
channel: "whatsapp",
template_name: "xyz",
params: '"name","vendor"',
lang_code: "en",
media_url: "http://www.africau.edu/images/default/sample.pdf",
});
var config: AxiosRequestConfig = {
method: "post",
url: "https://api.kaleyra.io/v1/HXIN1707222213IN/messages",
headers: {
"api-key": api_key,
"content-type": "multipart/form-data",
},
data: data,
};
let response = await axios(config);
return response.data;
}
}
It gives me an enter image description hereerror request failed with status code 400. Here I have replaced X, Y, and XYZ with actual parameters. So Inputs are correct but still get an error saying 'E413', message: 'Invalid/incorrect inputs.
As per sample request in kaleyra documentation, they have used
--header 'Content-Type: application/json'
while you are passing
"content-type": "multipart/form-data",
pls correct it and try.
how about using double quote strings for param value
params: "\"name\",\"vendor\""

How to fetch Sleep data from Google's REST api?

I'm trying to fetch my sleep data from Google-Fit.
When I make the following request -
const { data: sleepData } = await axios({
method: 'POST',
url: 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
headers: {
Authorization: `Bearer ${accessToken}`,
},
data: {
aggregateBy: [{ dataTypeName: 'com.google.sleep.segment' }],
bucketByTime: { durationMillis: 86400000 },
startTimeMillis: startTimeQuery, // day start time in UNIX
endTimeMillis: endTimeQuery, // day end time in UNIX
},
});
I'm getting the following data with empty points -
{
"bucket": [
{
"startTimeMillis": "1651115600000",
"endTimeMillis": "1651202000000",
"dataset": [
{
"dataSourceId": "derived:com.google.sleep.segment:com.google.android.gms:merged",
"point": []
}
]
},
{
"startTimeMillis": "1651202000000",
"endTimeMillis": "1651288400000",
"dataset": [
{
"dataSourceId": "derived:com.google.sleep.segment:com.google.android.gms:merged",
"point": []
}
]
},
]}
Has anyone run into similar problems?
I'm using Google-Fit on an Android Device.
Hey here is a working example from Google Fitness REST API with my account which is connected to my sleep tracking device.
var axios = require('axios');
var data = JSON.stringify({
"aggregateBy": [
{
"dataTypeName": "com.google.sleep.segment"
}
],
"endTimeMillis": {endTimeMillis},
"startTimeMillis": {startTimeMillis}
});
var config = {
method: 'post',
url: 'https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate',
headers: {
'Authorization': 'Bearer {AccessToken}',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
The Only difference is to remove the bucketByTime so that Fitness API will send the segment points as small as possible.

Getting a callback after a request has been completed in a Gmail Add On in Apps Script

First of all what I am trying to do is accomplish the following.
Note: this is not my add-on.
How is this script generated? I cannot find any information about script.google.com/macros.
After this tab is closed, the add-on gets a callback that looks like this:
As I don't understand the flow my questions are:
How does the add-on script know that the tab is being closed?
How is the script created?
At which endpoint does the script call the google add-on?
The following is my add-on script:
function insertDocumentToRMS(e){
var url = "https://test.signumid.hr/v/1/rms";
var object = {
"data" : e.parameters.file.toString()
}
var payload = JSON.stringify(object);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
};
var options = {
"method": "POST",
"contentType": "application/json",
"headers": headers,
"payload": payload,
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
var url2 = "https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber;
Logger.log(url2);
var object2 = {
"SignatureProvider": "SwisscomAis",
"SignatureProviderData": {
"SwisscomRequestData": {
"mobileNumber": "+41796063855",
"language": "en",
"message": "Matej PotpiĆĄiii!",
"jurisdiction": "ZERTES",
"signatureLevel": "AES"
}
},
"Documents": [
{
"SignatureOptions": {
"Reason": "Reason",
"Location": "Location",
"SignerContactInfo": "SignerContactInfo",
"SignerName": "SignerName"
},
"Document": e.parameters.file.toString()
}
]
}
var payload2 = JSON.stringify(object2);
var headers2 = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
};
var options2 = {
"method": "GET",
"contentType": "application/json",
"headers": headers2,
"payload": payload2,
"muteHttpExceptions": true
};
var response2 = UrlFetchApp.fetch(url2, options2);
Logger.log(response2);
let actionSign = CardService.newAction().setFunctionName('test');
var actionResponse = CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
.setOpenAs(CardService.OpenAs.OVERLAY)
.setOnClose(CardService.OnClose.RELOAD))
.build();
return actionResponse;
}
As you can see at the end (here), I am trying to use an actionBuilder with an actionResponse that has the property OnClose, but the only parameters on OnClose are: NOTHING and RELOAD. Can I pass an action somehow or what am I supposed to do to replicate the scenario that I mentioned above?
var actionResponse = CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://test.signumid.hr/v/1/signer/document/storage/"+ data.recordNumber)
.setOpenAs(CardService.OpenAs.OVERLAY)
.setOnClose(CardService.OnClose.RELOAD))
.build();
Basically what the add-on is doing is a 'sign in workflow' to authorize scopes. If you want to replicate that workflow you can take a look at this sample provided by Google.
Aside from that you can submit a feature request to control browser events.
Looking for any alternative options I found this and this.
As for macros using Google Apps Script, you can look here.

Graphql query with $http.post does not work

The request for the code below goes all ok but I don't get any data back (Just says "Error Not Found" in the "preview" tab of the request in chrome). I try the same query in GraphiQL and it gives back relevant data. I am not sure what I am missing here. Please advise, kind of stuck with this.
PlayService.prototype.getPlays = function(playID) {
//The query.
const playsQuery = `query ($playid: String) {
plays(id: $playid) {
id
items {
nodes {
id
name
}
}
}
}`;
// variables to pass.
const variables = {
playid: playID
};
//The request.
const result = $http.post(
/graphql,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ playsQuery, variables })
}
);
return result && result.data;
};
You appear to be sending the data body as:
{
playsQuery: "<query string>",
variables: {}
}
The GraphQL spec specifies that you must follow this format for GraphQL queries over REST:
http://graphql.org/learn/serving-over-http/
{
"query": "...",
"operationName": "...",
"variables": { "myVariable": "someValue", ... }
}

github says cannot parse json while creating a repo in rest api

I'm learning REST api for github and trying to create a new repository by running a JS. Here is my function for creating a new repo: the token is generated, and all access/scopes is granted for my token.
function createNewRepo(userId, name){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": "EnableIssues",
"content-type": "application/json",
"Authorization": token,
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true,
}
};
//console.log(eval(options));
request(options, function (error, response, body)
{
var obj = JSON.parse(body);
console.log( obj );
});
}
however when running this, I find,
{ message: 'Problems parsing JSON', documentation_url: 'https://developer.github.com/v3' }
I'm not sure how exactly could the JSON be invalid.
Also, the documentation says it must include public_repo or repo which I'm also not sure how to apply here.
This for me has created the repository.
var myToken = "token INSERTHERETHETOKEN"; // <-- there must be the word token before the actual token.
var urlRoot = "https://api.github.com";
var request = require("request");
function createNewRepo(user, name, token){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": user,
// "content-type": "application/json", This is set by json:true
"Authorization": token,
"Accept": "application/vnd.github.v3+json"
},
body: {
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
},
json: true
};
request(options, function (error, response, body) {
// Do your stuff... but notice that response
// is already a json object and you don't need to parse it.
});
}
createNewRepo("YourGithubUser", "test.repository", myToken);

Categories

Resources