Most Google Ads entities expose a getId()
method that returns their
identifier. While not strictly necessary in most cases, IDs may come in handy
when
- Working with reports
- IDs provide a good way to link a report row to the actual Google Ads entity.
- Maintaining a mapping with an external datastore
- You may already have ID-based information stored in your own database.
- Looking for a bit of a performance boost
Fetching by IDs is often quicker than alternatives. The code for fetching a single entity is a bit easier too:
let campaigns = AdsApp.campaigns() .withIds([678678]) .get(); // versus let campaigns = AdsApp.campaigns() .withCondition("Name='My Campaign'") .get();
Uniqueness
Campaign IDs and ad group IDs are unique: no two campaigns or ad groups will
ever share the same ID. Ads and keywords, however, have composite IDs: a unique
identifier of a keyword is a combination of its ad group ID and keyword ID.
Likewise, a unique identifier of an ad is a combination of its ad group ID and
ad ID. This has implications for the way selector.withIds()
is called.
For campaigns and ad groups, selector.withIds()
expects an array of numbers:
let ids = [123123, 234234, 345345];
let campaignSelector = AdsApp.campaigns().withIds(ids);
For ads and keywords, however, selector.withIds()
needs an array of
two-element arrays, the first element being the ad group ID. The following
snippet retrieves three keywords from an ad group:
let adGroupId = 123123;
let keywordSelector = AdsApp.keywords().withIds([
[adGroupId, 234234],
[adGroupId, 345345],
[adGroupId, 456456]
]);
The same construct applies when fetching ads.
Temporary IDs
When working with a mutate request with multiple operations, you'll occasionally need to use temporary IDs to link resources to each other, since the full resource names won't be available until you get the API response. Temporary IDs must be negative numbers starting with -1, and cannot repeat within the same mutate request. In order to use temporary IDs effectively, you'll have to write some code to ensure that you don't create duplicate temporary IDs:
let nextId = -1;
function getNextTempId() {
const ret = nextId;
nextId -= 1;
return ret;
}
Each successive call to getNextTempId
will return a number one less than the
previous. Since all temp IDs must be negative, start at -1.
Temporary IDs are not remembered across jobs or mutate requests. To reference a resource created in a previous mutate request, use its actual resource name.