Search code examples
javascriptgoogle-analyticsgoogle-analytics-api

Insert experiment to Google analytics api (gapi)


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.)


Solution

  • 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.