Configurer votre client

Avec des identifiants OAuth 2.0 créés et une bibliothèque cliente , vous pouvez commencer à utiliser l'écran l'API Video 360. Découvrez comment autoriser, configurer votre client et effectuer votre première demande en en suivant le guide de démarrage rapide ci-dessous.

Java

  1. Importez les bibliothèques nécessaires.

    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.displayvideo.v3.DisplayVideo;
    import com.google.api.services.displayvideo.v3.DisplayVideo.Advertisers;
    import com.google.api.services.displayvideo.v3.model.Advertiser;
    import com.google.api.services.displayvideo.v3.model.ListAdvertisersResponse;
    import java.io.Reader;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
  2. Chargez le fichier de codes secrets du client et générez des identifiants d'autorisation.

    La première fois que vous effectuez cette étape, vous êtes invité à accepter une autorisation dans votre navigateur. Avant d'accepter, vérifiez que vous êtes connecté avec un Compte Google ayant accès à Display & Video 360. Votre application sera autorisée pour accéder aux données au nom du compte actuellement connecté. Consultez nos Autoriser Guide sur les demandes pour en savoir plus sur les campagnes display Autorisations de l'utilisateur de 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. Créez un client API autorisé.

    // Create authorized API client.
    DisplayVideo service =
        new DisplayVideo.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("displayvideo-java-installed-app-sample")
            .build();
    
  4. Effectuez une opération.

    // Perform an operation.
    // Retrieve and print the first ten advertisers under a partner.
    ListAdvertisersResponse response =
        service
            .advertisers()
            .list()
            .setPartnerId(partner-id)
            .setPageSize(10)
            .execute();
    if (response.getAdvertisers().size() > 0) {
      for (int i = 0; i < response.getAdvertisers().size(); i++) {
        System.out.printf(
            "ID: %s Display Name: %s%n",
            response.getAdvertisers().get(i).getAdvertiserId(),
            response.getAdvertisers().get(i).getDisplayName());
      }
    } else {
      System.out.print("No advertisers found.");
    }
    

Python

  1. Importez les bibliothèques nécessaires.

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient import discovery
    
  2. Chargez le fichier de codes secrets du client et générez des identifiants d'autorisation.

    La première fois que vous effectuez cette étape, vous êtes invité à accepter une autorisation dans votre navigateur. Avant d'accepter, vérifiez que vous êtes connecté avec un Compte Google ayant accès à Display & Video 360. Votre application sera autorisée pour accéder aux données au nom du compte actuellement connecté. Consultez nos Autoriser Guide sur les demandes pour en savoir plus sur les campagnes display Autorisations de l'utilisateur de 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. Créez un client API autorisé.

    # Build the discovery document URL.
    discovery_url = f'https://displayvideo.googleapis.com/$discovery/rest?version=v3'
    
    # Build the API service.
    service = discovery.build(
        'displayvideo',
        'v3',
        discoveryServiceUrl=discovery_url,
        credentials=credentials)
    
  4. Effectuez une opération.

    # Build advertisers.list request.
    request = service.advertisers().list(
        partnerId=partner-id, pageSize='10')
    
    # Execute request.
    response = request.execute()
    
    # Print response.
    if len(response['advertisers']) > 0:
      for advertiser in response['advertisers']:
        print(f'ID: {advertiser["advertiserId"]} Display Name: {advertiser["displayName"]}')
    else:
      print('No advertisers found.')
    

PHP

Cet exemple suppose que vous exécutez PHP avec un serveur Web intégré et avez configuré vos identifiants pour vous rediriger vers la page Web appropriée. Pour Dans cet exemple, ce code dans un fichier index.php peut être exécuté à l'aide du code suivant : et les identifiants configurés pour rediriger vers http://localhost:8000 après authentification:

php -S localhost:8000 -t ./

  1. Téléchargez et installez le client PHP Google API.

    La méthode privilégiée consiste à utiliser Composer:

    composer require google/apiclient:^2.15.1 google/apiclient-services:=0.332.0
    

    Une fois l'installation effectuée, n'oubliez pas d'inclure le chargeur automatique:

    require_once '/path/to/your-project/vendor/autoload.php';
    
  2. Créez un objet Google_Client.

    $client = new Google_Client();
    
  3. Configurez le client, redirigez vers l'URL d'authentification si nécessaire et récupérez un jeton d'accès.

    La première fois que vous effectuez cette étape, vous êtes invité à accepter une autorisation dans votre navigateur. Avant d'accepter, vérifiez que vous êtes connecté avec un Compte Google ayant accès à Display & Video 360. Votre application sera autorisée pour accéder aux données au nom du compte actuellement connecté. Consultez nos Autoriser Guide sur les demandes pour en savoir plus sur les campagnes display Autorisations de l'utilisateur de Video 360.

    // Set up the client.
    $client->setApplicationName('DV360 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. Créer un client pour le réseau Display & Service d'API Video 360

    $service = new Google_Service_DisplayVideo($client);
    
  5. Effectuez une opération.

    // Configure params for the advertisers.list request.
    $optParams = array('pageSize' => 10, 'partnerId' => partner-id);
    
    // Execute the request.
    $result = $service->advertisers->listAdvertisers($optParams);
    
    // Print the retrieved advertisers.
    if (!empty($result->getAdvertisers())) {
      print('<pre>');
      foreach ($result->getAdvertisers() as $advertiser) {
        printf('<p>ID: %s, Display Name: %s</p>', $advertiser->advertiserId, $advertiser->displayName);
      }
      print('</pre>');
    } else {
      print '<p>No advertisers found.</p>';
    }