问题
I'm trying to insert an experiment to Google analytics through their api (using gapi)
var experiment = {
"name": "Testing",
"description": "test",
"status": "READY_TO_RUN",
"variations": [{
"name": "Original",
"url": "http://abc.se",
}, {
"name": "Variant 1",
"url": "http://abc.se/1",
}],
};
gapi.client.analytics.management.experiments.insert({
'accountId': currentProfile['accountId'],
'profileId': currentProfile['profileId'],
'webPropertyId': currentProfile['webPropertyId'],
'resource': experiment
}).execute(callback);
The response-code I get is "code": 500, "message": "There was an internal error.",
Any help will be mostly appreciated. (First question on stackoverflow, I apologize in advance if my question is fuzzy.)
回答1:
The solution was to add the parameter "objectiveMetric". Altough it is not specified in the documentation.
final code:
var requestBody = {
"name": "testing2", //required
"status": "READY_TO_RUN", //required
"objectiveMetric": "ga:goal11Completions", //required?
"variations": [
{
"name": "test1", //required
"status": "ACTIVE",
"url": "http://abs.se/3" //required
},
{
"name": "test2", //required
"status": "ACTIVE",
"url": "http://abs.se/4" //required
}
]
};
var request = gapi.client.request({
'path': '/analytics/v3/management/accounts/{accountId}/webproperties/{webPropertyId}/profiles/{profileId}/experiments',
'method': 'POST',
'body': JSON.stringify(requestBody)});
request.execute(handleAccounts);
}
Big thanks to Pete for the help.
回答2:
First, review the API Reference for the Experiment INSERT method.
It requires that you make a POST request, and in the request body you need to supply an Experiment resource. In this case the required property/fields are name, status, and variation names. You also need to set objectiveMetric because as per the reference, this field is required if status is "RUNNING" and servingFramework is one of "REDIRECT" or "API".
If you're using the JavaScript client then you'll need to use gapi.client.request to execute this method. You can't do it the way you've described since that will make a GET request, and you haven't supplied a request body. You need to make a POST request with a request body. Take a look at Using gapi.client.request to make REST requests.
So it would look something like:
var requestBody = {
'name': 'Testing',
'status': 'RUNNING',
'objectiveMetric': 'ga:timeOnSite',
'variations': [
{'name': 'VER 1', 'status': 'ACTIVE', 'url': 'http://abs.com/1'},
{'name': 'VER 2', 'status': 'ACTIVE', 'url': 'http://abs.com/2'}
],
};
var request = gapi.client.request({
'path': '/analytics/v3/management/accounts/YOUR_ACCOUNT_ID/webproperties/YOUR_WEBPROPERTY_ID/profiles/YOUR_PROFILE_ID/experiments',
'method': 'POST',
'body': JSON.stringify(requestBody)});
request.execute(handleAccounts);
来源:https://stackoverflow.com/questions/20387407/insert-experiment-to-google-analytics-api-gapi