Part 5 - Write a Reporting Method

Stay organized with collections Save and categorize content based on your preferences.

In this part we're going to use the Reporting API in the Google Ads API to retrieve information about the entities created in this example.

This is not necessary in practice because you can use the resource name returned from a mutate response as an input to mutate requests. However, we will use this strategy to demonstrate how resource retrieval works in the Google Ads API.

In this script we'll use the SearchStream method, but it's possible to achieve the same functionality with the Search method. Add a new method that we can reuse throughout this script that accepts a GAQL query and returns the first GoogleAdsRow in the response.

5.0.0: Method for Retrieving Entities with Reporting (Google Ads API Only)
def _search_google_ads(client, query):
    """Queries the Google Ads API with the given query.

    This method will only return the first row of the query, assuming that
    the query only requests a single entity.

        client: a GoogleAdsClient instance.
        query: a GAQL query string.

        A GoogleAdsRow instance or None.
    googleads_service = client.get_service("GoogleAdsService")
    stream = googleads_service.search_stream(customer_id=_CUSTOMER_ID, query=query)
    # Passing the stream to the list constructor forces the stream to process to
    # completion so that we don't have to write a for loop.
    googleads_search_stream_response = list(stream)[0]
        # Retrieve the first result from the response
        return googleads_search_stream_response.results[0]
    except IndexError:
        # Return None if the response is empty
        return None