תחילת העבודה עם ה-API

כאן מוסבר איך מתחילים לכתוב אפליקציות שמשתמשות ב-Google Bid Manager API. ה-API מאפשר לנהל שאילתות ולאחזר מטא-נתונים של דוחות.

Bid Manager API v2 הוא הגרסה העדכנית ביותר הזמינה והמומלצת.

1. לפני שמתחילים

אם אתם לא מכירים את המושגים של Google Display & Video 360, כדאי לקרוא את מרכז העזרה של Display & Video 360 ולהתנסות בממשק המשתמש.

2. היערכות לאימות

כדי להתחיל להשתמש ב-Bid Manager API צריך קודם להשתמש בכלי ההגדרה, שמדריך אתכם ביצירת פרויקט ב-Google API Console, בהפעלת ה-API וביצירת פרטי כניסה.

יוצרים את פרטי הכניסה בפרוטוקול OAuth 2.0 על ידי לחיצה על Create credentials > OAuth client ID (יצירת פרטי כניסה > מזהה לקוח ב-OAuth). אחרי שיוצרים את פרטי הכניסה, מזהה הלקוח יופיע בדף Credentials. לוחצים על מזהה הלקוח כדי להציג פרטים כמו סוד לקוח, מזהי URI להפניה אוטומטית, כתובות מקורות של JavaScript וכתובת אימייל.

למידע נוסף קראו את המאמר בקשות הרשאה.

3. קריאה ל-Bid Manager API

בכרטיסיות הבאות יש מדריכים למתחילים לתכנות בשפות שונות. קוד לדוגמה דומה נמצא גם במאגר Bid Manager API דוגמאות

Java

  1. מייבאים את הספריות הנדרשות.

    import static java.nio.charset.StandardCharsets.UTF_8;
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.util.Utils;
    import com.google.api.services.doubleclickbidmanager.DoubleClickBidManager;
    import com.google.api.services.doubleclickbidmanager.model.ListQueriesResponse;
    import com.google.api.services.doubleclickbidmanager.model.Query;
    import java.io.Reader;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
  2. טוענים את הקובץ של סודות הלקוח ויוצרים פרטי כניסה להרשאה.

    בפעם הראשונה שתבצעו את השלב הזה, תתבקשו לאשר את הודעת ההרשאה בדפדפן. לפני שתאשרו, ודאו שנכנסתם באמצעות חשבון Google עם גישה ל-Display & Video 360. לאפליקציה שלכם תהיה הרשאה לגשת לנתונים מטעם החשבון שמחובר כרגע.

    // Read client secrets file.
    GoogleClientSecrets clientSecrets;
    try (Reader reader = Files.newBufferedReader(Paths.get(path-to-client-secrets-file), UTF_8)) {
      clientSecrets = GoogleClientSecrets.load(Utils.getDefaultJsonFactory(), reader);
    }
    
    // Generate authorization credentials.
    // Set up the authorization code flow.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            Utils.getDefaultTransport(),
            Utils.getDefaultJsonFactory(),
            clientSecrets,
            oauth-scopes)
        .build();
    
    Credential credential =
        new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
  3. יוצרים לקוח API מורשה.

    // Create authorized API client.
    DoubleClickBidManager service =
        new DoubleClickBidManager.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("bidmanager-java-installed-app-sample")
            .build();
    
  4. מבצעים פעולה.

    // Perform an operation.
    // Call the API, getting a list of 10 queries.
    ListQueriesResponse queriesResponse = service.queries().list().setPageSize(10).execute();
    
    // Print them out.
    System.out.println("Id\t\tName");
    if (queriesResponse.getQueries().size() > 0) {
      for (int i = 0; i < queriesResponse.getQueries().size(); i++) {
        Query currentQuery = queriesResponse.getQueries().get(i);
        System.out.printf(
            "%s\t%s%n",
            currentQuery.getQueryId(),
            currentQuery.getMetadata().getTitle());
      }
    } else {
      System.out.println("No queries exist.");
    }
    

למידע מפורט יותר על השימוש ב-Bid Manager API עם Java, תוכלו לקרוא את הקובץ README בקטע דוגמאות ל-Bid Manager API.

Python

  1. מייבאים את הספריות הנדרשות.

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient import discovery
    
  2. טוענים את הקובץ של סודות הלקוח ויוצרים פרטי כניסה להרשאה.

    בפעם הראשונה שתבצעו את השלב הזה, תתבקשו לאשר את הודעת ההרשאה בדפדפן. לפני שתאשרו, ודאו שנכנסתם באמצעות חשבון Google עם גישה ל-Display & Video 360. לאפליקציה שלכם תהיה הרשאה לגשת לנתונים מטעם החשבון שמחובר כרגע.

    # Set up a flow object to create the credentials using the
    # client secrets file and OAuth scopes.
    credentials = InstalledAppFlow.from_client_secrets_file(
        path-to-client-secrets-file, oauth-scopes).run_local_server()
    
  3. יוצרים לקוח API מורשה.

    # Build the discovery document URL.
    discovery_url = f'https://doubleclickbidmanager.googleapis.com/$discovery/rest?version=v2'
    
    # Build the API service.
    service = discovery.build(
        'doubleclickbidmanager',
        'v2',
        discoveryServiceUrl=discovery_url,
        credentials=credentials)
    
  4. מבצעים פעולה.

    # Build and execute queries.listqueries request.
    response = service.queries().list(pageSize='10').execute()
    
    # Print queries out.
    if 'queries' in response:
      print('Id\t\tName')
      for query in response['queries']:
        print('%s\t%s' % (query['queryId'], query['metadata']['title']))
    else:
      print('No queries exist.')
    

למידע מפורט יותר על השימוש ב-Bid Manager API עם Python, תוכלו לקרוא את הקובץ README שבדוגמאות ל-Bid Manager API.

PHP

הדוגמה הזו מבוססת על ההנחה שאתם מפעילים את ה-PHP עם שרת אינטרנט מובנה, ושהגדרתם את פרטי הכניסה כך שיפנו אוטומטית לדף האינטרנט הרלוונטי. לדוגמה, אפשר להריץ את הקוד הזה בקובץ index.php באמצעות הפקודה ופרטי הכניסה הבאים שהוגדרו להפנות אוטומטית אל http://localhost:8000 לאחר האימות:

php -S localhost:8000 -t ./

  1. מורידים ומתקינים את לקוח ה-PHP של Google API.

    השיטה המועדפת היא באמצעות Composer:

    composer require google/apiclient:^2.12.1
    

    לאחר ההתקנה, חשוב לכלול את הטוען האוטומטי

    require_once '/path/to/your-project/vendor/autoload.php';
    

  2. יוצרים אובייקט Google_Client.

    $client = new Google_Client();
    
  3. מגדירים את הלקוח, מפנים לכתובת URL לאימות במקרה הצורך ומאחזרים אסימון גישה.

    בפעם הראשונה שתבצעו את השלב הזה, תתבקשו לאשר את הודעת ההרשאה בדפדפן. לפני שתאשרו, ודאו שנכנסתם באמצעות חשבון Google עם גישה ל-Display & Video 360. לאפליקציה שלכם תהיה הרשאה לגשת לנתונים מטעם החשבון שמחובר כרגע.

    // Set up the client.
    $client->setApplicationName('DBM API PHP Samples');
    $client->addScope(oauth-scope);
    $client->setAccessType('offline');
    $client->setAuthConfigFile(path-to-client-secrets-file);
    
    // If the code is passed, authenticate. If not, redirect to authentication page.
    if (isset($_GET['code'])) {
      $client->authenticate($_GET['code']);
    } else {
      $authUrl = $client->createAuthUrl();
      header('Location: ' . $authUrl);
    }
    
    // Exchange authorization code for an access token.
    $accessToken = $client->getAccessToken();
    $client->setAccessToken($accessToken);
    
  4. הגדרת לקוח לשירות Display & Video 360 API.

    $service = new Google_Service_DoubleClickBidManager($client);
    
  5. מבצעים פעולה.

    // Configure params for the Queries.listqueries request.
    $optParams = array('pageSize' => 10);
    
    // Execute the request.
    $result = $service->queries->listQueries($optParams);
    
    // Print the retrieved queries.
    if (!empty($result->getQueries())) {
      print('<pre><p>Id Name</p>');
      foreach ($result->getQueries() as $query) {
        printf('<p>%s %s</p>', $query->queryId, $query->metadata->title);
      }
      print('</pre>');
    } else {
      print '<p>No queries exist.</p>';
    }
    

למידע מפורט יותר על השימוש ב-Bid Manager API עם PHP, תוכלו לקרוא את הקובץ README שבדוגמאות ל-Bid Manager API.

4. השלבים הבאים

עכשיו, אחרי שיצרתם ספריית לקוח, תוכלו לעיין במסמכי התיעוד ולהתחיל לפתח את ההטמעה.

אפשר למצוא גם מדריכים נוספים בנושא שימוש בדוחות מתוזמנים ושיטות מומלצות לדיווח.