Gửi yêu cầu thay đổi

Sau khi tạo các thao tác biến đổi cho từng thực thể cần thiết cho một chiến dịch Thông minh, hãy kết hợp các thao tác đó thành một yêu cầu GoogleAdsService.Mutate duy nhất để tạo tất cả các thực thể cùng một lúc.

Việc sử dụng một yêu cầu thay đổi tài nguyên duy nhất mang lại những lợi ích sau:

  • Giảm độ phức tạp, vì các thực thể này không được chia sẻ và phụ thuộc rất nhiều vào nhau.
  • Ngăn việc tạo các thực thể không có mối liên kết nếu một trong các thao tác không thành công vì bất kỳ lý do nào (khi partial_failure được đặt thành false, đây là giá trị mặc định).

Khi sử dụng tên tài nguyên tạm thời (mã nhận dạng số nguyên âm như -1, -2 và -3) để tạo và liên kết các thực thể trong một yêu cầu duy nhất, hãy đảm bảo rằng bạn sắp xếp các thao tác sao cho những thực thể có các phần phụ thuộc được tạo sau các thực thể mẹ mà chúng tham chiếu.

Java

/**
 * Sends a mutate request with a group of mutate operations.
 *
 * <p>The {@link GoogleAdsServiceClient} allows batching together a list of operations. These are
 * executed sequentially, and later operations my refer to previous operations via temporary IDs.
 * For more detail on this, please refer to
 * https://developers.google.com/google-ads/api/docs/batch-processing/temporary-ids.
 */
private void sendMutateRequest(
    GoogleAdsClient googleAdsClient, long customerId, List<MutateOperation> operations) {
  try (GoogleAdsServiceClient client =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    MutateGoogleAdsResponse outerResponse = client.mutate(String.valueOf(customerId), operations);
    for (MutateOperationResponse innerResponse :
        outerResponse.getMutateOperationResponsesList()) {
      OneofDescriptor oneofDescriptor =
          innerResponse.getDescriptorForType().getOneofs().stream()
              .filter(o -> o.getName().equals("response"))
              .findFirst()
              .get();
      Message createdEntity =
          (Message)
              innerResponse.getField(innerResponse.getOneofFieldDescriptor(oneofDescriptor));
      String resourceName =
          (String)
              createdEntity.getField(
                  createdEntity.getDescriptorForType().findFieldByName("resource_name"));
      System.out.printf(
          "Created a(n) %s with resource name: '%s'.%n",
          createdEntity.getClass().getSimpleName(), resourceName);
    }
  }
}
      

C#

// The below methods create and return MutateOperations that we later provide to
// the GoogleAdsService.Mutate method in order to create the entities in a single
// request. Since the entities for a Smart campaign are closely tied to one-another
// it's considered a best practice to create them in a single Mutate request; the
// entities will either all complete successfully or fail entirely, leaving no
// orphaned entities. See:
// https://developers.google.com/google-ads/api/docs/mutating/overview
MutateOperation campaignBudgetOperation =
    CreateCampaignBudgetOperation(customerId, suggestedBudgetAmount);
MutateOperation smartCampaignOperation =
    CreateSmartCampaignOperation(customerId);
MutateOperation smartCampaignSettingOperation =
    CreateSmartCampaignSettingOperation(customerId, businessProfileLocation,
        businessName);
IEnumerable<MutateOperation> campaignCriterionOperations =
    CreateCampaignCriterionOperations(customerId, keywordThemeInfos,
        suggestionInfo);
MutateOperation adGroupOperation = CreateAdGroupOperation(customerId);
MutateOperation adGroupAdOperation = CreateAdGroupAdOperation(customerId,
    adSuggestions);

// Send the operations in a single mutate request.
MutateGoogleAdsRequest mutateGoogleAdsRequest = new MutateGoogleAdsRequest
{
    CustomerId = customerId.ToString()
};
// It's important to create these entities in this order because they depend on
// each other, for example the SmartCampaignSetting and ad group depend on the
// campaign, and the ad group ad depends on the ad group.
mutateGoogleAdsRequest.MutateOperations.Add(campaignBudgetOperation);
mutateGoogleAdsRequest.MutateOperations.Add(smartCampaignOperation);
mutateGoogleAdsRequest.MutateOperations.Add(smartCampaignSettingOperation);
mutateGoogleAdsRequest.MutateOperations.Add(campaignCriterionOperations);
mutateGoogleAdsRequest.MutateOperations.Add(adGroupOperation);
mutateGoogleAdsRequest.MutateOperations.Add(adGroupAdOperation);

MutateGoogleAdsResponse response =
    googleAdsServiceClient.Mutate(mutateGoogleAdsRequest);

PrintResponseDetails(response);
      

PHP

    // The below methods create and return MutateOperations that we later provide to the
    // GoogleAdsService.Mutate method in order to create the entities in a single request.
    // Since the entities for a Smart campaign are closely tied to one-another it's considered
    // a best practice to create them in a single Mutate request so they all complete
    // successfully or fail entirely, leaving no orphaned entities.
    // See: https://developers.google.com/google-ads/api/docs/mutating/overview.
    $campaignBudgetOperation = self::createCampaignBudgetOperation(
        $customerId,
        $suggestedBudgetAmount
    );
    $smartCampaignOperation = self::createSmartCampaignOperation($customerId);
    $smartCampaignSettingOperation = self::createSmartCampaignSettingOperation(
        $customerId,
        $businessProfileLocationResourceName,
        $businessName
    );
    $campaignCriterionOperations = self::createCampaignCriterionOperations(
        $customerId,
        $keywordThemeInfos,
        $suggestionInfo
    );
    $adGroupOperation = self::createAdGroupOperation($customerId);
    $adGroupAdOperation = self::createAdGroupAdOperation($customerId, $adSuggestions);

    // Issues a single mutate request to add the entities.
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    $response = $googleAdsServiceClient->mutate(
        MutateGoogleAdsRequest::build(
            $customerId,
            // It's important to create these entities in this order because they depend on
            // each other, for example the SmartCampaignSetting and ad group depend on the
            // campaign, and the ad group ad depends on the ad group.
            array_merge(
                [
                $campaignBudgetOperation,
                $smartCampaignOperation,
                $smartCampaignSettingOperation,
                ],
                $campaignCriterionOperations,
                [
                $adGroupOperation,
                $adGroupAdOperation
                ]
            )
        )
    );

    self::printResponseDetails($response);
}
      

Python

# The below methods create and return MutateOperations that we later
# provide to the GoogleAdsService.Mutate method in order to create the
# entities in a single request. Since the entities for a Smart campaign
# are closely tied to one-another it's considered a best practice to
# create them in a single Mutate request so they all complete successfully
# or fail entirely, leaving no orphaned entities. See:
# https://developers.google.com/google-ads/api/docs/mutating/overview
campaign_budget_operation: MutateOperation = (
    create_campaign_budget_operation(
        client, customer_id, suggested_budget_amount
    )
)
smart_campaign_operation: MutateOperation = create_smart_campaign_operation(
    client, customer_id
)
smart_campaign_setting_operation: MutateOperation = (
    create_smart_campaign_setting_operation(
        client, customer_id, business_profile_location, business_name
    )
)
campaign_criterion_operations: List[MutateOperation] = (
    create_campaign_criterion_operations(
        client, customer_id, keyword_theme_infos, suggestion_info
    )
)
ad_group_operation: MutateOperation = create_ad_group_operation(
    client, customer_id
)
ad_group_ad_operation: MutateOperation = create_ad_group_ad_operation(
    client, customer_id, ad_suggestions
)

googleads_service: GoogleAdsServiceClient = client.get_service(
    "GoogleAdsService"
)

# Send the operations into a single Mutate request.
response: MutateGoogleAdsResponse = googleads_service.mutate(
    customer_id=customer_id,
    mutate_operations=[
        # It's important to create these entities in this order because
        # they depend on each other, for example the SmartCampaignSetting
        # and ad group depend on the campaign, and the ad group ad depends
        # on the ad group.
        campaign_budget_operation,
        smart_campaign_operation,
        smart_campaign_setting_operation,
        # Expand the list of campaign criterion operations into the list of
        # other mutate operations
        *campaign_criterion_operations,
        ad_group_operation,
        ad_group_ad_operation,
    ],
)

print_response_details(response)
      

Ruby

# The below methods create and return MutateOperations that we later
# provide to the GoogleAdsService.Mutate method in order to create the
# entities in a single request. Since the entities for a Smart campaign
# are closely tied to one-another it's considered a best practice to
# create them in a single Mutate request so they all complete successfully
# or fail entirely, leaving no orphaned entities. See:
# https://developers.google.com/google-ads/api/docs/mutating/overview
mutate_operations = []

# It's important to create these operations in this order because
# they depend on each other, for example the SmartCampaignSetting
# and ad group depend on the campaign, and the ad group ad depends
# on the ad group.
mutate_operations << create_campaign_budget_operation(
  client,
  customer_id,
  suggested_budget_amount,
)

mutate_operations << create_smart_campaign_operation(
  client,
  customer_id,
)

mutate_operations << create_smart_campaign_setting_operation(
  client,
  customer_id,
  business_profile_location,
  business_name,
)

mutate_operations += create_campaign_criterion_operations(
  client,
  customer_id,
  keyword_theme_infos,
  suggestion_info,
)

mutate_operations << create_ad_group_operation(client, customer_id)

mutate_operations << create_ad_group_ad_operation(
  client,
  customer_id,
  ad_suggestions
)

# Sends the operations into a single Mutate request.
response = client.service.google_ads.mutate(
  customer_id: customer_id,
  mutate_operations: mutate_operations,
)

print_response_details(response)
      

Perl

# The below methods create and return MutateOperations that we later provide to the
# GoogleAdsService.Mutate method in order to create the entities in a single
# request. Since the entities for a Smart campaign are closely tied to one-another
# it's considered a best practice to create them in a single Mutate request; the
# entities will either all complete successfully or fail entirely, leaving no
# orphaned entities. See:
# https://developers.google.com/google-ads/api/docs/mutating/overview
my $campaign_budget_operation =
  _create_campaign_budget_operation($customer_id, $suggested_budget_amount);
my $smart_campaign_operation = _create_smart_campaign_operation($customer_id);
my $smart_campaign_setting_operation =
  _create_smart_campaign_setting_operation($customer_id,
  $business_profile_location, $business_name);
my $campaign_criterion_operations =
  _create_campaign_criterion_operations($customer_id, $keyword_theme_infos,
  $suggestion_info);
my $ad_group_operation = _create_ad_group_operation($customer_id);
my $ad_group_ad_operation =
  _create_ad_group_ad_operation($customer_id, $ad_suggestions);

# It's important to create these entities in this order because they depend on
# each other. For example, the SmartCampaignSetting and ad group depend on the
# campaign and the ad group ad depends on the ad group.
my $mutate_operations = [
  $campaign_budget_operation, $smart_campaign_operation,
  $smart_campaign_setting_operation,
  # Expand the list of campaign criterion operations into the list of
  # other mutate operations.
  @$campaign_criterion_operations,
  $ad_group_operation, $ad_group_ad_operation
];

# Send the operations in a single mutate request.
my $mutate_google_ads_response = $api_client->GoogleAdsService()->mutate({
  customerId       => $customer_id,
  mutateOperations => $mutate_operations
});

_print_response_details($mutate_google_ads_response);
      

curl