클라이언트 구성

OAuth 2.0 사용자 인증 정보가 생성되고 클라이언트 라이브러리가 설치되면 Display & Video 360 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.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. 클라이언트 보안 비밀 파일을 로드하고 승인 사용자 인증 정보를 생성합니다.

    이 단계를 처음 수행할 때 브라우저에서 승인 메시지를 수락하라는 메시지가 표시됩니다. 수락하기 전에 Display & Video 360에 액세스할 수 있는 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.
    DisplayVideo service =
        new DisplayVideo.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("displayvideo-java-installed-app-sample")
            .build();
    
  4. 작업을 수행합니다.

    // 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. 필요한 라이브러리를 가져옵니다.

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient import discovery
    
  2. 클라이언트 보안 비밀 파일을 로드하고 승인 사용자 인증 정보를 생성합니다.

    이 단계를 처음 수행할 때 브라우저에서 승인 메시지를 수락하라는 메시지가 표시됩니다. 수락하기 전에 Display & Video 360에 액세스할 수 있는 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://displayvideo.googleapis.com/$discovery/rest?version=v3'
    
    # Build the API service.
    service = discovery.build(
        'displayvideo',
        'v3',
        discoveryServiceUrl=discovery_url,
        credentials=credentials)
    
  4. 작업을 수행합니다.

    # 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.')
    

2,399필리핀

이 샘플에서는 내장 웹 서버를 사용하여 PHP를 실행하고 관련 웹페이지로 리디렉션되도록 사용자 인증 정보를 구성했다고 가정합니다. 예를 들어 index.php 파일의 이 코드는 인증 후 http://localhost:8000로 리디렉션되도록 구성된 다음 명령어와 사용자 인증 정보를 사용하여 실행할 수 있습니다.

php -S localhost:8000 -t ./

  1. Google API PHP 클라이언트를 다운로드하고 설치합니다.

    선호되는 방법은 Composer를 사용하는 것입니다.

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

    설치가 완료되면 자동 로더를 포함해야 합니다.

    require_once '/path/to/your-project/vendor/autoload.php';
    
  2. Google_Client 객체를 만듭니다.

    $client = new Google_Client();
    
  3. 클라이언트를 설정하고, 필요한 경우 인증 URL로 리디렉션하고, 액세스 토큰을 가져옵니다.

    이 단계를 처음 수행할 때 브라우저에서 승인 메시지를 수락하라는 메시지가 표시됩니다. 수락하기 전에 Display & Video 360에 액세스할 수 있는 Google 계정으로 로그인해야 합니다. 앱이 현재 로그인한 계정을 대신하여 데이터에 액세스하도록 승인됩니다. Display & 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. Display & Video 360 API 서비스의 클라이언트를 구성합니다.

    $service = new Google_Service_DisplayVideo($client);
    
  5. 작업을 수행합니다.

    // 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>';
    }