POST vs. GET request differences in Google Analytics API Version 4 - google-analytics-api

Google Analytics v4 API now uses POST requests instead of GET request. And there are no good javascript examples out there yet for me to follow. I'm getting empty object Object { }, but I'm sure that data is there and ViewID is correct!
Any advice on what I am doing wrong? or are there any fully working example that I can follow? Thanks.
requestData = function () {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var params = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{
"startDate":"yesterday",
"endDate":"today"
}],
"metrics":[{
"expression":"ga:users"
}],
"dimensions": [{
"name":"ga:pagePath"
}]
}]
}
$.ajax({
url: url,
type: "POST",
data: params,
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});

I would highly recommend you use the Google Javascript Client Library to simplify your life greatly. There are plenty of Code Samples using said library:
var DISCOVERY = 'https://analyticsreporting.googleapis.com/$discovery/rest';
// Load the API from the client discovery URL.
gapi.client.load(DISCOVERY).then(function() {
// Call the Analytics Reporting API V4 batchGet method.
gapi.client.analyticsreporting.reports.batchGet( {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}).then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}).then(null, function(err) {
// Log any errors.
console.log(err);
});
As for getting jQuery to work, a similar question was asked about nodejs Their solution was to set the content-type=application/json which fortunatly has been Asked and answered as well.
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";
var data = {
"reportRequests":[{
"viewId":"12345678",
"dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
"metrics":[{"expression":"ga:users"}],
"dimensions": [{"name":"ga:pagePath"}]
}]
}
$.ajax({
url: url,
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(results) {
console.log(results)
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed');
alert(xhr.status);
alert(thrownError);
}
});

Related

How do I perform a Bulk Write operation using the MongoDB Atlas Data API?

I am using the MongoDB Data API on Atlas from a serverless function, and I’m attempting to update many documents (thousands) with different values for each. Reading through the Data API documentation it seems as though there is no /bulk or /bulkWrite action available.
In this case I have the document _id’s of each document I’d like to update and their respective changes. I attempted to add them all to a bulk update array like so:
const userIds = ['123', 'abc', '567', ...];
let bulkArr = [];
for (const id of userIds) {
bulkArr.push({
updateOne: {
filter: { _id: { $oid: id} },
update: { $addToSet: { someArray: 'some value' } },
},
});
}
Then I tried making a request like this:
var requestData = JSON.stringify({
collection: "<collection>",
database: "<database>",
dataSource: "<datasource>",
operations: bulkArr,
});
var config = {
method: "post",
url: "https://data.mongodb-api.com/app/data-somekey/endpoint/data/v1/action/bulkWrite",
headers: {
"Content-Type": "application/json",
"Access-Control-Request-Headers": "*",
"api-key": "<api_key>",
},
data: requestData,
};
await axios(config)
.then(function (response) {
return response;
})
.catch(function (error) {
console.error({
status: error.response.status,
message: "Update failed: " + error.response.statusText,
});
return error;
});
This returns a 404. How can I perform a bulk update operation that is similar to this? Thanks!

Sharepoint REST - Delete item from list

i would like to delete item from list in SharePoint 2016. I use SharePoint REST API, but I cannot successfully delete item. This is error message (http code 400):
A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry.A 'StartObject' node was expected.
Here is my code:
$.ajax({
url: 'https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items?$filter=ID eq '5'',
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method-Override": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
What is incorrect? Thanks
Please use below code: It works fine for me :
$.ajax({
url: "https://myshp.com/test/_api/web/lists(guid'e23e21c7-ab29-445e-87b8-2b20b721f79d')/items(5)",
type: 'POST',
contentType: 'application/json;odata=verbose',
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
})

Error while setting up Extjs Rest Proxy Create function

I am using Rest proxy in Extjs Model as:
Ext.define('ThemeApp.model.peopleModel', {
extend: 'Ext.data.Model', fields: [
{ name: 'userId' },
{ name: 'title' },
{ name: 'body'}
],
proxy: {
type: 'rest',
format: 'json',
limitParam:"",
filterParam: "",
startParam:'',
pageParam:'',
url:'http://jsonplaceholder.typicode.com/posts/1',
api: {
read : 'http://jsonplaceholder.typicode.com/posts/1',
create: 'http://httpbin.org/post'},
headers: {'Content-Type': "application/json" },
reader: {
type: 'json',
//rootProperty:'issues'
},
writer: {
type: 'json'
}
In my view I am calling create function as:
var user = Ext.create('posts', {"userId": 124,"title": "sunt","body": "quia"});
user.save();
As I am testing everything on http://jsonplaceholder.typicode.com/ so I am expecting that code will work cause when I test GET and POST functionality via Postman utility everything works fine.
Can anyone point out my error?
I found my mistake.
In the following code I was not setting the correct name of my model, as it won't be "Posts"
var user = Ext.create('posts', {"userId": 124,"title": "sunt","body": "quia"});
user.save();
Also if you are trying with http://jsonplaceholder.typicode.com/ you are not supposed to send ID in the post request.

Is it possible to change the header config of an AngularJS $resource object?

Here's my code:
var userAuth;
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
userAuth = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: {
'Authorization': userAuth
}
}
});
I want to be able to use the updated contents of the userAuth variable in the headers of the current endpoint of the resource, after it has been modified in the transformResponse of the login call. Is this even possible? If so, how?
EDIT: I am using Angular version 1.1.3 - this question is about changing the headers in the resource once they have been set, not settings them initially. Thanks
Assuming you are using the current stable release (1.0.8), although this feature is documented in the $resource page it has not been released.
AngularJS resource not setting Content-Type
EDIT:
See my comment below for the explaination of this code.
var customerHeaders = {
'Authorization' : ''
};
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
customHeaders.Authorization = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: customHeaders
}
});

ASP.NET MVC 2: jQuery post string is null?

I'm not sure what's the issue, but I'm constructing a string and trying to pass it to my Controller Action. But when the action is executed, the data is null.
JavaScript:
var xml = "<Request><ZipCode>92612</ZipCode></Request>";
$.ajax({
url: "/Home/GetXml",
contentType: 'application/text; charset=utf-8',
data: xml,
success: function (result) { success(result); },
type: "POST",
datatype: "text"
});
Controller:
[HttpPost]
public ActionResult GetXml(string data)
{
if (!String.IsNullOrEmpty(data))
{
return View("Index", data);
}
return View("Index");
}
If I set a breakpoint on the if, the "data" is null. What gives?
The answer: don't use contentType
Thanks to this question and answer:
Asp.Net Mvc JQuery ajax input parameters are null
try with
$.ajax({
url: "/Home/GetXml",
contentType: 'application/text; charset=utf-8',
data: { data: xml },
success: function (result) { success(result); },
type: "POST",
datatype: "text"
});