Mutate Ads

Stay organized with collections Save and categorize content based on your preferences.

Mutate responsive search ad

As mentioned previously, only certain ad types are mutable. The following code example illustrates how to modify an existing responsive search ad.

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adId) {
  // Creates an AdOperation to update an ad.
  AdOperation.Builder adOperation = AdOperation.newBuilder();

  // Creates an Ad in the update field of the operation.
  Ad.Builder adBuilder =
      adOperation
          .getUpdateBuilder()
          .setResourceName(ResourceNames.ad(customerId, adId))
          .addFinalUrls("http://www.example.com/")
          .addFinalMobileUrls("http://www.example.com/mobile");

  // Sets the responsive search ad properties to update on the ad.
  adBuilder
      .getResponsiveSearchAdBuilder()
      .addAllHeadlines(
          ImmutableList.of(
              AdTextAsset.newBuilder()
                  .setText("Cruise to Pluto #" + getShortPrintableDateTime())
                  .setPinnedField(ServedAssetFieldType.HEADLINE_1)
                  .build(),
              AdTextAsset.newBuilder().setText("Tickets on sale now").build(),
              AdTextAsset.newBuilder().setText("Buy your ticket now").build()))
      .addAllDescriptions(
          ImmutableList.of(
              AdTextAsset.newBuilder().setText("Best space cruise ever.").build(),
              AdTextAsset.newBuilder()
                  .setText("The most wonderful space experience you will ever have.")
                  .build()));

  // Sets the update mask (the fields which will be modified) to be all the fields we set above.
  adOperation.setUpdateMask(FieldMasks.allSetFieldsOf(adBuilder.build()));

  // Creates a service client to connect to the API.
  try (AdServiceClient adServiceClient =
      googleAdsClient.getLatestVersion().createAdServiceClient()) {
    // Issues the mutate request.
    MutateAdsResponse response =
        adServiceClient.mutateAds(
            String.valueOf(customerId), ImmutableList.of(adOperation.build()));

    // Displays the result.
    for (MutateAdResult result : response.getResultsList()) {
      System.out.printf("Ad with resource name '%s' was updated.%n", result.getResourceName());
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long adId)
{
    // Get the AdService.
    AdServiceClient adService = client.GetService(Services.V11.AdService);

    Ad ad = new Ad()
    {
        ResourceName = ResourceNames.Ad(customerId, adId),
        ResponsiveSearchAd = new ResponsiveSearchAdInfo()
        {
            // Update some properties of the responsive search ad.
            Headlines =
            {
                new AdTextAsset()
                {
                    Text = "Cruise to Pluto #" + ExampleUtilities.GetShortRandomString(),
                    PinnedField = ServedAssetFieldTypeEnum.Types.ServedAssetFieldType.Headline1
                },
                new AdTextAsset() { Text = "Tickets on sale now" },
                new AdTextAsset() { Text = "Buy your ticket now" }
            },
            Descriptions =
            {
                new AdTextAsset() { Text = "Best space cruise ever." },
                new AdTextAsset() { Text = "The most wonderful space experience you will ever have." },
            }
        },
        FinalUrls = { "http://www.example.com/" },
        FinalMobileUrls = { "http://www.example.com/mobile" }
    };

    AdOperation operation = new AdOperation()
    {
        Update = ad,
        UpdateMask = FieldMasks.AllSetFieldsOf(ad)
    };

    try
    {
        // Issue the update request.
        MutateAdsResponse response = adService.MutateAds(customerId.ToString(),
            new[] { operation });

        // Display the results.
        foreach (MutateAdResult updatedAd in response.Results)
        {
            Console.WriteLine($"Ad with resource ID = '{updatedAd.ResourceName}' was " +
                $"updated.");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $adId
) {
    // Creates an ad with the specified resource name and other changes.
    $ad = new Ad([
        'resource_name' => ResourceNames::forAd($customerId, $adId),
        'responsive_search_ad' => new ResponsiveSearchAdInfo([
            // Update some properties of the responsive search ad.
            'headlines' => [
                new AdTextAsset([
                    'text' => 'Cruise to Pluto #' . Helper::getShortPrintableDatetime(),
                    'pinned_field' => ServedAssetFieldType::HEADLINE_1
                ]),
                new AdTextAsset(['text' => 'Tickets on sale now']),
                new AdTextAsset(['text' => 'Buy your ticket now'])
            ],
            'descriptions' => [
                new AdTextAsset(['text' => 'Best space cruise ever.']),
                new AdTextAsset([
                    'text' => 'The most wonderful space experience you will ever have.'])
            ]
        ]),
        'final_urls' => ['http://www.example.com'],
        'final_mobile_urls' => ['http://www.example.com/mobile']
    ]);

    // Constructs an operation that will update the ad, using the FieldMasks to derive the
    // update mask. This mask tells the Google Ads API which attributes of the ad you want to
    // change.
    $adOperation = new AdOperation();
    $adOperation->setUpdate($ad);
    $adOperation->setUpdateMask(FieldMasks::allSetFieldsOf($ad));

    // Issues a mutate request to update the ad.
    $adServiceClient = $googleAdsClient->getAdServiceClient();
    $response = $adServiceClient->mutateAds($customerId, [$adOperation]);

    // Prints the resource name of the updated ad.
    /** @var Ad $updatedAd */
    $updatedAd = $response->getResults()[0];
    printf(
        "Updated ad with resource name: '%s'.%s",
        $updatedAd->getResourceName(),
        PHP_EOL
    );
}
      

Python

def main(client, customer_id, ad_id):
    ad_service = client.get_service("AdService")
    ad_operation = client.get_type("AdOperation")

    # Update ad operation.
    ad = ad_operation.update
    ad.resource_name = ad_service.ad_path(customer_id, ad_id)

    # Update some properties of the responsive search ad.
    headline_1 = client.get_type("AdTextAsset")
    headline_1.text = f"Cruise to Pluto #{uuid4().hex[:8]}"
    headline_1.pinned_field = client.enums.ServedAssetFieldTypeEnum.HEADLINE_1

    headline_2 = client.get_type("AdTextAsset")
    headline_2.text = "Tickets on sale now"

    headline_3 = client.get_type("AdTextAsset")
    headline_3.text = "Buy your tickets now"

    ad.responsive_search_ad.headlines.extend(
        [headline_1, headline_2, headline_3]
    )

    description_1 = client.get_type("AdTextAsset")
    description_1.text = "Best space cruise ever."

    description_2 = client.get_type("AdTextAsset")
    description_2.text = (
        "The most wonderful space experience you will ever have."
    )

    ad.final_urls.append("https://www.example.com")
    ad.final_mobile_urls.append("https://www.example.com/mobile")
    client.copy_from(
        ad_operation.update_mask, protobuf_helpers.field_mask(None, ad._pb)
    )

    # Updates the ad.
    ad_response = ad_service.mutate_ads(
        customer_id=customer_id, operations=[ad_operation]
    )
    print(
        f'Ad with resource name "{ad_response.results[0].resource_name}" '
        "was updated."
    )
      

Ruby

This example is not yet available in Ruby; you can take a look at the other languages.
    

Perl

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

  # Create an ad with the proper resource name and any other changes.
  my $ad = Google::Ads::GoogleAds::V11::Resources::Ad->new({
      resourceName => Google::Ads::GoogleAds::V11::Utils::ResourceNames::ad(
        $customer_id, $ad_id
      ),
      responsiveSearchAd =>
        Google::Ads::GoogleAds::V11::Common::ResponsiveSearchAdInfo->new({
          # Update some properties of the responsive search ad.
          headlines => [
            Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
                text        => "Cruise to Pluto #" . uniqid(),
                pinnedField => HEADLINE_1
              }
            ),
            Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
                text => "Tickets on sale now"
              }
            ),
            Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
                text => "Buy your ticket now"
              }
            ),

          ],
          descriptions => [
            Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
                text => "Best space cruise ever."
              }
            ),
            Google::Ads::GoogleAds::V11::Common::AdTextAsset->new({
                text =>
                  "The most wonderful space experience you will ever have."
              }
            ),
          ]}
        ),
      finalUrls       => ["http://www.example.com/"],
      finalMobileUrls => ["http://www.example.com/mobile"]});

  # Create an ad operation for update, using the FieldMasks utility to derive
  # the update mask.
  my $ad_operation =
    Google::Ads::GoogleAds::V11::Services::AdService::AdOperation->new({
      update     => $ad,
      updateMask => all_set_fields_of($ad)});

  # Issue a mutate request to update the ad.
  my $ads_response = $api_client->AdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_operation]});

  printf "Updated ad with resource name: '%s'.\n",
    $ads_response->{results}[0]{resourceName};

  return 1;
}