Example: Adding and removing real estate listings

Assume you have Dynamic Remarketing ads for your real estate website. New listings get added to inventory, while sold properties get removed. The goal is to update your Dynamic Remarketing ads to reflect your current inventory.

Step 1 - Get information about your listings setup

In order to manage your real estate listings, you'll need to retrieve the feed.attributes of your Feed. In order to easily access this information later, create a Map that contains keys of type RealEstatePlaceholderField and values of type FeedAttribute. Assuming you use the same Map object to create your FeedMapping, as shown in this example, this map will serve as a convenient mechanism for creating each FeedItem in the following step.

Java

private Map<RealEstatePlaceholderField, FeedAttribute> getFeed(
    GoogleAdsClient googleAdsClient, long customerId, String feedResourceName) {
  // Constructs the query.
  String query =
      "SELECT feed.attributes FROM feed WHERE feed.resource_name = '" + feedResourceName + "'";

  // Constructs the request.
  SearchGoogleAdsRequest request =
      SearchGoogleAdsRequest.newBuilder()
          .setCustomerId(String.valueOf(customerId))
          .setPageSize(PAGE_SIZE)
          .setQuery(query)
          .build();

  // Issues the search request.
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
    // Gets the first result because we only need the single feed item we created previously.
    GoogleAdsRow googleAdsRow = searchPagedResponse.getPage().getResponse().getResults(0);
    // Gets the attributes list from the feed and creates a map with keys of each attribute and
    // values of each corresponding ID.
    List<FeedAttribute> feedAttributeList = googleAdsRow.getFeed().getAttributesList();
    // Creates a map to return.
    Map<RealEstatePlaceholderField, FeedAttribute> feedAttributes = new HashMap<>();
    // Loops through each of the feed attributes and populates the map.
    for (FeedAttribute feedAttribute : feedAttributeList) {
      switch (feedAttribute.getName()) {
        case "Listing ID":
          feedAttributes.put(RealEstatePlaceholderField.LISTING_ID, feedAttribute);
          break;
        case "Listing Name":
          feedAttributes.put(RealEstatePlaceholderField.LISTING_NAME, feedAttribute);
          break;
        case "Final URLs":
          feedAttributes.put(RealEstatePlaceholderField.FINAL_URLS, feedAttribute);
          break;
        case "Image URL":
          feedAttributes.put(RealEstatePlaceholderField.IMAGE_URL, feedAttribute);
          break;
        case "Contextual Keywords":
          feedAttributes.put(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS, feedAttribute);
          break;
          // Optionally add other RealEstatePlaceholderFields.
        default:
          throw new Error("Invalid attribute name.");
      }
    }
    return feedAttributes;
  }
}
      

C#

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

PHP

public static function realEstatePlaceholderFieldsMapFor(
    string $feedResourceName,
    int $customerId,
    GoogleAdsClient $googleAdsClient
) {
    return self::placeholderFieldsMapFor(
        $feedResourceName,
        $customerId,
        $googleAdsClient,
        [
            'Listing ID' => RealEstatePlaceholderField::LISTING_ID,
            'Listing Name' => RealEstatePlaceholderField::LISTING_NAME,
            'Final URLs' => RealEstatePlaceholderField::FINAL_URLS,
            'Image URL' => RealEstatePlaceholderField::IMAGE_URL,
            'Contextual Keywords' => RealEstatePlaceholderField::CONTEXTUAL_KEYWORDS
        ]
    );
}
      

Python

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

Ruby

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

Perl

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

  # Construct the search query.
  my $search_query =
    sprintf "SELECT feed.attributes FROM feed WHERE feed.resource_name = '%s'",
    $feed_resource_name;

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

  # Get the first result because we only need the single feed item we created previously.
  my $google_ads_row = $search_response->{results}[0];

  # Get the attributes list from the feed and create a hash with keys of each attribute and
  # values of each corresponding ID.
  my $feed_attribute_list = $google_ads_row->{feed}{attributes};

  # Create a hash to return.
  my $feed_attributes = {};
  # Loop through each of the feed attributes and populates the hash.
  foreach my $feed_attribute (@$feed_attribute_list) {
    my $feed_attribute_name = $feed_attribute->{name};

    if ($feed_attribute_name eq "Listing ID") {
      $feed_attributes->{LISTING_ID} = $feed_attribute;
    } elsif ($feed_attribute_name eq "Listing Name") {
      $feed_attributes->{LISTING_NAME} = $feed_attribute;
    } elsif ($feed_attribute_name eq "Final URLs") {
      $feed_attributes->{FINAL_URLS} = $feed_attribute;
    } elsif ($feed_attribute_name eq "Image URL") {
      $feed_attributes->{IMAGE_URL} = $feed_attribute;
    } elsif ($feed_attribute_name eq "Contextual Keywords") {
      $feed_attributes->{CONTEXTUAL_KEYWORDS} = $feed_attribute;
    } else {
      die("Invalid attribute name.");
    }
  }

  return $feed_attributes;
}
      

Step 2 - Construct operations to add the new listings

Now that the utility method above is in place, constructing the operations for adding new listings is straightforward. The basic steps for each new listing are:

  1. Get the mapping from RealEstatePlaceholderField to feed attribute ID using the utility method.
  2. For each attribute of the listing (listing ID, listing name, image URL, etc.), create a FeedItemAttributeValue with its feed_attribute_id set to the ID of the FeedAttribute found in the mapping for the corresponding FeedItemAttributeValue field.
  3. On the FeedItemAttributeValue, set the appropriate value for the attribute's field. For example, for listing ID, set the string_value field because the LISTING_ID field has a data type of STRING.
  4. Once you have all of the FeedItemAttributeValue objects, create a new FeedItem and set its feed to the resource name of your Feed, and its FeedItemAttributeValue objects to the collection of FeedItemAttributeValue objects.
  5. Create a new FeedItemOperation where the create operation is set to the FeedItem.

Java

private void createFeedItems(
    GoogleAdsClient googleAdsClient,
    long customerId,
    Map<RealEstatePlaceholderField, FeedAttribute> feedAttributes,
    String feedResourceName) {

  // Creates the listing ID feed attribute value.
  FeedItemAttributeValue listingId =
      FeedItemAttributeValue.newBuilder()
          .setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.LISTING_ID).getId())
          .setStringValue("ABC123DEF")
          .build();
  // Creates the listing name feed attribute value.
  FeedItemAttributeValue listingName =
      FeedItemAttributeValue.newBuilder()
          .setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.LISTING_NAME).getId())
          .setStringValue("Two bedroom with magnificent views")
          .build();
  // Creates the final URLs feed attribute value.
  FeedItemAttributeValue finalUrls =
      FeedItemAttributeValue.newBuilder()
          .setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.FINAL_URLS).getId())
          .addStringValues("http://www.example.com/listings/")
          .build();

  // Optionally insert additional attributes here, such as address, city, description, etc.

  // Creates the image URL feed attribute value.
  FeedItemAttributeValue imageUrl =
      FeedItemAttributeValue.newBuilder()
          .setFeedAttributeId(feedAttributes.get(RealEstatePlaceholderField.IMAGE_URL).getId())
          .setStringValue("http://www.example.com/listings/images?listing_id=ABC123DEF")
          .build();
  // Creates the contextual keywords feed attribute value.
  FeedItemAttributeValue contextualKeywords =
      FeedItemAttributeValue.newBuilder()
          .setFeedAttributeId(
              feedAttributes.get(RealEstatePlaceholderField.CONTEXTUAL_KEYWORDS).getId())
          .addStringValues("beach community")
          .addStringValues("ocean view")
          .addStringValues("two bedroom")
          .build();

  // Creates the FeedItem, specifying the Feed ID and the attributes created above.
  FeedItem feedItem =
      FeedItem.newBuilder()
          .setFeed(feedResourceName)
          .addAttributeValues(listingId)
          .addAttributeValues(listingName)
          .addAttributeValues(finalUrls)
          // Optionally include additional attributes.
          .addAttributeValues(imageUrl)
          .addAttributeValues(contextualKeywords)
          .build();

  // Creates an operation to add the FeedItem. You can include multiple feed items in a single
  // operation.
  FeedItemOperation operation = FeedItemOperation.newBuilder().setCreate(feedItem).build();
  // Creates the feed item service client.
  try (FeedItemServiceClient feedItemServiceClient =
      googleAdsClient.getLatestVersion().createFeedItemServiceClient()) {
    // Adds the feed items.
    MutateFeedItemsResponse response =
        feedItemServiceClient.mutateFeedItems(
            Long.toString(customerId), ImmutableList.of(operation));
    for (MutateFeedItemResult result : response.getResultsList()) {
      System.out.printf("Created feed item with resource name '%s'.%n", result.getResourceName());
    }
  }
}
      

C#

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

PHP

private static function createFeedItem(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    string $feedResourceName,
    array $placeHoldersToFeedAttributesMap
) {
    // Creates the listing ID feed attribute value.
    $listingIdAttributeValue = new FeedItemAttributeValue([
        'feed_attribute_id' => $placeHoldersToFeedAttributesMap[
            RealEstatePlaceholderField::LISTING_ID]->getId(),
        'string_value' => 'ABC123DEF'
    ]);
    // Creates the listing name feed attribute value.
    $listingNameAttributeValue = new FeedItemAttributeValue([
        'feed_attribute_id' => $placeHoldersToFeedAttributesMap[
            RealEstatePlaceholderField::LISTING_NAME]->getId(),
        'string_value' => 'Two bedroom with magnificent views'
    ]);
    // Creates the final URLs feed attribute value.
    $finalUrlsAttributeValue = new FeedItemAttributeValue([
        'feed_attribute_id' => $placeHoldersToFeedAttributesMap[
            RealEstatePlaceholderField::FINAL_URLS]->getId(),
        'string_values' => ['http://www.example.com/listings/']
    ]);
    // Creates the image URL feed attribute value.
    $imageUrlAttributeValue = new FeedItemAttributeValue([
        'feed_attribute_id'
            => $placeHoldersToFeedAttributesMap[RealEstatePlaceholderField::IMAGE_URL]->getId(),
        'string_value' => 'http://www.example.com/listings/images?listing_id=ABC123DEF'
    ]);
    // Creates the contextual keywords feed attribute value.
    $contextualKeywordsAttributeValue = new FeedItemAttributeValue([
        'feed_attribute_id' => $placeHoldersToFeedAttributesMap[
            RealEstatePlaceholderField::CONTEXTUAL_KEYWORDS]->getId(),
        'string_values' => ['beach community', 'ocean view', 'two bedroom']
    ]);

    // Creates the feed item, specifying the feed ID and the attributes created above.
    $feedItem = new FeedItem([
        'feed' => $feedResourceName,
        'attribute_values' => [
            $listingIdAttributeValue,
            $listingNameAttributeValue,
            $finalUrlsAttributeValue,
            $imageUrlAttributeValue,
            $contextualKeywordsAttributeValue
        ]
    ]);

    // Creates the feed item operation.
    $operation = new FeedItemOperation();
    $operation->setCreate($feedItem);

    // Issues a mutate request to add the feed item and print some information.
    $feedItemServiceClient = $googleAdsClient->getFeedItemServiceClient();
    $response = $feedItemServiceClient->mutateFeedItems($customerId, [$operation]);
    printf(
        "Feed item with resource name '%s' was created.%s",
        $response->getResults()[0]->getResourceName(),
        PHP_EOL
    );
}
      

Python

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

Ruby

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

Perl

sub create_feed_item {
  my ($api_client, $customer_id, $feed_attributes, $feed_resource_name) = @_;

  # Create the listing ID feed attribute value.
  my $listing_id =
    Google::Ads::GoogleAds::V6::Resources::FeedItemAttributeValue->new({
      feedAttributeId => $feed_attributes->{LISTING_ID}{id},
      stringValue     => "ABC123DEF"
    });
  # Create the listing name feed attribute value.
  my $listing_name =
    Google::Ads::GoogleAds::V6::Resources::FeedItemAttributeValue->new({
      feedAttributeId => $feed_attributes->{LISTING_NAME}{id},
      stringValue     => "Two bedroom with magnificent views"
    });
  # Create the final URLs feed attribute value.
  my $final_urls =
    Google::Ads::GoogleAds::V6::Resources::FeedItemAttributeValue->new({
      feedAttributeId => $feed_attributes->{FINAL_URLS}{id},
      stringValue     => "http://www.example.com/listings/"
    });

  # Optionally insert additional attributes here, such as address, city, description, etc.

  # Create the image URL feed attribute value.
  my $image_url =
    Google::Ads::GoogleAds::V6::Resources::FeedItemAttributeValue->new({
      feedAttributeId => $feed_attributes->{IMAGE_URL}{id},
      stringValue     =>
        "http://www.example.com/listings/images?listing_id=ABC123DEF"
    });
  # Create the contextual keywords feed attribute value.
  my $contextual_keywords =
    Google::Ads::GoogleAds::V6::Resources::FeedItemAttributeValue->new({
      feedAttributeId => $feed_attributes->{CONTEXTUAL_KEYWORDS}{id},
      stringValues    => ["beach community", "ocean view", "two bedroom"]});

  # Create a feed item, specifying the Feed ID and the attributes created above.
  my $feed_item = Google::Ads::GoogleAds::V6::Resources::FeedItem->new({
      feed            => $feed_resource_name,
      attributeValues => [
        $listing_id, $listing_name, $final_urls,
        $image_url,  $contextual_keywords
      ]});

  # Create a feed item operation.
  my $feed_item_operation =
    Google::Ads::GoogleAds::V6::Services::FeedItemService::FeedItemOperation->
    new({
      create => $feed_item
    });

  # Add the feed item.
  my $feed_items_response = $api_client->FeedItemService()->mutate({
      customerId => $customer_id,
      operations => [$feed_item_operation]});

  printf "Created feed item with resource name '%s'.\n",
    $feed_items_response->{results}[0]{resourceName};
}
      

Step 3 - Remove sold listings

The process for removing sold listings is even simpler—all you need is the FeedItem resource_name.

If you don't have the resource_name of a sold listing, you can use the Google Ads Query Language to construct a query that retrieves feed_item fields from a feed with a given resource name.

The basic steps for each listing you want to remove are:

  1. Create a new FeedItemOperation and set its remove operation to the resource name of the FeedItem you want to remove.
  2. Like any other mutate operation, pass the FeedItemOperation to the MutateFeedItemsRequest.

Java

private void removeAttributeFromFeedItem(
    GoogleAdsClient googleAdsClient,
    long customerId,
    long feedId,
    long feedItemId,
    String flightPlaceholderField) {
  // Gets the feed resource name.
  String feedResourceName = ResourceNames.feed(customerId, feedId);

  // Gets a map of the placeholder values and feed attributes.
  Map<FlightPlaceholderField, FeedAttribute> feedAttributes =
      AddFlightsFeed.getFeed(googleAdsClient, customerId, feedResourceName);

  // Gets the feed item resource name.
  String feedItemResourceName = ResourceNames.feedItem(customerId, feedId, feedItemId);
  // Removes the attribute from the feed item.
  FeedItem feedItem =
      removeAttributeValueFromFeedItem(
          googleAdsClient,
          customerId,
          feedAttributes,
          feedItemResourceName,
          FlightPlaceholderField.valueOf(flightPlaceholderField.toUpperCase()));

  // Creates the operation.
  FeedItemOperation operation =
      FeedItemOperation.newBuilder()
          .setUpdate(feedItem)
          .setUpdateMask(FieldMasks.allSetFieldsOf(feedItem))
          .build();

  // Creates the feed item service client.
  try (FeedItemServiceClient feedItemServiceClient =
      googleAdsClient.getLatestVersion().createFeedItemServiceClient()) {
    // Updates the feed item.
    MutateFeedItemsResponse response =
        feedItemServiceClient.mutateFeedItems(
            Long.toString(customerId), ImmutableList.of(operation));
    for (MutateFeedItemResult result : response.getResultsList()) {
      System.out.printf("Updated feed item with resource name '%s'.%n", result.getResourceName());
    }
  }
}
      

C#

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

PHP

// Creates the feed item operation.
$operation = new FeedItemOperation();
$operation->setUpdate($feedItem);
$operation->setUpdateMask(FieldMasks::allSetFieldsOf($feedItem));

// Issues a mutate request to update the feed item and print some information.
$feedItemServiceClient = $googleAdsClient->getFeedItemServiceClient();
$response = $feedItemServiceClient->mutateFeedItems($customerId, [$operation]);
printf(
    "Feed item with resource name '%s' was updated to remove the value of"
    . " placeholder field type '%s'.%s",
    $response->getResults()[0]->getResourceName(),
    $flightPlaceholderFieldName,
    PHP_EOL
);
      

Python

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

Ruby

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

Perl

# Create a feed item operation.
my $feed_item_operation =
  Google::Ads::GoogleAds::V6::Services::FeedItemService::FeedItemOperation->
  new({
    update     => $feed_item,
    updateMask => all_set_fields_of($feed_item)});

# Update the feed item.
my $feed_items_response = $api_client->FeedItemService()->mutate({
    customerId => $customer_id,
    operations => [$feed_item_operation]});

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