Builders

Builders are the standard way to create entities in AdWords scripts. Builders allow you to build an AdWords entity either synchronously or asynchronously. You can also check whether the operation was successful or not, and take appropriate actions depending on the operation’s outcome. The following code snippet shows how to create a keyword using a builder.

// Retrieve your ad group.
var adGroup = AdWordsApp.adGroups().get().next();

// Create a keyword operation.
var keywordOperation = adGroup.newKeywordBuilder()
    .withCpc(1.2)
    .withText("shoes")
    .withFinalUrl("http://www.example.com/shoes")
    .build();

// Optional: examine the outcome. The call to isSuccessful()
// will block until the operation completes.
if (keywordOperation.isSuccessful()) {
  // Get the result.
  var keyword = keywordOperation.getResult();
} else {
  // Handle the errors.
  var errors = keywordOperation.getErrors();
}

The current release adds builder support for ads and keywords. The existing builders for ad groups and ad extensions - phone number, sitelinks and mobile apps have also been standardized. The addSitelink, addPhoneNumber, and addMobileApp methods of AdGroup and Campaign classes will now return the resulting operation.

Performance considerations

By default, AdWords scripts executes its operations asynchronously. This allows scripts to group your operations as batches, and achieve high performance. However, calling the Operation methods like isSuccessful() and getResult() forces AdWords scripts to flush their pending operations list, and thus may lead to poor performance. Instead, create an array to hold the operations, then iterate through that array to retrieve the results.

Poor performance Good performance
for (var i = 0; i < keywords.length; i++)
  var keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();

  // Bad: retrieving the result in the same
  // loop that creates the operation
  // leads to poor performance.
  var newKeyword =
      keywordOperation.getResult();
  newKeyword.applyLabel("New keywords”);
}
// Create an array to hold the operations
var operations = [];

for (var i = 0; i < keywords.length; i++) {
  var keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();
  operations.push(keywordOperation);
}

// Process the operations separately. Allows
// AdWords scripts to group operations into
// batches.
for (var i = 0; i < operations.length; i++) {
  var newKeyword = operations[i].getResult();
  newKeyword.applyLabel("New keywords”);
}

Send feedback about...

AdWords Scripts
AdWords Scripts
Need help? Visit our support page.