Отчет о кампании в CSV

Джава

This example is not yet available in Java; you can take a look at the other languages.
    

С#

// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V16.Services;
using Google.Api.Ads.Common.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Google.Ads.GoogleAds.Examples.V16
{
    /// <summary>
    /// This code example illustrates how to use Google Ads API to get metrics about a campaign and
    /// serialize the result as a CSV file.
    /// </summary>
    public class CampaignReportToCsv : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="CampaignReportToCsv"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// Optional output file path. If left null, a file `CampaignReportToCsv.csv` will
            /// be created in the user's home directory.
            /// </summary>
            [Option("OutputFilePath", Required = false, HelpText =
                "Optional output file path. If left null, a file `CampaignReportToCsv.csv` will " +
                "be created in the user's home directory.")]
            public string OutputFilePath { get; set; }
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example illustrates how to get metrics about a campaign and serialize the " +
            "result as a CSV file.";

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            CampaignReportToCsv codeExample = new CampaignReportToCsv();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(),
                options.CustomerId,
                options.OutputFilePath);
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="outputFilePath">The path to which the CSV file is written.</param>
        public void Run(GoogleAdsClient client, long customerId, string outputFilePath)
        {
            GoogleAdsServiceClient googleAdsServiceClient =
                client.GetService(Services.V16.GoogleAdsService);

            // Create a query that retrieves campaigns.
            string query = @"
                SELECT
                    campaign.id,
                    campaign.name,
                    segments.date,
                    metrics.impressions,
                    metrics.clicks,
                    metrics.cost_micros
                FROM campaign
                WHERE segments.date DURING LAST_30_DAYS
                    AND campaign.status = 'ENABLED'
                ORDER BY segments.date DESC";

            // Issues a search request.
            googleAdsServiceClient.SearchStream(customerId.ToString(), query,
                delegate (SearchGoogleAdsStreamResponse response)
                {
                    if (response.Results.Count() == 0)
                    {
                        Console.WriteLine("No results found!");
                        return;
                    }

                    CsvFile csvFile = new CsvFile();

                    // Set the header for the CSV file.
                    csvFile.Headers.AddRange(response.FieldMask.Paths);

                    // Iterate over all returned rows and extract the information.
                    foreach (GoogleAdsRow googleAdsRow in response.Results)
                    {
                        csvFile.Records.Add(new string[]
                        {
                            googleAdsRow.Campaign.Id.ToString(),
                            googleAdsRow.Campaign.Name,
                            googleAdsRow.Segments.Date,
                            googleAdsRow.Metrics.Impressions.ToString(),
                            googleAdsRow.Metrics.Clicks.ToString(),
                            googleAdsRow.Metrics.CostMicros.ToString()
                        });
                    }

                    if (outputFilePath == null)
                    {
                        outputFilePath =
                            Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) +
                            Path.DirectorySeparatorChar +
                            GetType().Name +
                            DateTime.Now.ToString("-yyyyMMMMdd-HHmmss") + ".csv";
                    }
                    else if (!outputFilePath.EndsWith(".csv"))
                    {
                        outputFilePath += ".csv";
                    }

                    // Create the file with the specified path, write all lines, and close it.
                    csvFile.Write(outputFilePath);

                    Console.WriteLine(
                        $"Successfully wrote {response.Results.Count()} entries to {outputFilePath}.");
                }
            );
        }
    }
}
      

PHP

<?php

/**
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\Misc;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsException;
use Google\Ads\GoogleAds\V16\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V16\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V16\Services\SearchGoogleAdsRequest;
use Google\ApiCore\ApiException;

/**
 * This code example illustrates how to get metrics about a campaign and serialize the result as a
 * CSV file.
 */
class CampaignReportToCsv
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // Optional: You may pass the output file path on the command line or specify it here. If
    // neither are set a null value will be passed to the runExample() method and the default
    // path will be used: `CampaignReportToCsv.csv` file in the folder where the script is located.
    private const OUTPUT_FILE_PATH = null;
    private const PAGE_SIZE = 1000;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::OUTPUT_FILE_PATH => GetOpt::OPTIONAL_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::OUTPUT_FILE_PATH] ?: self::OUTPUT_FILE_PATH
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string|null $outputFilePath the path of the file to write the CSV content to
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        ?string $outputFilePath
    ) {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        // Creates a query that retrieves campaigns.
        $query =
            "SELECT campaign.id, "
                . "campaign.name, "
                . "segments.date, "
                . "metrics.impressions, "
                . "metrics.clicks, "
                . "metrics.cost_micros "
            . "FROM campaign "
            . "WHERE segments.date DURING LAST_7_DAYS "
                . "AND campaign.status = 'ENABLED' "
            . "ORDER BY segments.date DESC";

        // Issues a search request by specifying page size.
        $response = $googleAdsServiceClient->search(
            SearchGoogleAdsRequest::build($customerId, $query)->setPageSize(self::PAGE_SIZE)
        );

        // Iterates over all rows in all pages and extracts the information.
        $csvRows = [];
        foreach ($response->iterateAllElements() as $googleAdsRow) {
            /** @var GoogleAdsRow $googleAdsRow */
            $csvRows[] = [
                'campaign.id' => $googleAdsRow->getCampaign()->getId(),
                'campaign.name' => $googleAdsRow->getCampaign()->getName(),
                'segments.date' => $googleAdsRow->getSegments()->getDate(),
                'metrics.impressions' => $googleAdsRow->getMetrics()->getImpressions(),
                'metrics.clicks' => $googleAdsRow->getMetrics()->getClicks(),
                'metrics.cost_micros' => $googleAdsRow->getMetrics()->getCostMicros()
            ];
        }

        if (empty($csvRows)) {
            print "No results found.";
            return;
        }

        // Uses default output file path when not set.
        if (is_null($outputFilePath)) {
            $outputFilePath = str_replace('.php', '.csv', __FILE__);
        }

        // Writes the results to the CSV file.
        $outputFile = fopen($outputFilePath, 'w');
        // Uses the keys of the first result row as a header row.
        fputcsv($outputFile, array_keys($csvRows[0]));
        foreach ($csvRows as $csvRow) {
            fputcsv($outputFile, array_values($csvRow));
        }
        fclose($outputFile);

        printf('Successfully created %s with %d entries', $outputFilePath, count($csvRows));
    }
}

CampaignReportToCsv::main();

      

Питон

#!/usr/bin/env python
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Shows how to write data from a basic campaign stats report to a CSV file.

This is important for migration because reports from the AdWords API are
returned in CSV format, so clients that are migrating may want to temporarily
convert Google Ads API reports to CSV while migrating their applications.

Examples:
    Write to file output.csv in the same directory as script with headers.
        $ python get_campaign_stats_to_csv.py -c 0123456789 -o output.csv -w

    Write to file output.csv in the same directory as script without headers.
        $ python get_campaign_stats_to_csv.py -c 0123456789 -o output.csv
"""
import argparse
import csv
import sys
import os

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


_DEFAULT_FILE_NAME = "campaign_report_to_csv_results.csv"


def main(client, customer_id, output_file, write_headers):
    """Writes rows returned from a search_stream request to a CSV file.
    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id (str): The client customer ID string.
        output_file (str): Filename of the file to write the report data to.
        write_headers (bool): From argparse, True if arg is provided.
    """
    file_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(file_dir, output_file)
    ga_service = client.get_service("GoogleAdsService")

    query = """
        SELECT
          customer.descriptive_name,
          segments.date,
          campaign.name,
          metrics.impressions,
          metrics.clicks,
          metrics.cost_micros
        FROM campaign
        WHERE
          segments.date DURING LAST_7_DAYS
        ORDER BY metrics.impressions DESC
        LIMIT 25"""

    # Issues a search request using streaming.
    search_request = client.get_type("SearchGoogleAdsStreamRequest")
    search_request.customer_id = customer_id
    search_request.query = query
    stream = ga_service.search_stream(search_request)

    with open(file_path, "w", newline="") as f:
        writer = csv.writer(f)

        # Define a list of headers for the first row.
        headers = [
            "Account",
            "Date",
            "Campaign",
            "Impressions",
            "Clicks",
            "Cost",
        ]

        # If the write_headers flag was passed, write header row to the CSV
        if write_headers:
            writer.writerow(headers)

        for batch in stream:
            for row in batch.results:
                # Use the CSV writer to write the individual GoogleAdsRow
                # fields returned in the SearchGoogleAdsStreamResponse.
                writer.writerow(
                    [
                        row.customer.descriptive_name,
                        row.segments.date,
                        row.campaign.name,
                        row.metrics.impressions,
                        row.metrics.clicks,
                        row.metrics.cost_micros,
                    ]
                )

        print(f"Customer {customer_id} report written to {output_file}")


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = GoogleAdsClient.load_from_storage(version="v16")

    parser = argparse.ArgumentParser(
        description="Retrieves a campaign stats and writes to CSV file."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID of the account you would like to get "
        "the report for to write to CSV.",
    )
    parser.add_argument(
        "-o",
        "--output_file",
        type=str,
        required=False,
        default=_DEFAULT_FILE_NAME,
        help="Name of the local CSV file to save the report to. File will be "
        "saved in the same directory as the script.",
    )
    # Optional boolean argument for writing headers.
    parser.add_argument(
        "-w",
        "--write_headers",
        action="store_true",
        help="Writes headers to the CSV file if argument is supplied. Simply "
        "add -w if you want the headers defined in the script to be "
        "added as the first row in the CSV file.",
    )
    args = parser.parse_args()

    try:
        main(
            google_ads_client,
            args.customer_id,
            args.output_file,
            args.write_headers,
        )
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Рубин

#!/usr/bin/ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example illustrates how to get metrics about a campaign and 
# serialize the result as a CSV file.

require 'optparse'
require 'time'
require 'csv'
require 'google/ads/google_ads'

PAGE_SIZE = 1000

def result_row_as_csv_hash(result_row)
  {
    "campaign.id": result_row.campaign.id.value,
    "campaign.name": result_row.campaign.name.value,
    "campaign.date": Time.parse(result_row.segments.date.value),
    "metrics.impressions": result_row.metrics.impressions.value,
    "metrics.clicks": result_row.metrics.clicks.value,
    "metrics.cost_micros": result_row.metrics.cost_micros.value,
  }
end

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

  ga_service = client.service.google_ads

  query = <<~QUERY
      SELECT campaign.id,
             campaign.name,
             segments.date,
             metrics.impressions,
             metrics.clicks,
             metrics.cost_micros
      FROM campaign
      WHERE segments.date DURING LAST_7_DAYS
        AND campaign.status = 'ENABLED'
      ORDER BY segments.date DESC
  QUERY

  response = ga_service.search(customer_id: customer_id, query: query, page_size: PAGE_SIZE)
  # convert the Google Ads response rows in to CSV ready hash objects
  csv_rows = response.map { |row| result_row_as_csv_hash(row) }

  if csv_rows.empty?
    puts "No results found."
    return
  end

  CSV.open(target_filepath, "wb") do |csv|
    # use the keys of the first csv_row as a header row
    csv << csv_rows.first.keys

    # write all the values as rows of the CSV
    csv_rows.each do |row|
      csv << row.values
    end
  end

  puts "successfully created #{target_filepath} with #{csv_rows.count} entries"
end

if __FILE__ == $PROGRAM_NAME
  options = {}

  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_GOOGLE_ADS_CUSTOMER_ID_HERE'
  options[:output_file_path] = __FILE__.gsub(".rb", ".csv")
  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-O', '--output-file-path OUTPUT-FILE-PATH', String, 'Output File Path') do |v|
      options[:output_file_path] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    # the GoogleAdsClient only accepts customer IDs without `-` characters,
    # so this removes them if the caller of this script copy pasted a customer
    # id directly from the user interface
    sanitized_customer_id = options.fetch(:customer_id).tr("-", "")

    write_campaign_report_csv(sanitized_customer_id, options.fetch(:output_file_path))
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Перл

#!/usr/bin/perl -w
#
# Copyright 2021, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example illustrates how to get metrics about a campaign and serialize
# the result as a CSV file.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator;
use
  Google::Ads::GoogleAds::V16::Services::GoogleAdsService::SearchGoogleAdsRequest;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

use constant PAGE_SIZE => 1000;

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
# Optional: You may pass the output file path on the command line or specify it
# here. If neither are set a null value will be passed to the campaign_report_to_csv()
# method and the default path will be used: `campaign_report_to_csv.csv` file in
# the folder where the script is located.
my $output_file_path = undef;

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

  # Create a query that retrieves campaigns.
  my $query =
    "SELECT campaign.id, campaign.name, segments.date, " .
    "metrics.impressions, metrics.clicks, metrics.cost_micros " .
    "FROM campaign WHERE segments.date DURING LAST_7_DAYS " .
    "AND campaign.status = 'ENABLED' ORDER BY segments.date DESC";

  # Create a search Google Ads request that that retrieves campaigns.
  my $search_request =
    Google::Ads::GoogleAds::V16::Services::GoogleAdsService::SearchGoogleAdsRequest
    ->new({
      customerId => $customer_id,
      query      => $query,
      pageSize   => PAGE_SIZE
    });

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

  my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({
    service => $google_ads_service,
    request => $search_request
  });

  # Iterate over all rows in all pages and extract the information.
  my $csv_rows = [];
  while ($iterator->has_next) {
    my $google_ads_row = $iterator->next;
    push @$csv_rows,
      [
      $google_ads_row->{campaign}{id},
      $google_ads_row->{campaign}{name},
      $google_ads_row->{segments}{date},
      $google_ads_row->{metrics}{impressions},
      $google_ads_row->{metrics}{clicks},
      $google_ads_row->{metrics}{costMicros}];
  }

  if (scalar @$csv_rows == 0) {
    print "No results found.\n";
    return 0;
  }

  # Use default output file path when not set.
  if (!$output_file_path) {
    $output_file_path = __FILE__ =~ s/\.pl/.csv/r;
  }

  # Write the results to the CSV file.
  open(CSV, ">", $output_file_path)
    or die "Could not open file '$output_file_path'.";
  # Write the header row.
  print CSV join(
    ",",
    (
      "campaign.id",    "campaign.name",
      "segments.date",  "metrics.impressions",
      "metrics.clicks", "metrics.cost_micros"
    )
    ),
    "\n";
  foreach my $csv_row (@$csv_rows) {
    print CSV join(",", @$csv_row), "\n";
  }
  close(CSV);

  printf "Successfully created %s with %d entries.", $output_file_path,
    scalar @$csv_rows;

  return 1;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"      => \$customer_id,
  "output_file_path=s" => \$output_file_path
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id);

# Call the example.
campaign_report_to_csv($api_client, $customer_id =~ s/-//gr, $output_file_path);

=pod

=head1 NAME

campaign_report_to_csv

=head1 DESCRIPTION

This code example illustrates how to get metrics about a campaign and serialize
the result as a CSV file.

=head1 SYNOPSIS

campaign_report_to_csv.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -output_file_path           [optional] The output file path.

=cut