仕組み

はじめに

デバイスの販売店は、ゼロトラスト登録 API を使用して統合を自動化できます。 組織の販売ツールはゼロタッチ登録で構築でき、ユーザーと顧客の生産性を向上させることができます。API を使用してユーザーをサポート:

  • 購入したデバイスをお客様のゼロタッチ登録アカウントに割り当てる
  • お客様のゼロタッチ登録アカウントを作成する。
  • 組織の電話と注文のメタデータをデバイスに追加します。
  • お客様に割り当てられたデバイスに関するレポートを作成する。

このドキュメントでは、API を紹介し、パターンについて説明します。API を使ってみる場合は、Java.NETPython のクイックスタートをお試しください。

API のコンセプト

お客様とデバイスは、API で使用するコアリソースです。顧客を作成するには、create を呼び出します。Claim API メソッドを使用してデバイスを作成できます(下記参照)。また、ゼロタッチ登録のポータルを使用してお客様とデバイスを作成することもできます。

デバイスと顧客リソースの関係

お客様
デバイスの販売先である会社。顧客は nameID を持っています。デバイスの申請または確認を行うには、お客様を使用してください。詳細については、Customer をご覧ください。
デバイス
組織が顧客に販売しているゼロタッチ登録対応の Android または ChromeOS デバイス。デバイスには、ハードウェア ID、メタデータ、顧客クレームがあります。デバイスは API の中心となるため、ほぼすべてのメソッドで使用できます。詳しくは、Device をご覧ください。
DeviceIdentifier
IMEI や MEID などのハードウェア ID をカプセル化して、製造されたデバイスを識別します。DeviceIdentifier を使用して、検索、更新、または申請するデバイスをターゲットにします。詳細については、識別子をご覧ください。
DeviceMetadata
デバイスのメタデータの Key-Value ペアを保存します。DeviceMetadata を使用して、組織のメタデータを保存します。詳しくは、デバイス メタデータをご覧ください。

アプリが使用できるすべての API メソッドとリソースの一覧については、API リファレンスをご覧ください。

顧客を作成する

Android デバイスの場合、販売パートナーは、顧客に代わって顧客アカウントを作成する責任を負います。お客様はこのアカウントを使用してゼロタッチ ポータルにアクセスし、デバイスのプロビジョニング設定を行います。これは、プロビジョニング設定に使用する Google Workspace アカウントをすでに持っている ChromeOS デバイスでは必要ありません。

create API メソッドを呼び出して、ゼロタッチ登録用の顧客アカウントを作成できます。顧客のゼロタッチ登録ポータルに会社名が表示されるため、アプリのユーザーに会社名が正しいことを確認する必要があります。顧客を作成した後で顧客名を編集することはできません。

所有者となるには、Google アカウントに関連付けられている会社のメールアドレスを 1 つ以上含める必要があります。API で個人用 Gmail アカウントを使用することはできません。お客様がアカウントの関連付けについてサポートを必要としている場合は、Google アカウントの関連付けの手順を送信します。

API を呼び出して顧客を作成すると、その顧客は従業員のポータル アクセス権を管理します。API を使用して顧客のユーザーを編集することはできません。以下のスニペットは、顧客を作成する方法を示しています。

Java

// Provide the customer data as a Company type.
// The API requires a name and owners.
Company customer = new Company();
customer.setCompanyName("XYZ Corp");
customer.setOwnerEmails(Arrays.asList("liz@example.com", "darcy@example.com"));
customer.setAdminEmails(Collections.singletonList("jane@example.com"));

// Use our reseller ID for the parent resource name.
String parentResource = String.format("partners/%d", PARTNER_ID);

// Call the API to create the customer using the values in the company object.
CreateCustomerRequest body = new CreateCustomerRequest();
body.setCustomer(customer);
Company response = service.partners().customers().create(parentResource, body).execute();

.NET

// Provide the customer data as a Company type.
// The API requires a name and owners.
var customer = new Company
{
    CompanyName = "XYZ Corp",
    OwnerEmails = new String[] { "liz@example.com", "darcy@example.com" },
    AdminEmails = new String[] { "jane@example.com" }
};

// Use our reseller ID for the parent resource name.
var parentResource = String.Format("partners/{0}", PartnerId);

// Call the API to create the customer using the values in the company object.
var body = new CreateCustomerRequest
{
    Customer = customer
};
var request = service.Partners.Customers.Create(body, parentResource);
var response = request.Execute();

Python

# Provide the customer data as a Company type. The API requires
# a name and at least one owner.
company = {'companyName':'XYZ Corp', \
  'ownerEmails':['liz@example.com', 'darcy@example.com'], \
  'adminEmails':['jane@example.com']}

# Use our reseller ID for the parent resource name.
parent_resource = 'partners/{0}'.format(PARTNER_ID)

# Call the API to create the customer using the values in the company object.
response = service.partners().customers().create(parent=parent_resource,
    body={'customer':company}).execute()

顧客の従業員のオーナーと管理者の役割の詳細については、ポータル ユーザーをご覧ください。

お客様に代わってデバイスを請求する

デバイスを購入した顧客は、アカウントでデバイスのプロビジョニング設定を構成する必要があります。デバイスを申請すると、そのデバイスがゼロタッチ登録に追加され、お客様がプロビジョニングを設定できるようになります。

デバイスのプロビジョニング レコードには、ゼロタッチ登録用のセクションがあります。デバイスを割り当てるには、お客様のレコードのゼロタッチ登録セクションを申請します。顧客を引数として partners.devices.claim メソッドまたは partners.devices.claimAsync メソッドを呼び出します。sectionType の値として常に SECTION_TYPE_ZERO_TOUCH を指定します。

別のお客様の同じデバイスの申請を行う前に、お客様のデバイスの申請を取り消す必要があります(下記を参照)。この申請メソッドは、新しいデバイスの作成時に、DeviceIdentifier フィールド(IMEI または MEID、または ChromeOS デバイスのシリアル番号、メーカー名とモデル、証明済みのデバイス ID)をvalidateします。

以下のスニペットは、デバイスの申請方法を示したものです。

Java

// Identify the device to claim.
DeviceIdentifier identifier = new DeviceIdentifier();
// The manufacturer value is optional but recommended for cellular devices
identifier.setManufacturer("Google");
identifier.setImei("098765432109875");

// Create the body to connect the customer with the device.
ClaimDeviceRequest body = new ClaimDeviceRequest();
body.setDeviceIdentifier(identifier);
body.setCustomerId(customerId);
body.setSectionType("SECTION_TYPE_ZERO_TOUCH");

// Claim the device.
ClaimDeviceResponse response = service.partners().devices().claim(PARTNER_ID, body).execute();

.NET

// Identify the device to claim.
var deviceIdentifier = new DeviceIdentifier
{
    // The manufacturer value is optional but recommended for cellular devices
    Manufacturer = "Google",
    Imei = "098765432109875"
};

// Create the body to connect the customer with the device.
ClaimDeviceRequest body = new ClaimDeviceRequest
{
    DeviceIdentifier = deviceIdentifier,
    CustomerId = CustomerId,
    SectionType = "SECTION_TYPE_ZERO_TOUCH"
};

// Claim the device.
var response = service.Partners.Devices.Claim(body, PartnerId).Execute();

Python

# Identify the device to claim.
# The manufacturer value is optional but recommended for cellular devices
device_identifier = {'manufacturer':'Google', 'imei':'098765432109875'}

# Create the body to connect the customer with the device.
request_body = {'deviceIdentifier':device_identifier, \
    'customerId':customer_id, \
    'sectionType':'SECTION_TYPE_ZERO_TOUCH'}

# Claim the device.
response = service.partners().devices().claim(partnerId=PARTNER_ID,
    body=request_body).execute()

デバイスの申請を取り消す

組織は、お客様からデバイスの申請を解除できます。デバイスの申請を解除すると、そのデバイスはゼロタッチ登録から削除されます。販売パートナーは、別のアカウントに移行したいデバイス、返品したいデバイス、誤って申請されたデバイスの申請を取り消すことがあります。メソッド partners.devices.unclaim または partners.devices.unclaimAsync を呼び出して、お客様からのデバイスの申請を解除します。

ベンダー

ベンダーは、ディーラー ネットワークの販売パートナー、グローバル販売パートナー ネットワーク内のローカル オペレーター、お客様の代わりにデバイスを販売する組織の代理として利用できます。ベンダーは、ユーザー、顧客、デバイスを分離するのに役立ちます。

  • 作成したベンダーは、ゼロタッチ登録アカウントや他のベンダーのアカウントを参照することはできません。
  • ベンダーの顧客とデバイスの確認と、ベンダーのデバイスの登録解除ができます。ただし、ベンダーの顧客にデバイスを割り当てることはできません。

ポータルを使用して、組織のベンダーを作成します。API は使用できません。新しいベンダーを作成するには、アカウントのロールがオーナーである必要があります。組織にベンダーがある場合、partners.vendors.list を呼び出してベンダーを一覧表示し、partners.vendors.customers.list を呼び出してベンダーの顧客を取得できます。次の例では、両方のメソッドを使用して、ベンダーの顧客向けの利用規約のステータスを示すレポートを出力します。

Java

// First, get the organization's vendors.
String parentResource = String.format("partners/%d", PARTNER_ID);
ListVendorsResponse results = service.partners().vendors().list(parentResource).execute();
if (results.getVendors() == null) {
  return;
}

// For each vendor, report the company name and a maximum 5 customers.
for (Company vendor: results.getVendors()) {
  System.out.format("\n%s customers\n", vendor.getCompanyName());
  System.out.println("---");
  // Use the vendor's API resource name as the parent resource.
  AndroidProvisioningPartner.Partners.Vendors.Customers.List customerRequest =
      service.partners().vendors().customers().list(vendor.getName());
  customerRequest.setPageSize(5);
  ListVendorCustomersResponse customerResponse = customerRequest.execute();

  List<Company> customers = customerResponse.getCustomers();
  if (customers == null) {
    System.out.println("No customers");
    break;
  } else {
    for (Company customer: customers) {
      System.out.format("%s: %s\n",
          customer.getCompanyName(),
          customer.getTermsStatus());
    }
  }
}

.NET

// First, get the organization's vendors.
var parentResource = String.Format("partners/{0}", PartnerId);
var results = service.Partners.Vendors.List(parentResource).Execute();
if (results.Vendors == null)
{
    return;
}

// For each vendor, report the company name and a maximum 5 customers.
foreach (Company vendor in results.Vendors)
{
    Console.WriteLine("\n{0} customers", vendor);
    Console.WriteLine("---");
    // Use the vendor's API resource name as the parent resource.
    PartnersResource.VendorsResource.CustomersResource.ListRequest customerRequest =
        service.Partners.Vendors.Customers.List(vendor.Name);
    customerRequest.PageSize = 5;
    var customerResponse = customerRequest.Execute();

    IList<Company> customers = customerResponse.Customers;
    if (customers == null)
    {
        Console.WriteLine("No customers");
        break;
    }
    else
    {
        foreach (Company customer in customers)
        {
            Console.WriteLine("{0}: {1}", customer.Name, customer.TermsStatus);
        }
    }
}

Python

# First, get the organization's vendors.
parent_resource = 'partners/{0}'.format(PARTNER_ID)
vendor_response = service.partners().vendors().list(
    parent=parent_resource).execute()
if 'vendors' not in vendor_response:
  return

# For each vendor, report the company name and a maximum 5 customers.
for vendor in vendor_response['vendors']:
  print '\n{0} customers'.format(vendor['companyName'])
  print '---'
  # Use the vendor's API resource name as the parent resource.
  customer_response = service.partners().vendors().customers().list(
      parent=vendor['name'], pageSize=5).execute()
  if 'customers' not in customer_response:
    print 'No customers'
    break
  for customer in customer_response['customers']:
    print '  {0}: {1}'.format(customer['name'], customer['termsStatus'])

デバイスのコレクションがある場合、どの販売パートナーまたはベンダーがデバイスを要求しているかを特定する必要があります。数値の販売パートナー ID を取得するには、デバイスのクレーム レコードの resellerId フィールドの値を調べます。

組織は、ベンダーによって申請されているデバイスの申請を解除できます。デバイスを変更するその他の API 呼び出しの場合は、API メソッドを呼び出す前に、組織がデバイスを要求していることを確認する必要があります。次の例はその方法を示しています。

Java

// Get the devices claimed for two customers: one of our organization's
// customers and one of our vendor's customers.
FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest();
body.setSectionType("SECTION_TYPE_ZERO_TOUCH");
body.setCustomerId(Arrays.asList(resellerCustomerId, vendorCustomerId));
body.setLimit(MAX_PAGE_SIZE);
FindDevicesByOwnerResponse response =
    service.partners().devices().findByOwner(PARTNER_ID, body).execute();
if (response.getDevices() == null) {
  return;
}

for (Device device: response.getDevices()) {
  // Confirm the device was claimed by our reseller and not a vendor before
  // updating metadata in another method.
  for (DeviceClaim claim: device.getClaims()) {
    if (claim.getResellerId() == PARTNER_ID) {
      updateDeviceMetadata(device.getDeviceId());
      break;
    }
  }
}

.NET

// Get the devices claimed for two customers: one of our organization's
// customers and one of our vendor's customers.
FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest
{
    Limit = MaxPageSize,
    SectionType = "SECTION_TYPE_ZERO_TOUCH",
    CustomerId = new List<long?>
    {
        resellerCustomerId,
        vendorCustomerId
    }
};
var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute();
if (response.Devices == null)
{
    return;
}

foreach (Device device in response.Devices)
{
    // Confirm the device was claimed by our reseller and not a vendor before
    // updating metadata in another method.
    foreach (DeviceClaim claim in device.Claims)
    {
        if (claim.ResellerId == PartnerId)
        {
            UpdateDeviceMetadata(device.DeviceId);
            break;
        }
    }
}

Python

# Get the devices claimed for two customers: one of our organization's
# customers and one of our vendor's customers.
request_body = {'limit':MAX_PAGE_SIZE, \
  'pageToken':None, \
  'customerId':[reseller_customer_id, vendor_customer_id], \
  'sectionType':'SECTION_TYPE_ZERO_TOUCH'}
response = service.partners().devices().findByOwner(partnerId=PARTNER_ID,
    body=request_body).execute()

for device in response['devices']:
  # Confirm the device was claimed by our reseller and not a vendor before
  # updating metadata in another method.
  for claim in device['claims']:
    if claim['resellerId'] == PARTNER_ID:
      update_device_metadata(device['deviceId'])
      break

長時間実行のバッチ オペレーション

API には、デバイス メソッドの非同期バージョンが含まれています。これらのメソッドでは多数のデバイスをバッチ処理できる一方、同期メソッドでは API リクエストごとに 1 台のデバイスを処理します。非同期メソッド名には、claimAsync などの Async という接尾辞が付いています。

非同期 API メソッドは、処理が完了する前に結果を返します。また、非同期メソッドは、ユーザーが長時間実行オペレーションの完了を待つ間、アプリ(またはツール)の応答性を維持するのに役立ちます。アプリは、オペレーションのステータスを定期的に確認する必要があります。

運用

Operation を使用して、長時間実行のバッチ オペレーションを追跡します。非同期メソッドの呼び出しが成功すると、レスポンスでオペレーションへの参照が返されます。次の JSON スニペットは、updateMetadataAsync を呼び出した後の一般的なレスポンスを示しています。

{
  "name": "operations/apibatchoperation/1234567890123476789"
}

各オペレーションには個別のタスクのリストが含まれます。operations.get を呼び出して、オペレーションに含まれるタスクのステータスと結果に関する情報を確認します。以下のスニペットは、これを行う方法を示しています。実際のアプリでは、すべてのエラーを処理する必要があります。

Java

// Build out the request body to apply the same order number to a customer's
// purchase of 2 devices.
UpdateMetadataArguments firstUpdate = new UpdateMetadataArguments();
firstUpdate.setDeviceMetadata(metadata);
firstUpdate.setDeviceId(firstTargetDeviceId);

UpdateMetadataArguments secondUpdate = new UpdateMetadataArguments();
secondUpdate.setDeviceMetadata(metadata);
secondUpdate.setDeviceId(firstTargetDeviceId);

// Start the device metadata update.
UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest();
body.setUpdates(Arrays.asList(firstUpdate, secondUpdate));
Operation response = service
    .partners()
    .devices()
    .updateMetadataAsync(PARTNER_ID, body)
    .execute();

// Assume the metadata update started, so get the Operation for the update.
Operation operation = service.operations().get(response.getName()).execute();

.NET

// Build out the request body to apply the same order number to a customer's
// purchase of 2 devices.
var updates = new List<UpdateMetadataArguments>
{
    new UpdateMetadataArguments
    {
        DeviceMetadata = metadata,
        DeviceId = firstTargetDeviceId
    },
    new UpdateMetadataArguments
    {
        DeviceMetadata = metadata,
        DeviceId = secondTargetDeviceId
    }
};

// Start the device metadata update.
UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest
{
    Updates = updates
};
var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute();

// Assume the metadata update started, so get the Operation for the update.
Operation operation = service.Operations.Get(response.Name).Execute();

Python

# Build out the request body to apply the same order number to a customer's
# purchase of 2 devices.
updates = [{'deviceMetadata':metadata,'deviceId':first_target_device_id},
    {'deviceMetadata':metadata,'deviceId':second_target_device_id}]

# Start the device metadata update.
response = service.partners().devices().updateMetadataAsync(
    partnerId=PARTNER_ID, body={'updates':updates}).execute()

# Assume the metadata update started, so get the Operation for the update.
operation = service.operations().get(name=response['name']).execute()

オペレーションが完了したかどうかを確認するには、オペレーションで値が truedone フィールドを確認します。done が存在しないか false の場合、オペレーションはまだ実行中です。

レスポンス

オペレーションが完了すると、API は結果でオペレーションを更新します。個々のタスクがすべて成功した場合も、まったく成功した場合も、失敗した場合もあります。response フィールドは DevicesLongRunningOperationResponse オブジェクトで、操作における各デバイスの処理の詳細を示します。

successCount フィールドを調べて、タスクの失敗を効率的に特定し、大規模な結果リストの反復処理を回避します。DevicesLongRunningOperationResponseperDeviceStatus フィールドは OperationPerDevice インスタンスのリストで、操作中の各デバイスの詳細を示します。リストの順序は、元のリクエストのタスクと一致します。

OperationPerDevice タスクには、result フィールドと、サーバーが受信したリクエストのリマインダー サマリーが含まれます。result フィールドを使用して、タスクが成功したか失敗したかを確認します。

以下の JSON スニペットは、updateMetadataAsync を呼び出した後のオペレーションからの一般的なレスポンスの一部を示しています。

"response": {
  "perDeviceStatus": [
    {
      "result": {
        "deviceId": "12345678901234567",
        "status": "SINGLE_DEVICE_STATUS_SUCCESS"
      },
      "updateMetadata": {
        "deviceId": "12345678901234567",
        "deviceMetadata": {
          "entries": {
            "phonenumber": "+1 (800) 555-0100"
          }
        }
      }
    }
  ],
  "successCount": 1
}

進捗状況を管理する

アプリで進行状況を追跡する必要がある場合は、オペレーションを定期的に再取得する必要があります。metadata フィールドには DevicesLongRunningOperationMetadata インスタンスが含まれ、アプリはこれを使用して、実行中のオペレーションの最新の進行状況を確認できます。次の表に示す DevicesLongRunningOperationMetadata のフィールドを使用して、オペレーションの進行状況を追跡します。

項目 一般的な使用方法
processingStatus BATCH_PROCESS_PENDING から BATCH_PROCESS_IN_PROGRESS に変更し、オペレーションの進行に合わせて BATCH_PROCESS_PROCESSED に変更します。
progress 処理された更新の割合。アプリはこの情報を使用して、終了時間を推定できます。オペレーションの終了中に progress 値が 100 になる可能性があるため、オペレーションの done フィールドをチェックして、オペレーションが完了して結果があるかどうかを確認します。
devicesCount オペレーションでの更新の数を示します。API が一部の更新を解析できない場合、これはリクエストの更新回数とは異なる場合があります。

以下の簡単な例は、アプリが進行状況メタデータを使用してポーリング間隔を設定する方法を示しています。アプリでは、ポーリングのためにより高度なタスクランナーが必要になる場合があります。エラー処理も追加する必要があります。

Java

// Milliseconds between polling the API.
private static long MIN_INTERVAL = 2000;
private static long MAX_INTERVAL = 10000;

// ...
// Start the device metadata update.
Operation response = service
    .partners()
    .devices()
    .updateMetadataAsync(PARTNER_ID, body)
    .execute();
String operationName = response.getName();

// Start polling for completion.
long startTime = new Date().getTime();
while (true) {

  // Get the latest update on the operation's progress using the API.
  Operation operation = service.operations().get(operationName).execute();

  if (operation.get("done") != null && operation.getDone()) {
    // The operation is finished. Print the status.
    System.out.format("Operation complete: %s of %s successful device updates\n",
        operation.getResponse().get("successCount"),
        operation.getMetadata().get("devicesCount"));
    break;

  } else {
    // Estimate how long the operation *should* take - within min and max value.
    BigDecimal opProgress = (BigDecimal) operation.getMetadata().get("progress");
    double progress = opProgress.longValue();
    long interval = MAX_INTERVAL;
    if (progress > 0) {
      interval = (long) ((new Date().getTime() - startTime) *
          ((100.0 - progress) / progress));
    }
    interval = Math.max(MIN_INTERVAL, Math.min(interval, MAX_INTERVAL));

    // Sleep until the operation should be complete.
    Thread.sleep(interval);
  }
}

.NET

// Milliseconds between polling the API.
private static double MinInterval = 2000;
private static double MaxInterval = 10000;

// ...
// Start the device metadata update.
var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute();
var operationName = response.Name;

// Start polling for completion.
var startTime = DateTime.Now;
while (true)
{

    // Get the latest update on the operation's progress using the API.
    Operation operation = service.Operations.Get(operationName).Execute();

    if (operation.Done == true)
    {
        // The operation is finished. Print the status.
        Console.WriteLine("Operation complete: {0} of {1} successful device updates",
                          operation.Response["successCount"],
                          operation.Metadata["devicesCount"]);
        break;
    }
    else
    {
        // Estimate how long the operation *should* take - within min and max value.
        double progress = (double)(long)operation.Metadata["progress"];
        double interval = MaxInterval;
        if (progress > 0)
        {
            interval = DateTime.Now.Subtract(startTime).TotalMilliseconds *
                                     ((100.0 - progress) / progress);
        }
        interval = Math.Max(MinInterval, Math.Min(interval, MaxInterval));

        // Sleep until the operation should be complete.
        System.Threading.Thread.Sleep((int)interval);
    }
}

Python

# Seconds between polling the API.
MIN_INTERVAL = 2;
MAX_INTERVAL = 10;

# ...
# Start the device metadata update
response = service.partners().devices().updateMetadataAsync(
  partnerId=PARTNER_ID, body={'updates':updates}).execute()

op_name = response['name']
start_time = time.time()

# Start polling for completion
while True:
  # Get the latest update on the operation's progress using the API
  op = service.operations().get(name=op_name).execute()

  if 'done' in op and op['done']:
    # The operation is finished. Print the status.
    print('Operation complete: {0} of {1} successful device updates'.format(
      op['response']['successCount'], op['metadata']['devicesCount']
    ))
    break
  else:
    # Estimate how long the operation *should* take - within min and max.
    progress = op['metadata']['progress']
    interval = MIN_INTERVAL
    if progress > 0:
      interval = (time.time() - start_time) * ((100.0 - progress) / progress)
    interval = max(MIN_INTERVAL, min(interval, MAX_INTERVAL))

    # Sleep until the operation should be complete.
    time.sleep(interval)

アプリのユーザーに適したポーリング アプローチを選択してください。一部のアプリユーザーは、プロセスの完了を待っている場合に、進行状況を定期的に更新すると便利です。

ページングされた結果

partners.devices.findByOwner API メソッドは非常に大規模なデバイスリストを返す場合があります。レスポンス サイズを削減するために、このメソッドと他の API メソッド(partners.devices.findByIdentifier など)はページングされた結果をサポートしています。結果のページングを使用すると、アプリは大規模なリストを 1 ページずつ反復的にリクエストして処理できます。

API メソッドを呼び出した後、レスポンスに nextPageToken の値が含まれているかどうかを確認します。nextPageTokennull でない場合、アプリはこのメソッドを再度呼び出し、それを使用してデバイスの別のページをフェッチできます。limit パラメータでデバイス数の上限を設定する必要があります。nextPageTokennull の場合、アプリは最後のページをリクエストしています。

以下のメソッドの例は、アプリがデバイスのリストを 1 ページずつ出力する方法を示しています。

Java

private static long MAX_PAGE_SIZE = 10;

// ...
/**
 * Demonstrates how to loop through paginated lists of devices.
 * @param pageToken       The token specifying which result page to return.
 * @throws IOException    If the zero-touch API call fails.
 */
private void printDevices(String pageToken) throws IOException {

  // Create the request body to find the customer's devices.
  FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest();
  body.setLimit(MAX_PAGE_SIZE);
  body.setSectionType("SECTION_TYPE_ZERO_TOUCH");
  body.setCustomerId(Collections.singletonList(targetCustomerId));

  // Call the API to get a page of Devices. Send a page token from the method
  // argument (might be None). If the page token is None, the API returns the first page.
  FindDevicesByOwnerResponse response =
      service.partners().devices().findByOwner(PARTNER_ID, body).execute();
  if (response.getDevices() == null) {
    return;
  }

  // Print the devices included in this page of results.
  for (Device device: response.getDevices()) {
    System.out.format("Device %s\n", device.getName());
  }
  System.out.println("---");

  // Check to see if another page of devices is available. If yes,
  // fetch and print the devices.
  if (response.getNextPageToken() != null) {
    this.printDevices(response.getNextPageToken());
  }
}

// ...
// Pass null to start printing the first page of devices.
printDevices(null);

.NET

private static int MaxPageSize = 10;

// ...
/// <summary>Demonstrates how to loop through paginated lists of devices.</summary>
/// <param name="pageToken">The token specifying which result page to return.</param>
private void PrintDevices(string pageToken)
{
    // Create the request body to find the customer's devices.
    FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest
    {
        PageToken = pageToken,
        Limit = MaxPageSize,
        SectionType = "SECTION_TYPE_ZERO_TOUCH",
        CustomerId = new List<long?>
        {
            targetCustomerId
        }
    };

    // Call the API to get a page of Devices. Send a page token from the method
    // argument (might be None). If the page token is None, the API returns the first page.
    var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute();
    if (response.Devices == null)
    {
        return;
    }

    // Print the devices included in this page of results.
    foreach (Device device in response.Devices)
    {
        Console.WriteLine("Device: {0}", device.Name);
    }
    Console.WriteLine("---");

    // Check to see if another page of devices is available. If yes,
    // fetch and print the devices.
    if (response.NextPageToken != null)
    {
        this.PrintDevices(response.NextPageToken);
    }
}

// ...
// Pass null to start printing the first page of devices.
PrintDevices(null);

Python

MAX_PAGE_SIZE = 10;

# ...
def print_devices(page_token):
  """Demonstrates how to loop through paginated lists of devices.

  Args:
    page_token: The token specifying which result page to return.
  """

   # Create the body to find the customer's devices.
  request_body = {'limit':MAX_PAGE_SIZE, \
    'pageToken':page_token, \
    'customerId':[target_customer_id], \
    'sectionType':'SECTION_TYPE_ZERO_TOUCH'}

  # Call the API to get a page of Devices. Send a page token from the method
  # argument (might be None). If the page token is None,
  # the API returns the first page.
  response = service.partners().devices().findByOwner(partnerId=PARTNER_ID,
    body=request_body).execute()

  # Print the devices included in this page of results.
  for device in response['devices']:
    print 'Device: {0}'.format(device['name'])
  print '---'

  # Check to see if another page of devices is available. If yes,
  # fetch and print the devices.
  if 'nextPageToken' in response:
    print_devices(response['nextPageToken'])

# ...
# Pass None to start printing the first page of devices.
print_devices(None);

次のステップ

API の仕組みを理解したところで、Java.NETPython のクイックスタートを使用してサンプルを試してみましょう。