إجراء طلب بيانات من واجهة برمجة التطبيقات

يتطلّب هذا الدليل عدة إعدادات مسبقة تم ضبطها في الخطوات السابقة. ابدأ بقراءة المقدمة إذا لم يسبق لك ذلك.

تقديم طلب بيانات من واجهة برمجة التطبيقات

اختَر العميل الذي تريده للحصول على تعليمات حول كيفية إجراء طلب بيانات من واجهة برمجة التطبيقات:

Java

يتم نشر عناصر مكتبة البرامج في مستودع Maven المركزي. أضِف مكتبة البرامج كعنصر تابع إلى مشروعك على النحو التالي:

تكون تبعية Maven على النحو التالي:

<dependency>
  <groupId>com.google.api-ads</groupId>
  <artifactId>google-ads</artifactId>
  <version>38.0.0</version>
</dependency>

تكون تبعية Gradle على النحو التالي:

implementation 'com.google.api-ads:google-ads:38.0.0'
api.googleads.serviceAccountSecretsPath=JSON_KEY_FILE_PATH
api.googleads.developerToken=INSERT_DEVELOPER_TOKEN_HERE
api.googleads.loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

أنشئ عنصر GoogleAdsClient على النحو التالي:

GoogleAdsClient googleAdsClient = null;
try {
  googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
  System.err.printf(
      "Failed to load GoogleAdsClient configuration from file. Exception: %s%n",
      fnfe);
  System.exit(1);
} catch (IOException ioe) {
  System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
  System.exit(1);
}

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

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

يتم نشر حِزم مكتبة البرامج إلى مستودع Nuget.org. ابدأ بإضافة مرجع nuget إلى حزمة Google.Ads.GoogleAds.

dotnet add package Google.Ads.GoogleAds --version 18.1.0

أنشئ عنصر GoogleAdsConfig يتضمّن الإعدادات ذات الصلة، واستخدِمه لإنشاء عنصر GoogleAdsClient.

GoogleAdsConfig config = new GoogleAdsConfig()
{
    DeveloperToken = "******",
    OAuth2Mode = OAuth2Flow.SERVICE_ACCOUNT,
    OAuth2SecretsJsonPath = "PATH_TO_CREDENTIALS_JSON",
    LoginCustomerId = ******
};
GoogleAdsClient client = new GoogleAdsClient(config);

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService = client.GetService(
        Services.V20.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

يتم نشر حِزم مكتبة البرامج في مستودع Packagist. انتقِل إلى الدليل الجذر لمشروعك وشغِّل الأمر التالي لتثبيت المكتبة وجميع العناصر التابعة لها في الدليل vendor/ الخاص بالدليل الجذر لمشروعك.

composer require googleads/google-ads-php:29.0.0

أنشئ نسخة من ملف google_ads_php.ini من مستودع GitHub وعدِّلها لتضمين بيانات الاعتماد الخاصة بك.

[GOOGLE_ADS]
developerToken = "INSERT_DEVELOPER_TOKEN_HERE"
loginCustomerId = "INSERT_LOGIN_CUSTOMER_ID_HERE"

[OAUTH2]
jsonKeyFilePath = "INSERT_ABSOLUTE_PATH_TO_OAUTH2_JSON_KEY_FILE_HERE"
scopes = "https://www.googleapis.com/auth/adwords"

أنشئ مثيلاً من الكائن GoogleAdsClient.

$oAuth2Credential = (new OAuth2TokenBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->build();

$googleAdsClient = (new GoogleAdsClientBuilder())
    ->fromFile('/path/to/google_ads_php.ini')
    ->withOAuth2Credential($oAuth2Credential)
    ->build();

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

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

يتم توزيع مكتبة البرامج على PyPI ويمكن تثبيتها باستخدام الأمر pip على النحو التالي:

python -m pip install google-ads==21.3.0

أنشئ نسخة من ملف google-ads.yaml من مستودع GitHub وعدِّلها لتضمين بيانات الاعتماد الخاصة بك.

developer_token: INSERT_DEVELOPER_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
json_key_file_path: JSON_KEY_FILE_PATH_HERE

أنشئ مثيلاً من GoogleAdsClient عن طريق استدعاء الطريقة GoogleAdsClient.load_from_storage. مرِّر مسار google-ads.yaml كسلسلة إلى الطريقة عند استدعائها:

from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("path/to/google-ads.yaml")

أضِف معالجًا إلى أداة تسجيل المكتبة لتحديد مكان طباعة السجلات. سيؤدي ما يلي إلى توجيه مسجّل المكتبة إلى الطباعة في وحدة التحكّم(stdout).

import logging
import sys

logger = logging.getLogger('google.ads.googleads.client')
logger.addHandler(logging.StreamHandler(sys.stdout))

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

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

يتم نشر حِزم Ruby الخاصة بمكتبة البرامج على موقع استضافة حِزم Rubygems. الطريقة المقترَحة للتثبيت هي استخدام أداة Bundler. أضِف سطرًا إلى ملف Gemfile:

gem 'google-ads-googleads', '~> 34.0.0'

بعد ذلك، استخدِم الأمر التالي:

bundle install

أنشئ نسخة من ملف google_ads_config.rb من مستودع GitHub وعدِّلها لتضمين بيانات الاعتماد الخاصة بك.

Google::Ads::GoogleAds::Config.new do |c|
  c.developer_token = 'INSERT_DEVELOPER_TOKEN_HERE'
  c.login_customer_id = 'INSERT_LOGIN_CUSTOMER_ID_HERE'
  c.keyfile = 'JSON_KEY_FILE_PATH'
end

أنشئ مثيلاً من GoogleAdsClient عن طريق تمرير المسار إلى المكان الذي تحتفظ فيه بهذا الملف.

client = Google::Ads::GoogleAds::GoogleAdsClient.new('path/to/google_ads_config.rb')

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

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

يتم توزيع المكتبة على CPAN. ابدأ بنسخ مستودع google-ads-perl في الدليل الذي تختاره.

git clone https://github.com/googleads/google-ads-perl.git

انتقِل إلى الدليل google-ads-perl ونفِّذ الأمر التالي في موجه الأوامر لتثبيت جميع التبعيات اللازمة لاستخدام المكتبة.

cd google-ads-perl
cpan install Module::Build
perl Build.PL
perl Build installdeps

أنشئ نسخة من ملف googleads.properties من مستودع GitHub وعدِّلها لتضمين بيانات الاعتماد الخاصة بك.

jsonKeyFilePath=JSON_KEY_FILE_PATH
developerToken=INSERT_DEVELOPER_TOKEN_HERE
loginCustomerId=INSERT_LOGIN_CUSTOMER_ID_HERE

أنشئ مثيلاً من Client عن طريق تمرير المسار إلى المكان الذي تحتفظ فيه بهذا الملف.

my $properties_file = "/path/to/googleads.properties";

my $api_client = Google::Ads::GoogleAds::Client->new({
  properties_file => $properties_file
});

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

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::V20::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;
}

REST

ابدأ بضبط حساب الخدمة كبيانات الاعتماد النشطة في gcloud CLI.

gcloud auth login --cred-file=PATH_TO_CREDENTIALS_JSON

بعد ذلك، احصل على رمز دخول OAuth 2.0 المميز لواجهة Google Ads API.

gcloud auth \
  print-access-token \
  --scopes='https://www.googleapis.com/auth/adwords'

بعد ذلك، شغِّل تقرير حملة باستخدام طريقة GoogleAdsService.SearchStream لاسترداد الحملات في حسابك. لا يغطّي هذا الدليل تفاصيل عملية الإبلاغ.

curl -i -X POST https://googleads.googleapis.com/v20/customers/CUSTOMER_ID/googleAds:searchStream \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer ACCESS_TOKEN" \
   -H "developer-token: DEVELOPER_TOKEN" \
   -H "login-customer-id: LOGIN_CUSTOMER_ID" \
   --data-binary "@query.json"

في ما يلي محتوى query.json:

{
  "query": "SELECT campaign.id, campaign.name, campaign.network_settings.target_content_network FROM campaign ORDER BY campaign.id"
}