Client Libraries

Our client libraries provide high-level views and basic building blocks of Google Ads API functionality, making it easier to develop apps quickly. We recommend starting out with one if you're new to the API.

Client library Source Distribution Code examples
Java google-ads-java Maven, tar.gz View on GitHub
.NET google-ads-dotnet nuget, tar.gz, zip View on GitHub
PHP google-ads-php tar.gz View on GitHub
Python google-ads-python tar.gz, zip View on GitHub
Ruby google-ads-ruby gem, tar.gz, zip View on GitHub
Perl google-ads-perl tar.gz, zip View on GitHub

Supported API versions

The table shows which client libraries work with which API versions.

Java

Client library for Java
v17 Min: 32.0.0
Max: -
v16 Min: 30.0.0
Max: -

C#

Client library for .NET
v17 Min: 20.1.0
Max: -
v16 Min: 18.1.0
Max: -

PHP

Client library for PHP
v17 Min: 23.1.0
Max: -
v16 Min: 22.1.0
Max: -

Python

Client library for Python
v17 Min: 24.1.0
Max: -
v16 Min: 23.1.0
Max: -

Ruby

Client library for Ruby
v17 Min: 29.0.0
Max: -
v16 Min: 27.0.0
Max: -

Perl

Client library for Perl
v17 Min: 23.0.0
Max: -
v16 Min: 21.0.0
Max: -

Configuration

Each Ads API Client library provides different configuration settings and loading methods that you can use to customize its behavior.

Here are the environment variables that are common to all client libraries and that can be loaded to set configuration settings:

  • Client library
    • GOOGLE_ADS_CONFIGURATION_FILE_PATH: Path to the configuration file.
  • OAuth2
    • Application Mode
      • GOOGLE_ADS_CLIENT_ID : Set this value to your OAuth2 client ID.
      • GOOGLE_ADS_CLIENT_SECRET : Set this value to your OAuth2 client secret.
      • GOOGLE_ADS_REFRESH_TOKEN : Set this value to a pre-generated OAuth2 refresh token if you want to reuse OAuth2 tokens. This setting is optional.
    • Service Account Mode
      • GOOGLE_ADS_JSON_KEY_FILE_PATH : Set this value to the OAuth2 JSON configuration file path.
      • GOOGLE_ADS_IMPERSONATED_EMAIL : Set this value to the email address of the account you are impersonating.
  • Google Ads API
    • GOOGLE_ADS_DEVELOPER_TOKEN : Set this to your developer token.
    • GOOGLE_ADS_LOGIN_CUSTOMER_ID : This is the customer ID of the authorized customer to use in the request, without hyphens (-).
    • GOOGLE_ADS_LINKED_CUSTOMER_ID : This header is only required for methods that update the resources of an entity when permissioned through Linked Accounts in the Google Ads UI (AccountLink resource in the Google Ads API). Set this value to the customer ID of the data provider that updates the resources of the specified customer ID. It should be set without hyphens (-). To learn more about Linked Accounts, visit the Help Center.

Environment variables are commonly defined in a bash configuration file such as a .bashrc or .bash_profile file located in the $HOME directory. They can also be defined using the command line.

Here are some basic steps to define an environment variable using a .bashrc file using a terminal:

# Append the line "export GOOGLE_ADS_CLIENT_ID=1234567890" to
# the bottom of your .bashrc file.
echo "export GOOGLE_ADS_CLIENT_ID=1234567890" >> ~/.bashrc

# Update your bash environment to use the most recently updated
# version of your .bashrc file.
src ~/.bashrc

Environment variables can also be set in your terminal instance directly from the command line:

export GOOGLE_ADS_CLIENT_ID=1234567890

Another alternative is to set environment variables when calling the command that uses them:

GOOGLE_ADS_CLIENT_ID=1234567890 php /path/to/script/that/uses/envvar.php

Search pagination

GoogleAdsService.Search is typically used in interactive apps that display pages of results. The page size is fixed at 10,000 results per page.

Our client library automatically implements paging when you iterate results so that you can sequentially download and process them all at once, for example:

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    String query = "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id";
    // Constructs the SearchGoogleAdsStreamRequest.
    SearchGoogleAdsStreamRequest request =
        SearchGoogleAdsStreamRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setQuery(query)
            .build();

    // Creates and issues a search Google Ads stream request that will retrieve all campaigns.
    ServerStream<SearchGoogleAdsStreamResponse> stream =
        googleAdsServiceClient.searchStreamCallable().call(request);

    // Iterates through and prints all of the results in the stream response.
    for (SearchGoogleAdsStreamResponse response : stream) {
      for (GoogleAdsRow googleAdsRow : response.getResultsList()) {
        System.out.printf(
            "Campaign with ID %d and name '%s' was found.%n",
            googleAdsRow.getCampaign().getId(), googleAdsRow.getCampaign().getName());
      }
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V17.GoogleAdsService);

    // Create a query that will retrieve all campaigns.
    string query = @"SELECT
                    campaign.id,
                    campaign.name,
                    campaign.network_settings.target_content_network
                FROM campaign
                ORDER BY campaign.id";

    try
    {
        // Issue a search request.
        googleAdsService.SearchStream(customerId.ToString(), query,
            delegate (SearchGoogleAdsStreamResponse resp)
            {
                foreach (GoogleAdsRow googleAdsRow in resp.Results)
                {
                    Console.WriteLine("Campaign with ID {0} and name '{1}' was found.",
                        googleAdsRow.Campaign.Id, googleAdsRow.Campaign.Name);
                }
            }
        );
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
{
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that retrieves all campaigns.
    $query = 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id';
    // Issues a search stream request.
    /** @var GoogleAdsServerStreamDecorator $stream */
    $stream = $googleAdsServiceClient->searchStream(
        SearchGoogleAdsStreamRequest::build($customerId, $query)
    );

    // Iterates over all rows in all messages and prints the requested field values for
    // the campaign in each row.
    foreach ($stream->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign with ID %d and name '%s' was found.%s",
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getCampaign()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService")

    query = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream = ga_service.search_stream(customer_id=customer_id, query=query)

    for batch in stream:
        for row in batch.results:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )
      

Ruby

def get_campaigns(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  responses = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id',
  )

  responses.each do |response|
    response.results.each do |row|
      puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
    end
  end
end
      

Perl

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

  # Create a search Google Ads stream request that will retrieve all campaigns.
  my $search_stream_request =
    Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      =>
        "SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id"
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  # Issue a search request and process the stream response to print the requested
  # field values for the campaign in each row.
  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      printf "Campaign with ID %d and name '%s' was found.\n",
        $google_ads_row->{campaign}{id}, $google_ads_row->{campaign}{name};
    });

  return 1;
}
      

Code examples

Check out our code examples of some common functions in the Google Ads API.