Create Campaign Experiment

Java

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.campaignmanagement;

import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v9.enums.CampaignExperimentTrafficSplitTypeEnum.CampaignExperimentTrafficSplitType;
import com.google.ads.googleads.v9.errors.GoogleAdsError;
import com.google.ads.googleads.v9.errors.GoogleAdsException;
import com.google.ads.googleads.v9.resources.CampaignExperiment;
import com.google.ads.googleads.v9.services.CampaignExperimentServiceClient;
import com.google.ads.googleads.v9.services.CreateCampaignExperimentMetadata;
import com.google.ads.googleads.v9.services.GoogleAdsRow;
import com.google.ads.googleads.v9.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v9.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v9.utils.ResourceNames;
import com.google.api.gax.longrunning.OperationFuture;
import com.google.protobuf.Empty;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

/** Adds a campaign experiment for a draft campaign. */
public class CreateCampaignExperiment {
  public static class CreateCampaignExperimentParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    public long customerId;

    @Parameter(names = ArgumentNames.BASE_CAMPAIGN_ID, required = true)
    public long baseCampaignId;

    @Parameter(names = ArgumentNames.DRAFT_ID, required = true)
    public long draftId;
  }

  public static void main(String[] args) {
    CreateCampaignExperimentParams params = new CreateCampaignExperimentParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.baseCampaignId = Long.valueOf("INSERT_CAMPAIGN_ID_HERE");
      params.draftId = Long.parseLong("INSERT_DRAFT_ID_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      System.exit(1);
    }

    try {
      new CreateCampaignExperiment()
          .runExample(googleAdsClient, params.customerId, params.baseCampaignId, params.draftId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID to operate on.
   * @param baseCampaignId the original campaign ID.
   * @param draftId the ID of a draft campaign.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient, long customerId, long baseCampaignId, long draftId) {
    // Creates the campaign experiment. Here we obtain a metadata object, rather than the full
    // entity. This is because the experiment is created asynchronously via the long running
    // operations API. We can use the information in the metadata to retrieve the entity, if
    // required.
    CreateCampaignExperimentMetadata metadata =
        createExperiment(googleAdsClient, customerId, baseCampaignId, draftId);

    // Logs the created resource name.
    System.out.printf(
        "Created campaign experiment with resource name: %s%n", metadata.getCampaignExperiment());

    // Prints additional details about the status of the experiment.
    printExperimentDetails(googleAdsClient, customerId, metadata);
  }

  /**
   * Creates an experiment by issuing an asynchronous operation and immediately blocking to get the
   * result.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID to operate on.
   * @param baseCampaignId the original campaign ID.
   * @param draftId the draft campaign ID.
   * @return a newly created experiment.
   */
  private CreateCampaignExperimentMetadata createExperiment(
      GoogleAdsClient googleAdsClient, long customerId, long baseCampaignId, long draftId) {
    // Defines the experiment to be created.
    CampaignExperiment experiment =
        CampaignExperiment.newBuilder()
            .setCampaignDraft(ResourceNames.campaignDraft(customerId, baseCampaignId, draftId))
            .setName("Campaign experiment #" + getPrintableDateTime())
            .setTrafficSplitPercent(50)
            .setTrafficSplitType(CampaignExperimentTrafficSplitType.RANDOM_QUERY)
            .build();

    // Creates an API service client.
    try (CampaignExperimentServiceClient campaignExperimentServiceClient =
        googleAdsClient.getLatestVersion().createCampaignExperimentServiceClient()) {
      // Issues the create request.
      OperationFuture<Empty, CreateCampaignExperimentMetadata> campaignExperimentAsync =
          campaignExperimentServiceClient.createCampaignExperimentAsync(
              String.valueOf(customerId), experiment);

      // Block on the long running (i.e. async) operation result.
      try {
        return campaignExperimentAsync.getMetadata().get();
      } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException("Create operation failed", e);
      }
    }
  }

  /**
   * Retrieves a CampaignExperiment and prints associated information.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID to use.
   * @param metadata the experiment to retrieve information from.
   */
  private void printExperimentDetails(
      GoogleAdsClient googleAdsClient, long customerId, CreateCampaignExperimentMetadata metadata) {
    // Defines a basic query to retrieve the experiment.
    String query =
        "SELECT campaign_experiment.experiment_campaign"
            + " FROM campaign_experiment"
            + " WHERE campaign_experiment.resource_name = '"
            + metadata.getCampaignExperiment()
            + "'";

    // Creates an API client.
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      // Issues a search request.
      SearchPagedResponse response =
          googleAdsServiceClient.search(String.valueOf(customerId), query);

      // Iterates through the results and prints the information returned.
      for (GoogleAdsRow row : response.iterateAll()) {
        System.out.printf(
            "Experiment campaign with resource name = '%s' created successfully.%n",
            row.getCampaignExperiment().getResourceName());
      }
    }
  }
}

      

C#

// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V9.Errors;
using Google.Ads.GoogleAds.V9.Resources;
using Google.Ads.GoogleAds.V9.Services;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V9.Enums.CampaignExperimentTrafficSplitTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V9
{
    /// <summary>
    /// This code example adds a campaign experiment for a draft campaign.
    /// </summary>
    public class CreateCampaignExperiment : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="CreateCampaignExperiment"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// ID of the base campaign.
            /// </summary>
            [Option("baseCampaignId", Required = true, HelpText =
                "ID of the base campaign.")]
            public long BaseCampaignId { get; set; }

            /// <summary>
            /// ID of the draft campaign.
            /// </summary>
            [Option("draftId", Required = true, HelpText =
                "ID of the draft campaign.")]
            public long DraftId { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = new Options();
            CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
                delegate (Options o)
                {
                    options = o;
                    return 0;
                }, delegate (IEnumerable<Error> errors)
                {
                    // The Google Ads customer ID for which the call is made.
                    options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

                    // ID of the base campaign.
                    options.BaseCampaignId = long.Parse("INSERT_BASE_CAMPAIGN_ID_HERE");

                    // ID of the draft campaign.
                    options.DraftId = long.Parse("INSERT_DRAFT_ID_HERE");

                    return 0;
                });

            CreateCampaignExperiment codeExample = new CreateCampaignExperiment();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.BaseCampaignId,
                options.DraftId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example adds a campaign experiment for a draft campaign.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="baseCampaignId">ID of the base campaign.</param>
        /// <param name="draftId">ID of the draft campaign.</param>
        public void Run(GoogleAdsClient client, long customerId, long baseCampaignId, long draftId)
        {
            try
            {
                string campaignDraftResourceName = ResourceNames.CampaignDraft(
                    customerId, baseCampaignId, draftId);
                Operation<Empty, CreateCampaignExperimentMetadata> operation =
                    CreateExperiment(client, customerId, campaignDraftResourceName);

                Console.WriteLine("Waiting until operation completes...");
                operation.PollUntilCompleted();

                DisplayExperimentDetails(client, customerId, operation.Metadata.CampaignExperiment);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates an experiment.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignDraftResourceName">The resource name Name of the campaign
        /// draft.</param>
        /// <returns>The long running operation for experiment creation.</returns>
        private static Operation<Empty, CreateCampaignExperimentMetadata>
            CreateExperiment(GoogleAdsClient client, long customerId,
                string campaignDraftResourceName)
        {
            // Get the CampaignExperimentService.
            CampaignExperimentServiceClient campaignExperimentService =
                client.GetService(Services.V9.CampaignExperimentService);

            CampaignExperiment experiment = new CampaignExperiment()
            {
                CampaignDraft = campaignDraftResourceName,
                Name = "Campaign Experiment - " + ExampleUtilities.GetRandomString(),
                TrafficSplitPercent = 50,
                TrafficSplitType = CampaignExperimentTrafficSplitType.RandomQuery
            };

            Operation<Empty, CreateCampaignExperimentMetadata> operation =
                campaignExperimentService.CreateCampaignExperiment(
                    customerId.ToString(), experiment);

            string experimentResourceName = operation.Metadata.CampaignExperiment;
            Console.WriteLine($"Created campaign experiment with resource name " +
                $"{experimentResourceName}");

            return operation;
        }

        /// <summary>
        /// Fetches an experiment and display its details.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="experimentResourceName">Resource name of the experiment.</param>
        /// <returns></returns>
        private static void DisplayExperimentDetails(GoogleAdsClient client, long customerId,
            string experimentResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService =
                client.GetService(Services.V9.GoogleAdsService);

            // Once the draft is created, you can modify the draft campaign as if it were
            // a real campaign. For example, you may add criteria, adjust bids, or even
            // include additional ads. Adding a criterion is shown here.
            string query = $@"
                SELECT
                    campaign_experiment.experiment_campaign
                FROM
                    campaign_experiment
                WHERE
                    campaign_experiment.resource_name = '{experimentResourceName}'";

            // Get the expriment campaign resource name.
            string experimentCampaignResourceName = googleAdsService.Search(
                customerId.ToString(), query).First().CampaignExperiment.ExperimentCampaign;

            Console.WriteLine($"Experiment campaign with resource ID =" +
                $" '{experimentCampaignResourceName}' finished creating.");
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\CampaignManagement;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V9\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V9\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V9\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V9\ResourceNames;
use Google\Ads\GoogleAds\V9\Enums\CampaignExperimentTrafficSplitTypeEnum\CampaignExperimentTrafficSplitType;
use Google\Ads\GoogleAds\V9\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V9\Resources\CampaignExperiment;
use Google\Ads\GoogleAds\V9\Services\GoogleAdsRow;
use Google\ApiCore\ApiException;

/**
 * This example illustrates how to begin creation of a campaign experiment from a draft and wait
 * for it to complete.
 */
class CreateCampaignExperiment
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const BASE_CAMPAIGN_ID = 'INSERT_BASE_CAMPAIGN_ID_HERE';
    private const DRAFT_ID = 'INSERT_DRAFT_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::BASE_CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::DRAFT_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::BASE_CAMPAIGN_ID] ?: self::BASE_CAMPAIGN_ID,
                $options[ArgumentNames::DRAFT_ID] ?: self::DRAFT_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param int $baseCampaignId the base campaign ID
     * @param int $draftId the draft ID used to create an experiment
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $baseCampaignId,
        int $draftId
    ) {
        // Creates a campaign experiment.
        $campaignExperiment = new CampaignExperiment([
            'campaign_draft'
                => ResourceNames::forCampaignDraft($customerId, $baseCampaignId, $draftId),
            'name' => 'Campaign Experiment #' . Helper::getPrintableDatetime(),
            'traffic_split_percent' => 50,
            'traffic_split_type' => CampaignExperimentTrafficSplitType::RANDOM_QUERY
        ]);

        // Issues an asynchronous request to create the campaign experiment. This will return
        // `Google\LongRunning\Operation` (LRO).
        $campaignExperimentServiceClient = $googleAdsClient->getCampaignExperimentServiceClient();
        $operationResponse = $campaignExperimentServiceClient->createCampaignExperiment(
            $customerId,
            $campaignExperiment
        );

        // Prints some info about the process and the campaign experiment resource name.
        $campaignExperimentResourceName =
            $operationResponse->getMetadata()->getCampaignExperiment();
        printf(
            'Asynchronous request to create campaign experiment with resource name "%1$s"'
            . ' started.%2$sWaiting until operation completes.%2$s',
            $campaignExperimentResourceName,
            PHP_EOL
        );

        // pollUntilComplete() implements a default back-off policy for retrying. You can tweak the
        // retrying parameters like the maximum polling interval to use by passing them as an array
        // to the pollUntilComplete() function. Visit the OperationResponse.php file for more
        // details.
        $operationResponse->pollUntilComplete();

        // Fetches information about the created experiment campaign and prints out its resource
        // name.
        $query = "SELECT campaign_experiment.experiment_campaign FROM campaign_experiment"
            . " WHERE campaign_experiment.resource_name = '$campaignExperimentResourceName'";
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        $response = $googleAdsServiceClient->search($customerId, $query);
        /** @var GoogleAdsRow $googleAdsRow */
        $googleAdsRow = $response->getIterator()->current();
        printf(
            "Experiment campaign with resource name '%s' finished creating.%s",
            $googleAdsRow->getCampaignExperiment()->getExperimentCampaign(),
            PHP_EOL
        );
    }
}

CreateCampaignExperiment::main();

      

Python

#!/usr/bin/env python
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This demonstrates how to create a campaign experiment.

It requests the creation based on a draft and waits for completion.
"""


import argparse
import sys
import uuid

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id, base_campaign_id, draft_id):
    # Create the campaign experiment.
    campaign_experiment = client.get_type("CampaignExperiment")
    campaign_draft_service = client.get_service("CampaignDraftService")
    campaign_draft_resource_name = campaign_draft_service.campaign_draft_path(
        customer_id, base_campaign_id, draft_id
    )

    campaign_experiment.campaign_draft = campaign_draft_resource_name
    campaign_experiment.name = f"Campaign Experiment #{uuid.uuid4()}"
    campaign_experiment.traffic_split_percent = 50
    campaign_experiment.traffic_split_type = (
        client.enums.CampaignExperimentTrafficSplitTypeEnum.RANDOM_QUERY
    )

    try:
        campaign_experiment_service = client.get_service(
            "CampaignExperimentService"
        )

        # A Long Running Operation (LRO) is returned from this
        # asynchronous request by the API.
        campaign_experiment_lro = (
            campaign_experiment_service.create_campaign_experiment(
                customer_id=customer_id, campaign_experiment=campaign_experiment
            )
        )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

    print(
        "Asynchronous request to create campaign experiment with "
        "resource name "
        f'"{campaign_experiment_lro.metadata.campaign_experiment}" started.'
    )
    print("Waiting until operation completes.")

    # Poll until the operation completes.
    campaign_experiment_lro.result()

    # Retrieve the campaign experiment that has been created.
    ga_service = client.get_service("GoogleAdsService")
    request = client.get_type("SearchGoogleAdsRequest")
    request.customer_id = customer_id
    request.query = f'''
        SELECT campaign_experiment.experiment_campaign
        FROM campaign_experiment
        WHERE campaign_experiment.resource_name =
        "{campaign_experiment_lro.metadata.campaign_experiment}"'''

    results = ga_service.search(request=request)

    try:
        for row in results:
            print(
                "Experiment campaign "
                f'"{row.campaign_experiment.experiment_campaign}" '
                "creation completed."
            )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v9")

    parser = argparse.ArgumentParser(
        description=("Create a campaign experiment based on a campaign draft.")
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    parser.add_argument(
        "-i",
        "--base_campaign_id",
        type=str,
        required=True,
        help="The base campaign id.",
    )
    parser.add_argument(
        "-d", "--draft_id", type=str, required=True, help="The id of the draft."
    )
    args = parser.parse_args()

    main(
        googleads_client, args.customer_id, args.base_campaign_id, args.draft_id
    )

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example illustrates how to begin creation of a campaign experiment from
# a draft and wait for it to complete.

require 'optparse'
require 'google/ads/google_ads'
require 'date'

def create_campaign_experiment(customer_id, campaign_id, draft_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new
  campaign_draft_resource_name = client.path.campaign_draft(
      customer_id, campaign_id, draft_id)

  experiment = client.resource.campaign_experiment do |ce|
    ce.campaign_draft = campaign_draft_resource_name
    ce.name = "Campaign Experiment ##{(Time.new.to_f * 1000).to_i}"
    ce.traffic_split_percent = 50
    ce.traffic_split_type = :RANDOM_QUERY
  end

  # A Gapic::Operation is returned from this asynchronous request by the API,
  # and is converted into a Google::Gax::Operation automatically.
  operation = client.service.campaign_experiment.create_campaign_experiment(
    customer_id: customer_id,
    campaign_experiment: experiment,
  )

  puts "Asynchronous request to create campaign experiment with " +
    "resource name #{operation.metadata.campaign_experiment} started."

  puts "Waiting until operation completes."

  # The wait_until_done! method implements a default backoff policy for
  # retrying.
  # You can also use operation.refresh! to make a call to the API to check
  # whether the LRO is finished, and operation.done? after refreshing to check
  # the status, if you'd rather implement your own backoff logic.
  operation.wait_until_done! do |op|
    raise op.results.message if operation.error?
  end

  query = <<~EOQUERY
    SELECT campaign_experiment.experiment_campaign
    FROM campaign_experiment
    WHERE campaign_experiment.resource_name = "#{operation.metadata.campaign_experiment}"
  EOQUERY

  response = client.service.google_ads.search(customer_id: customer_id, query: query)
  puts "Experiment campaign #{response.first.campaign_experiment.experiment_campaign}" \
      " finished creating."
end

if __FILE__ == $0

  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  # You can get these values by extracting them from the resource name
  # for a draft:
  # customers/{customer_id}/campaignDrafts/{base_campaign_id}~{draft_id}
  options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
  options[:draft_id] = 'INSERT_DRAFT_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: add_campaigns.rb [options]')

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-c', '--base-campaign-id CAMPAIGN-ID', String, 'Base Campaign ID') do |v|
      options[:campaign_id] = v
    end

    opts.on('-d', '--draft-id DRAFT-ID', String, 'Draft ID') do |v|
      options[:draft_id] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    create_campaign_experiment(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:campaign_id),
      options.fetch(:draft_id),
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Perl

#!/usr/bin/perl -w
#
# Copyright 2019, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example illustrates how to begin creation of a campaign experiment from a
# draft and wait for it to complete.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V9::Resources::CampaignExperiment;
use Google::Ads::GoogleAds::V9::Enums::CampaignExperimentTrafficSplitTypeEnum
  qw(RANDOM_QUERY);
use Google::Ads::GoogleAds::V9::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id      = "INSERT_CUSTOMER_ID_HERE";
my $base_campaign_id = "INSERT_BASE_CAMPAIGN_ID_HERE";
my $draft_id         = "INSERT_DRAFT_ID_HERE";

sub create_campaign_experiment {
  my ($api_client, $customer_id, $base_campaign_id, $draft_id) = @_;

  # Create a campaign experiment.
  my $campaign_experiment =
    Google::Ads::GoogleAds::V9::Resources::CampaignExperiment->new({
      campaignDraft =>
        Google::Ads::GoogleAds::V9::Utils::ResourceNames::campaign_draft(
        $customer_id, $base_campaign_id, $draft_id
        ),
      name                => "Campaign Experiment #" . uniqid(),
      trafficSplitPercent => 50,
      trafficSplitType    => RANDOM_QUERY
    });

  # A Long Running Operation (LRO) is returned from this asynchronous request
  # by the API.
  my $campaign_experiment_lro =
    $api_client->CampaignExperimentService()->create({
      customerId         => $customer_id,
      campaignExperiment => $campaign_experiment
    });

  printf "Asynchronous request to create campaign experiment with " .
    "resource name '%s' started.\n",
    $campaign_experiment_lro->{metadata}{campaignExperiment};

  printf "Waiting until operation completes.\n";

  # Poll until the operation completes.
  $campaign_experiment_lro = $api_client->OperationService()->poll_until_done({
      name => $campaign_experiment_lro->{name}});

  # Retrieve the campaign experiment that has been created.
  my $search_query =
    sprintf "SELECT campaign_experiment.experiment_campaign " .
    "FROM campaign_experiment " .
    "WHERE campaign_experiment.resource_name = '%s'",
    $campaign_experiment_lro->{metadata}{campaignExperiment};

  my $search_response = $api_client->GoogleAdsService()->search({
    customerId => $customer_id,
    query      => $search_query
  });

  printf "Experiment campaign '%s' finished creation.\n",
    $search_response->{results}[0]{campaignExperiment}{experimentCampaign};

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"      => \$customer_id,
  "base_campaign_id=i" => \$base_campaign_id,
  "draft_id=i"         => \$draft_id
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id, $base_campaign_id, $draft_id);

# Call the example.
create_campaign_experiment($api_client, $customer_id =~ s/-//gr,
  $base_campaign_id, $draft_id);

=pod

=head1 NAME

create_campaign_experiment

=head1 DESCRIPTION

This example illustrates how to begin creation of a campaign experiment from a
draft and wait for it to complete.

=head1 SYNOPSIS

create_campaign_experiment.pl [options]

    -help                            Show the help message.
    -customer_id                     The Google Ads customer ID.
    -base_campaign_id                The base campaign ID.
    -draft_id                        The draft ID used to create an experiment

=cut