Get Account Changes

Java

// Copyright 2018 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.

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

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.v6.errors.GoogleAdsError;
import com.google.ads.googleads.v6.errors.GoogleAdsException;
import com.google.ads.googleads.v6.resources.ChangeStatus;
import com.google.ads.googleads.v6.services.GoogleAdsRow;
import com.google.ads.googleads.v6.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v6.services.GoogleAdsServiceClient.SearchPagedResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;

/** Gets the changes in the account made in the last 7 days. */
public class GetAccountChanges {

  private static class GetAccountChangesParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;
  }

  public static void main(String[] args) {
    GetAccountChangesParams params = new GetAccountChangesParams();
    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");
    }

    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 GetAccountChanges().runExample(googleAdsClient, params.customerId);
    } 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 client instance.
   * @param customerId the customerId for which to retrieve change status.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    String query =
        "SELECT change_status.resource_name, "
            + "change_status.last_change_date_time, "
            + "change_status.resource_status, "
            + "change_status.resource_type, "
            + "change_status.ad_group, "
            + "change_status.ad_group_ad, "
            + "change_status.ad_group_bid_modifier, "
            + "change_status.ad_group_criterion, "
            + "change_status.ad_group_feed, "
            + "change_status.campaign, "
            + "change_status.campaign_criterion, "
            + "change_status.campaign_feed, "
            + "change_status.feed, "
            + "change_status.feed_item "
            + "FROM change_status "
            + "WHERE change_status.last_change_date_time DURING LAST_7_DAYS "
            + "ORDER BY change_status.last_change_date_time";

    try (GoogleAdsServiceClient client =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      SearchPagedResponse response = client.search(String.valueOf(customerId), query);

      for (GoogleAdsRow row : response.iterateAll()) {
        Optional<String> resourceNameOfChangedEntity =
            getResourceNameForResourceType(row.getChangeStatus());

        System.out.printf(
            "On '%s', change status '%s' shows a resource type of '%s' "
                + "with resource name '%s' was '%s'.%n",
            row.getChangeStatus().getLastChangeDateTime(),
            row.getChangeStatus().getResourceName(),
            row.getChangeStatus().getResourceType().name(),
            resourceNameOfChangedEntity.orElse(""),
            row.getChangeStatus().getResourceStatus().name());
      }
    }
  }

  /**
   * Each returned row contains all possible changed fields. This function returns the resource name
   * of the changed field based on the resource type. The changed field's parent is also populated
   * but is not used.
   *
   * @param changeStatus the change status for which to get affected resource name.
   * @return an Optional has a value when one could be obtained for the change resource type.
   */
  private static Optional<String> getResourceNameForResourceType(ChangeStatus changeStatus) {
    String resourceName = null;
    // This is the list of all known resource names but may be subject to change in the future.
    // See https://developers.google.com/google-ads/api/docs/change-status for a description.
    switch (changeStatus.getResourceType()) {
      case AD_GROUP:
        resourceName = changeStatus.getAdGroup();
        break;
      case AD_GROUP_AD:
        resourceName = changeStatus.getAdGroupAd();
        break;
      case AD_GROUP_BID_MODIFIER:
        resourceName = changeStatus.getAdGroupBidModifier();
        break;
      case AD_GROUP_CRITERION:
        resourceName = changeStatus.getAdGroup();
        break;
      case AD_GROUP_FEED:
        resourceName = changeStatus.getAdGroupFeed();
        break;
      case CAMPAIGN:
        resourceName = changeStatus.getCampaign();
        break;
      case CAMPAIGN_CRITERION:
        resourceName = changeStatus.getCampaignCriterion();
        break;
      case CAMPAIGN_FEED:
        resourceName = changeStatus.getCampaignFeed();
        break;
      case FEED:
        resourceName = changeStatus.getFeed();
        break;
      case FEED_ITEM:
        resourceName = changeStatus.getFeedItem();
        break;
    }
    return Optional.ofNullable(resourceName);
  }
}

C#

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

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V6.Errors;
using Google.Ads.GoogleAds.V6.Resources;
using Google.Ads.GoogleAds.V6.Services;
using Google.Protobuf;
using System;
using static Google.Ads.GoogleAds.V6.Enums.ChangeEventResourceTypeEnum.Types;
using static Google.Ads.GoogleAds.V6.Enums.ResourceChangeOperationEnum.Types;
using static Google.Ads.GoogleAds.V6.Resources.ChangeEvent.Types;

namespace Google.Ads.GoogleAds.Examples.V6
{
    /// <summary>
    /// This code example gets the changes in an account during the last 25 days.
    /// </summary>
    public class GetChangeDetails : ExampleBase
    {
        /// <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)
        {
            GetChangeDetails codeExample = new GetChangeDetails();

            Console.WriteLine(codeExample.Description);

            // The Google Ads customer ID for which the call is made.
            long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

            codeExample.Run(new GoogleAdsClient(), customerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description => "This code example gets the changes in an account " +
            "during the last 25 days.";

        /// <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>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V6.GoogleAdsService);

            // Construct a query to find details for recent changes in your account.
            // The LIMIT clause is required for the change_event resource.
            // The maximum size is 10000, but a low limit was set here for demonstrative
            // purposes.
            // The WHERE clause on change_date_time is also required. It must specify a
            // window of at most 30 days within the past 30 days.

            string startDate = DateTime.Today.Subtract(TimeSpan.FromDays(25)).ToString("yyyyMMdd");
            string endDate = DateTime.Today.Add(TimeSpan.FromDays(1)).ToString("yyyyMMdd");
            string searchQuery = $@"
                SELECT
                    change_event.resource_name,
                    change_event.change_date_time,
                    change_event.change_resource_name,
                    change_event.user_email,
                    change_event.client_type,
                    change_event.change_resource_type,
                    change_event.old_resource,
                    change_event.new_resource,
                    change_event.resource_change_operation,
                    change_event.changed_fields
                FROM
                    change_event
                WHERE
                    change_event.change_date_time >= '{startDate}' AND
                    change_event.change_date_time <= '{endDate}'
                ORDER BY
                    change_event.change_date_time DESC
                LIMIT 5";

            try
            {
                // Issue a search request.
                googleAdsService.SearchStream(customerId.ToString(), searchQuery,
                    delegate (SearchGoogleAdsStreamResponse resp)
                    {
                        // Display the results.
                        foreach (GoogleAdsRow googleAdsRow in resp.Results)
                        {
                            ChangeEvent changeEvent = googleAdsRow.ChangeEvent;
                            ChangedResource oldResource = changeEvent.OldResource;
                            ChangedResource newResource = changeEvent.NewResource;

                            bool knownResourceType = true;
                            IMessage oldResourceEntity = null;
                            IMessage newResourceEntity = null;
                            switch (changeEvent.ChangeResourceType)
                            {
                                case ChangeEventResourceType.Ad:
                                    oldResourceEntity = oldResource.Ad;
                                    newResourceEntity = newResource.Ad;
                                    break;

                                case ChangeEventResourceType.AdGroup:
                                    oldResourceEntity = oldResource.AdGroup;
                                    newResourceEntity = newResource.AdGroup;
                                    break;

                                case ChangeEventResourceType.AdGroupCriterion:
                                    oldResourceEntity = oldResource.AdGroupCriterion;
                                    newResourceEntity = newResource.AdGroupCriterion;
                                    break;

                                case ChangeEventResourceType.AdGroupBidModifier:
                                    oldResourceEntity = oldResource.AdGroupBidModifier;
                                    newResourceEntity = newResource.AdGroupBidModifier;
                                    break;

                                case ChangeEventResourceType.Campaign:
                                    oldResourceEntity = oldResource.Campaign;
                                    newResourceEntity = newResource.Campaign;
                                    break;

                                case ChangeEventResourceType.CampaignBudget:
                                    oldResourceEntity = oldResource.CampaignBudget;
                                    newResourceEntity = newResource.CampaignBudget;
                                    break;

                                case ChangeEventResourceType.CampaignCriterion:
                                    oldResourceEntity = oldResource.CampaignCriterion;
                                    newResourceEntity = newResource.CampaignCriterion;
                                    break;

                                default:
                                    knownResourceType = false;
                                    break;
                            }

                            if (!knownResourceType)
                            {
                                Console.WriteLine($"Unknown change_resource_type " +
                                    $"'{changeEvent.ChangeResourceType}'.");
                                continue;
                            }

                            Console.WriteLine($"On #{changeEvent.ChangeDateTime}, user " +
                                $"{changeEvent.UserEmail} used interface {changeEvent.ClientType} " +
                                $"to perform a(n) '{changeEvent.ResourceChangeOperation}' " +
                                $"operation on a '{changeEvent.ChangeResourceType}' with " +
                                $"resource name {changeEvent.ChangeResourceName}.");

                            foreach (string fieldMaskPath in changeEvent.ChangedFields.Paths)
                            {
                                if (changeEvent.ResourceChangeOperation ==
                                    ResourceChangeOperation.Create)
                                {
                                    object newValue = FieldMasks.GetFieldValue(
                                        fieldMaskPath, newResourceEntity);
                                    Console.WriteLine($"\t{fieldMaskPath} set to '{newValue}'.");
                                }
                                else if (changeEvent.ResourceChangeOperation ==
                                    ResourceChangeOperation.Update)
                                {
                                    object oldValue = FieldMasks.GetFieldValue(fieldMaskPath,
                                        oldResourceEntity);
                                    object newValue = FieldMasks.GetFieldValue(fieldMaskPath,
                                        newResourceEntity);

                                    Console.WriteLine($"\t{fieldMaskPath} changed from " +
                                        $"'{oldValue}' to '{newValue}'.");
                                }
                            }
                        }
                    });
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    }
}

PHP

<?php

/**
 * 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
 *
 *     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\AccountManagement;

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

use DateTime;
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsException;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\V6\Enums\ChangeClientTypeEnum\ChangeClientType;
use Google\Ads\GoogleAds\V6\Enums\ChangeEventResourceTypeEnum\ChangeEventResourceType;
use Google\Ads\GoogleAds\V6\Enums\ResourceChangeOperationEnum\ResourceChangeOperation;
use Google\Ads\GoogleAds\V6\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V6\Services\GoogleAdsRow;
use Google\ApiCore\ApiException;
use Google\Protobuf\Internal\RepeatedField;

/**
 * This example gets specific details about the most recent changes in your
 * account, including which field changed and the old and new values.
 */
class GetChangeDetails
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const PAGE_SIZE = 1000;

    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
        ]);

        // 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
            );
        } 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 customer ID
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();

        // Constructs a query to find details for recent changes in your account.
        // The LIMIT clause is required for the change_event resource.
        // The maximum size is 10000, but a low limit was set here for demonstrative
        // purposes.
        // The WHERE clause on change_date_time is also required. It must specify a
        // window of at most 30 days within the past 30 days.
        $query = 'SELECT change_event.resource_name, '
            . 'change_event.change_date_time, '
            . 'change_event.change_resource_name, '
            . 'change_event.user_email, '
            . 'change_event.client_type, '
            . 'change_event.change_resource_type, '
            . 'change_event.old_resource, '
            . 'change_event.new_resource, '
            . 'change_event.resource_change_operation, '
            . 'change_event.changed_fields '
            . 'FROM change_event '
            . sprintf(
                'WHERE change_event.change_date_time <= %s ',
                date_format(new DateTime('+1 day'), 'Ymd')
            ) . sprintf(
                'AND change_event.change_date_time >= %s ',
                date_format(new DateTime('-14 days'), 'Ymd')
            ) . 'ORDER BY change_event.change_date_time DESC '
            . 'LIMIT 5';
        // Issues a search request by specifying page size.
        // The page size is superfluous with the default limit set above, but it's
        // shown here since it's a good practice to use a reasonable page size when
        // you set a higher limit.
        $response =
            $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

        // Iterates over all rows in all pages and prints the requested field values for
        // the change event in each row.
        foreach ($response->iterateAllElements() as $googleAdsRow) {
            /** @var GoogleAdsRow $googleAdsRow */
            $changeEvent = $googleAdsRow->getChangeEvent();
            $oldResource = $changeEvent->getOldResource();
            $newResource = $changeEvent->getNewResource();

            $isResourceTypeKnown = true;
            $oldResourceEntity = null;
            $newResourceEntity = null;
            switch ($changeEvent->getChangeResourceType()) {
                case ChangeEventResourceType::AD:
                    $oldResourceEntity = $oldResource->getAd();
                    $newResourceEntity = $newResource->getAd();
                    break;
                case ChangeEventResourceType::AD_GROUP:
                    $oldResourceEntity = $oldResource->getAdGroup();
                    $newResourceEntity = $newResource->getAdGroup();
                    break;
                case ChangeEventResourceType::AD_GROUP_CRITERION:
                    $oldResourceEntity = $oldResource->getAdGroupCriterion();
                    $newResourceEntity = $newResource->getAdGroupCriterion();
                    break;
                case ChangeEventResourceType::AD_GROUP_BID_MODIFIER:
                    $oldResourceEntity = $oldResource->getAdGroupBidModifier();
                    $newResourceEntity = $newResource->getAdGroupBidModifier();
                    break;
                case ChangeEventResourceType::CAMPAIGN:
                    $oldResourceEntity = $oldResource->getCampaign();
                    $newResourceEntity = $newResource->getCampaign();
                    break;
                case ChangeEventResourceType::CAMPAIGN_BUDGET:
                    $oldResourceEntity = $oldResource->getCampaignBudget();
                    $newResourceEntity = $newResource->getCampaignBudget();
                    break;
                case ChangeEventResourceType::CAMPAIGN_CRITERION:
                    $oldResourceEntity = $oldResource->getCampaignCriterion();
                    $newResourceEntity = $newResource->getCampaignCriterion();
                    break;
                default:
                    $isResourceTypeKnown = false;
                    break;
            }
            if (!$isResourceTypeKnown) {
                printf(
                    "Unknown change_resource_type %s.%s",
                    ChangeEventResourceType::name($changeEvent->getChangeResourceType()),
                    PHP_EOL
                );
            }
            $resourceChangeOperation = $changeEvent->getResourceChangeOperation();
            printf(
                "On %s, user '%s' used interface '%s' to perform a(n) '%s' operation on a '%s' "
                . "with resource name '%s'.%s",
                $changeEvent->getChangeDateTime(),
                $changeEvent->getUserEmail(),
                ChangeClientType::name($changeEvent->getClientType()),
                ResourceChangeOperation::name($resourceChangeOperation),
                ChangeEventResourceType::name($changeEvent->getChangeResourceType()),
                $changeEvent->getChangeResourceName(),
                PHP_EOL
            );

            if (
                $resourceChangeOperation !== ResourceChangeOperation::CREATE
                && $resourceChangeOperation !== ResourceChangeOperation::UPDATE
            ) {
                continue;
            }
            foreach ($changeEvent->getChangedFields()->getPaths() as $path) {
                $newValueStr =
                    self::convertToString(FieldMasks::getFieldValue($path, $newResourceEntity));
                if ($resourceChangeOperation === ResourceChangeOperation::CREATE) {
                    printf("'$path' set to '%s'.%s", $newValueStr, PHP_EOL);
                } elseif ($resourceChangeOperation === ResourceChangeOperation::UPDATE) {
                    printf(
                        "'$path' changed from '%s' to '%s'.%s",
                        self::convertToString(FieldMasks::getFieldValue($path, $oldResourceEntity)),
                        $newValueStr,
                        PHP_EOL
                    );
                }
            }
        }
    }

    /**
     * Converts the specified value to string.
     *
     * @param mixed $value the value to be converted to string
     * @return string the value in string
     */
    private static function convertToString($value)
    {
        if (gettype($value) === 'boolean') {
            return $value ? 'true' : 'false';
        } elseif (gettype($value) === 'object' && get_class($value) === RepeatedField::class) {
            return json_encode(iterator_to_array($value->getIterator()));
        } else {
            return strval($value);
        }
    }
}

GetChangeDetails::main();

Python

#!/usr/bin/env python
#
# Copyright 2018 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 gets the changes in the account made in the last 7 days."""


import argparse
import sys


import google.ads.google_ads.client


ADS_PAGE_SIZE = 1000


def resource_name_for_resource_type(resource_type, row):
    """Return the resource name for the resource type.

    Each returned row contains all possible changed fields. This function
    returns the resource name of the changed field based on the
    resource type. The changed field's parent is also populated but is not used.

    Args:
        resource_type: the string equivalent of the resource type
        row: a single row returned from the service

    Returns:
        The resource name of the field that changed.
    """
    resource_name = ""  # default for UNSPECIFIED or UNKNOWN
    if resource_type == "AD_GROUP":
        resource_name = row.change_status.ad_group
    elif resource_type == "AD_GROUP_AD":
        resource_name = row.change_status.ad_group_ad
    elif resource_type == "AD_GROUP_CRITERION":
        resource_name = row.change_status.ad_group_criterion
    elif resource_type == "CAMPAIGN":
        resource_name = row.change_status.campaign
    elif resource_type == "CAMPAIGN_CRITERION":
        resource_name = row.change_status.campaign_criterion
    return resource_name


def main(client, customer_id):
    ads_service = client.get_service("GoogleAdsService", version="v6")
    query = """
        SELECT
          change_status.resource_name,
          change_status.last_change_date_time,
          change_status.resource_type,
          change_status.campaign,
          change_status.ad_group,
          change_status.resource_status,
          change_status.ad_group_ad,
          change_status.ad_group_criterion,
          change_status.campaign_criterion
        FROM change_status
        WHERE change_status.last_change_date_time DURING LAST_7_DAYS
        ORDER BY change_status.last_change_date_time"""

    response = ads_service.search(
        customer_id, query=query, page_size=ADS_PAGE_SIZE
    )

    resource_type_enum = client.get_type(
        "ChangeStatusResourceTypeEnum", version="v6"
    ).ChangeStatusResourceType
    change_status_operation_enum = client.get_type(
        "ChangeStatusOperationEnum", version="v6"
    ).ChangeStatusOperation

    try:
        for row in response:
            resource_type = resource_type_enum.Name(
                row.change_status.resource_type
            )
            resource_status = change_status_operation_enum.Name(
                row.change_status.resource_status
            )
            print(
                'On "%s", change status "%s" shows a resource type of "%s" '
                'with resource name "%s" was "%s".'
                % (
                    row.change_status.last_change_date_time,
                    row.change_status.resource_name,
                    resource_type,
                    resource_name_for_resource_type(resource_type, row),
                    resource_status,
                )
            )
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print(
            'Request with ID "%s" failed with status "%s" and includes the '
            "following errors:" % (ex.request_id, ex.error.code().name)
        )
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print("\t\tOn field: %s" % field_path_element.field_name)
        sys.exit(1)


if __name__ == "__main__":
    # GoogleAdsClient will read a google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = (
        google.ads.google_ads.client.GoogleAdsClient.load_from_storage()
    )

    parser = argparse.ArgumentParser(
        description=(
            "Displays account changes that occurred in the last 7 days."
        )
    )
    # 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.",
    )
    args = parser.parse_args()

    main(google_ads_client, args.customer_id)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# 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
#
#     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 gets specific details about the most recent changes in your
# account, including which field changed and the old and new values.

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

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

  # Construct a query to find details for recent changes in your account.
  # The LIMIT clause is required for the change_event resource.
  # The maximum size is 10000, but a low limit was set here for demonstrative
  # purposes.
  # The WHERE clause on change_date_time is also required. It must specify a
  # window of at most 30 days within the past 30 days.
  query = <<~QUERY
    SELECT
      change_event.resource_name,
      change_event.change_date_time,
      change_event.change_resource_name,
      change_event.user_email,
      change_event.client_type,
      change_event.change_resource_type,
      change_event.old_resource,
      change_event.new_resource,
      change_event.resource_change_operation,
      change_event.changed_fields
    FROM
      change_event
    WHERE
      change_event.change_date_time <= '#{(Date.today + 1).to_s}'
      AND change_event.change_date_time >= '#{(Date.today - 14).to_s}'
    ORDER BY
      change_event.change_date_time DESC
    LIMIT 5
  QUERY

  # Execute the query to fetch results from the API.
  response = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
    # The page size is superfluous with the default limit set above, but it's
    # shown here since it's a good practice to use a reasonable page size when
    # you set a higher limit.
    page_size: PAGE_SIZE
  )

  # Process the results and output changes.
  response.each do |row|
    event = row.change_event
    old_resource, new_resource = case event.change_resource_type
    when :AD
      [event.old_resource.ad, event.new_resource.ad]
    when :AD_GROUP
      [event.old_resource.ad_group, event.new_resource.ad_group]
    when :AD_GROUP_CRITERION
      [event.old_resource.ad_group_criterion, event.new_resource.ad_group_criterion]
    when :AD_GROUP_BID_MODIFIER
      [event.old_resource.ad_group_bid_modifier, event.new_resource.ad_group_bid_modifier]
    when :CAMPAIGN
      [event.old_resource.campaign, event.new_resource.campaign]
    when :CAMPAIGN_BUDGET
      [event.old_resource.campaign_budget, event.new_resource.campaign_budget]
    when :CAMPAIGN_CRITERION
      [event.old_resource.campaign_criterion, event.new_resource.campaign_criterion]
    else
      puts "Unknown change_resource_type #{event.change_resource_type}."
      next
    end
    puts "On #{event.change_date_time}, user #{event.user_email} used interface " \
      "#{event.client_type} to perform a(n) #{event.resource_change_operation} " \
      "operation on a #{event.change_resource_type} with resource name " \
      "#{event.change_resource_name}."
    if [:UPDATE, :CREATE].include? event.resource_change_operation
      event.changed_fields.paths.each do |changed_field|
        new_value = get_value_from_path(changed_field, new_resource)
        if :CREATE == event.resource_change_operation
          puts "\t#{changed_field} set to '#{new_value}'."
        else
          old_value = get_value_from_path(changed_field, old_resource)
          puts "\t#{changed_field} changed from '#{old_value}' to '#{new_value}'."
        end
      end
    end
  end
end

# Given the string value of a path from the response, look up the value of the
# field located at that path on the given object.
def get_value_from_path(path, object)
  path.split(".").inject(object) {|obj, key| obj.send(key)}
end

if __FILE__ == $PROGRAM_NAME
  PAGE_SIZE = 1000

  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'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %s [options]', File.basename(__FILE__))

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

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

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

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

  begin
    get_change_details(options.fetch(:customer_id).tr("-", ""))
  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 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.
#
# This example gets specific details about the most recent changes in your
# account, including which field changed and the old and new values.

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::Utils::SearchGoogleAdsIterator;
use Google::Ads::GoogleAds::Utils::FieldMasks;
use Google::Ads::GoogleAds::V6::Enums::ResourceChangeOperationEnum
  qw(CREATE UPDATE);
use Google::Ads::GoogleAds::V6::Enums::ChangeEventResourceTypeEnum
  qw(AD AD_GROUP AD_GROUP_CRITERION AD_GROUP_BID_MODIFIER CAMPAIGN CAMPAIGN_BUDGET CAMPAIGN_CRITERION);
use
  Google::Ads::GoogleAds::V6::Services::GoogleAdsService::SearchGoogleAdsRequest;

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

use constant PAGE_SIZE => 1000;

# 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";

sub get_change_details {
  my ($api_client, $customer_id) = @_;

  # Construct a query to find details for recent changes in your account.
  # The LIMIT clause is required for the change_event resource.
  # The maximum size is 10000, but a low limit was set here for demonstrative
  # purposes.
  # The WHERE clause on change_date_time is also required. It must specify a
  # window of at most 30 days within the past 30 days.
  my $search_query =
    "SELECT change_event.resource_name, change_event.change_date_time, " .
    "change_event.change_resource_name, change_event.user_email, " .
    "change_event.client_type, change_event.change_resource_type, " .
    "change_event.old_resource, change_event.new_resource, " .
    "change_event.resource_change_operation, change_event.changed_fields " .
    "FROM change_event " .
    "WHERE change_event.change_date_time DURING LAST_14_DAYS " .
    "ORDER BY change_event.change_date_time DESC LIMIT 5";

  # Create a search Google Ads request that will retrieve all change events using
  # pages of the specified page size.
  my $search_request =
    Google::Ads::GoogleAds::V6::Services::GoogleAdsService::SearchGoogleAdsRequest
    ->new({
      customerId => $customer_id,
      query      => $search_query,
      # The page size is superfluous with the default limit set above, but it's
      # shown here since it's a good practice to use a reasonable page size
      # when you set a higher limit.
      pageSize => PAGE_SIZE
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({
    service => $google_ads_service,
    request => $search_request
  });

  # Iterate over all rows in all pages and print the requested field values for
  # the change event in each row.
  while ($iterator->has_next) {
    my $google_ads_row = $iterator->next;

    my $change_event = $google_ads_row->{changeEvent};
    printf "On %s, user %s used interface %s to perform a(n) %s operation " .
      "on a %s with resource name '%s'.\n", $change_event->{changeDateTime},
      $change_event->{userEmail}, $change_event->{clientType},
      $change_event->{resourceChangeOperation},
      $change_event->{changeResourceType}, $change_event->{changeResourceName};

    if (grep /$change_event->{resourceChangeOperation}/, (CREATE, UPDATE)) {
      my ($old_resource, $new_resource) =
        __get_changed_resources_for_resource_type($change_event);

      foreach my $changed_field (split /,/, $change_event->{changedFields}) {
        my $new_value = get_field_value($new_resource, $changed_field) || "";
        if ($change_event->{resourceChangeOperation} eq CREATE) {
          print "\t$changed_field set to '$new_value'.\n";
        } else {
          my $old_value = get_field_value($old_resource, $changed_field) || "";
          print "\t$changed_field changed from '$old_value' to '$new_value'.\n";
        }
      }
    }
  }

  return 1;
}

# This method returns the old resource and new resource based on the change
# resource type of a change event.
sub __get_changed_resources_for_resource_type {
  my $change_event  = shift;
  my $resource_type = $change_event->{changeResourceType};
  if ($resource_type eq AD) {
    return $change_event->{oldResource}{ad}, $change_event->{newResource}{ad};
  } elsif ($resource_type eq AD_GROUP) {
    return $change_event->{oldResource}{adGroup},
      $change_event->{newResource}{adGroup};
  } elsif ($resource_type eq AD_GROUP_CRITERION) {
    return $change_event->{oldResource}{adGroupCriterion},
      $change_event->{newResource}{adGroupCriterion};
  } elsif ($resource_type eq AD_GROUP_BID_MODIFIER) {
    return $change_event->{oldResource}{adGroupBidModifier},
      $change_event->{newResource}{adGroupBidModifier};
  } elsif ($resource_type eq CAMPAIGN) {
    return $change_event->{oldResource}{campaign},
      $change_event->{newResource}{campaign};
  } elsif ($resource_type eq CAMPAIGN_BUDGET) {
    return $change_event->{oldResource}{campaignBudget},
      $change_event->{newResource}{campaignBudget};
  } elsif ($resource_type eq CAMPAIGN_CRITERION) {
    return $change_event->{oldResource}{campaignCriterion},
      $change_event->{newResource}{campaignCriterion};
  } else {
    print "Unknown change_resource_type $resource_type.\n";
  }
}

# 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);

# 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);

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

=pod

=head1 NAME

get_change_details

=head1 DESCRIPTION

This example gets specific details about the most recent changes in your
account, including which field changed and the old and new values.

=head1 SYNOPSIS

get_change_details.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut