Mutate Ads

Mutate expanded text ad

As mentioned previously, only certain ad types are mutable. The following code example illustrates how to modify an existing expanded text 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 expanded text ad properties to update on the ad.
  adBuilder
      .getExpandedTextAdBuilder()
      .setHeadlinePart1("Cruise to Pluto #" + System.currentTimeMillis())
      .setHeadlinePart2("Tickets on sale now")
      .setDescription("Best space cruise ever.");

  // 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.V5.AdService);

    Ad ad = new Ad()
    {
        ResourceName = ResourceNames.Ad(customerId, adId),
        ExpandedTextAd = new ExpandedTextAdInfo()
        {
            // Update some properties of the expanded text ad.
            HeadlinePart1 = "Cruise to Pluto #" + ExampleUtilities.GetShortRandomString(),
            HeadlinePart2 = "Tickets on sale now",
            Description = "Best space cruise ever.",
        },
        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),
        'expanded_text_ad' => new ExpandedTextAdInfo([
            'headline_part1' => 'Cruise to Pluto #' . uniqid(),
            'headline_part2' => 'Tickets on sale now',
            'description' => 'Best space cruise ever'
        ]),
        '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", version="v5")

    ad_operation = client.get_type("AdOperation", version="v5")

    # Update ad operation.
    ad = ad_operation.update
    ad.resource_name = ad_service.ad_path(customer_id, ad_id)
    ad.expanded_text_ad.headline_part1 = (
        f"Cruise to Pluto {str(uuid.uuid4())[:8]}"
    )
    ad.expanded_text_ad.headline_part2 = "Tickets on sale now"
    ad.expanded_text_ad.description = "Best space cruise ever."
    ad.final_urls.append("http://www.example.com")
    ad.final_mobile_urls.append("http://www.example.com/mobile")

    fm = protobuf_helpers.field_mask(None, ad)
    ad_operation.update_mask.CopyFrom(fm)

    # Updates the ad.
    try:
        ad_response = ad_service.mutate_ads(customer_id, [ad_operation])
    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(
        f'Ad with resource name "{ad_response.results[0].resource_name}" '
        "was updated."
    )

Perl

sub update_expanded_text_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::V5::Resources::Ad->new({
      resourceName => Google::Ads::GoogleAds::V5::Utils::ResourceNames::ad(
        $customer_id, $ad_id
      ),
      expandedTextAd =>
        Google::Ads::GoogleAds::V5::Common::ExpandedTextAdInfo->new({
          # Update some properties of the expanded text ad.
          headlinePart1 => "Cruise to Pluto #" . uniqid(),
          headlinePart2 => "Tickets on sale now",
          description   => "Best space cruise ever."
        }
        ),
      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::V5::Services::AdService::AdOperation->new({
      update     => $ad,
      updateMask => all_set_fields_of($ad)});

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

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

  return 1;
}