Google Ads API is returning to beta status. Please read our blog post for more details.

Retrieving Objects

The GoogleAdsService is the unified object retrieval and reporting service of the Google Ads API. The service has a search method that:

  • Retrieves specific attributes of objects.
  • Retrieves performance metrics for objects based on a date range.
  • Orders objects based on their attributes.
  • Uses conditions to indicate which objects you want returned in the response.
  • Uses paging to break up large responses into manageable pages of results.
  • Limits the number of objects returned.

Making a request

The search method requires a SearchGoogleAdsRequest, which consists of the following attributes:

  • A customer_id.
  • A Google Ads Query Language query that indicates which resource to query, the attributes, segments, and metrics to retrieve, and the conditions to use to restrict which objects are returned.
  • A page_size to indicate how many objects to return in a single response when using paging.
  • An optional page_token to retrieve the next batch of results when using paging.

For more information on the Google Ads Query Language, check out the Google Ads Query Language guide.

Processing a response

A GoogleAdsService search request returns a SearchGoogleAdsResponse, which consists of the following attributes:

  • A results collection of GoogleAdsRow objects.

  • A total_results_count that indicates the total number of results that match the query, ignoring the LIMIT clause.

  • A next_page_token for requesting the next batch of results from the result set.

  • A field_mask that indicates which fields you requested in the SELECT clause of your query.

Paging through results

Google Ads Query Language supports paging by specifying page_size in your request. This will break up the result set of the query into multiple responses that each contains up to page_size objects. If page_size is not specified, it is automatically set to the maximum page size of 10,000.

For example, with the following query:

SELECT ad_group.id, ad_group_criterion.type, ad_group_criterion.criterion_id,
       ad_group_criterion.keyword.text, ad_group_criterion.keyword.match_type
FROM ad_group_criterion
WHERE ad_group_criterion.type = KEYWORD

If your account contains 50,000 keywords and page_size is set to 1,000, the result set will contain 1,000 GoogleAdsRow objects in the first response, along with a next_page_token. To retrieve the next one thousand rows, simply send the request again with the same page size, but update the request's page_token to the response's next_page_token. The value of page_size in the subsequent requests can be different each time.

Our client libraries handle paging automatically. You only have to iterate through the rows of the response. When all the rows in the current page have been returned, the client library will fetch a new page of rows automatically on your behalf until the entire data set has been retrieved. If using REST instead of gRPC, you must explicitly make a request for each new page.

Google Ads API internally caches the entire data set, so subsequent requests are faster than the first request. Depending on your use case, you can set page_size to any value between 1 and 10,000. In general, for faster overall performance, you should use a larger page_size due to fewer round trips in your responses.

Your query must remain exactly the same in subsequent requests to take advantage of the cached data; the requests won't contribute towards your quota, particularly for basic access. If the query differs and it is sent along with the page token, it will result in an error. When manual paging is required such as during web page navigation, you can retrieve one page at a time with a page token:

Java

try (GoogleAdsServiceClient googleAdsServiceClient = GoogleAdsServiceClient.create()) {
  int pageSize = 50;
  String customerId = "INSERT_CUSTOMER_ID_HERE";
  String query = "SELECT campaign.id, campaign.name FROM campaign";

  SearchGoogleAdsRequest request =
      SearchGoogleAdsRequest.newBuilder()
          .setCustomerId(customerId)
          .setPageSize(pageSize)
          .setQuery(query)
          .build();

  while (true) {
    SearchGoogleAdsResponse response = googleAdsServiceClient.searchCallable().call(request);
    for (GoogleAdsRow element : response.getResultsList()) {
      System.out.printf(
          "Campaign with ID %d and name '%s' was found.%n",
          element.getCampaign().getId().getValue(), element.getCampaign().getName().getValue());
    }

    String nextPageToken = response.getNextPageToken();
    if (!Strings.isNullOrEmpty(nextPageToken)) {
      request = request.toBuilder().setPageToken(nextPageToken).build();
    } else {
      break;
    }
  }

}

C#

private void PerPageLoopingExample(GoogleAdsClient client, long customerId)
{
  string query = "SELECT campaign.id, campaign.name FROM campaign";

  string pageToken = null;
  const int PAGE_SIZE = 20;

  do
  {
    pageToken = ProcessAPage(client, customerId.ToString(), query,
      PAGE_SIZE, pageToken);
  }
  while (pageToken != null);
}

private string ProcessAPage(GoogleAdsClient client, string customerId, string query,
  int pageSize, string pageToken)
{
  // Get the GoogleAdsService.
  GoogleAdsServiceClient googleAdsService = client.GetService(
    Services.V1.GoogleAdsService);

  // Create a SearchGoogleAdsRequest for the query.
  SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
  {
    Query = query,
    PageSize = pageSize,
    CustomerId = customerId,
  };

  // If a pageToken is not provided, a fresh query will run on the server.
  if (pageToken != null)
  {
    request.PageToken = pageToken;
  }

  // Issue a search request.
  IEnumerable response =
    googleAdsService.Search(request).AsRawResponses();

  // Obtain the first page.
  SearchGoogleAdsResponse currentResponse = response.FirstOrDefault();

  // Process the results.
  foreach (GoogleAdsRow row in currentResponse.Results)
  {
    Console.WriteLine($"{row.Campaign.Id}, {row.Campaign.Name}");
  }

  // Store the next page token for retrieving the next page in the future.
  return currentResponse.NextPageToken;
}

PHP

$pageSize = 50;
$customerId = 'INSERT_CUSTOMER_ID_HERE';
$query = 'SELECT campaign.id, campaign.name FROM campaign';
$nextPageToken = null;

while (true) {
    $response = $googleAdsServiceClient->search($customerId, $query,
        ['pageSize' => $pageSize, 'pageToken' => $nextPageToken]);

    $page = $response->getPage();
    foreach ($page as $element) {
        printf(
            "Campaign with ID %d and name '%s' was found.%s",
            $element->getCampaign()->getId()->getValue(),
            $element->getCampaign()->getName()->getValue(),
            PHP_EOL
        );
    }

    if (empty($page->getNextPageToken())) {
        break;
    } else {
        $nextPageToken = $page->getNextPageToken();
    }
}

Understanding the GoogleAdsRow

A GoogleAdsRow represents an object returned by a query, and consists of a set of attributes that are populated based on the fields requested in the SELECT clause.

For example, the response for the criteria query above will contain a collection of GoogleAdsRow objects with the following attributes populated:

ad_group
  id
ad_group_criterion
  type
  criterion_id
  keyword
    text
    match_type

For example, although an ad_group_criterion has a status attribute, the status field of the row's ad_group_criterion attribute will not be populated in a response for the query above because the SELECT clause does not include ad_group_criterion.status. Similarly, the campaign attribute of the row will not be populated because the SELECT clause does not include any fields from the campaign resource.

Segmentation

The response will contain one GoogleAdsRow for each combination of the following:

  • instance of the main resource specified in the FROM clause
  • value of each selected segment field

For example, the response for a query that selects FROM campaign and has segments.ad_network_type and segments.date in the SELECT clause will contain one row for each combination of the following:

  • campaign
  • segments.ad_network_type
  • segments.date

Send feedback about...

Google Ads API Beta
Google Ads API Beta
Need help? Visit our support page.