リクエスト元による支払いを使用する

概要

このページでは、リクエスト元による支払い機能の設定方法について説明します。また、リクエスト元による支払い機能を有効にしたバケットにリクエストを送信する例についても説明します。

リクエスト元による支払いを設定する

以降のセクションでは、リクエスト元による支払いをオンまたはオフにする方法と、バケットでリクエスト元による支払いが有効かどうかを確認する方法について説明します。

前提条件

  1. バケットのリクエスト元による支払いのステータスを確認するには storage.buckets.get 権限が必要です。また、Google Cloud コンソールまたは Google Cloud CLI でリクエスト元による支払いを有効または無効にする場合にも必要です。

  2. リクエスト元による支払いを有効または無効にするには storage.buckets.update 権限が必要です。

  3. リクエスト元による支払いを無効にする場合は、リクエストに請求先プロジェクトを含めるか resourcemanager.projects.createBillingAssignment 権限を持つ必要があります。詳細については、リクエスト元による支払いの使用条件とアクセス要件をご覧ください。

権限は、ロールによってユーザーに付与されます。たとえば、ストレージ管理者ロールには、上記のすべての storage.buckets 権限があります。ロールは、バケットを含むプロジェクトに付与できます。

リクエスト元による支払いの設定

バケットでリクエスト元による支払いを有効または無効にするには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、設定するバケットを探し、[リクエスト元による支払い] 列を見つけます。

    この列の値は、そのバケットのリクエスト元による支払いの現在の状態を示します。

  3. 目的のバケットでリクエスト元による支払いの状態をクリックします。

  4. 表示されたウィンドウで、リクエスト元による支払いに設定する状態に応じて、[オンにする] または [オフにする] をクリックします。

有効にすると、バケットの [リクエスト元による支払い] 列に緑色のふきだしと [オン] が表示されます。無効にすると、列に灰色のふきだしと [オフ] が表示されます。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

適切なフラグを指定して、gcloud storage buckets update コマンドを使用します。

gcloud storage buckets update gs://BUCKET_NAME FLAG

ここで

  • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

  • リクエスト元による支払いを有効にする場合 FLAG--requester-pays です。無効にする場合は --no-requester-pays です。

正常に終了すると、レスポンスは次の例のようになります。

Updating gs://my-bucket/...
  Completed 1  

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{true}));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Billing configuration for bucket " << metadata->name()
            << " is updated. The bucket now";
  if (!metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& billed_project) {
  StatusOr<gcs::BucketMetadata> metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{false}),
      gcs::UserProject(billed_project));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Billing configuration for bucket " << bucket_name
            << " is updated. The bucket now";
  if (!metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class EnableRequesterPaysSample
{
    public Bucket EnableRequesterPays(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);
        bucket.Billing ??= new Bucket.BillingData();
        bucket.Billing.RequesterPays = true;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Requester pays requests have been enabled for bucket {bucketName}.");
        return bucket;
    }
}

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class DisableRequesterPaysSample
{
    public Bucket DisableRequesterPays(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions
        {
            UserProject = projectId
        });

        bucket.Billing ??= new Bucket.BillingData();
        bucket.Billing.RequesterPays = false;

        bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions
        {
            UserProject = projectId
        });
        Console.WriteLine($"Requester pays disabled for bucket {bucketName}.");
        return bucket;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// enableRequesterPays sets requester pays flag to true.
func enableRequesterPays(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		RequesterPays: true,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Requester pays enabled for bucket %v\n", bucketName)
	return nil
}

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// disableRequesterPays sets requester pays flag to false.
func disableRequesterPays(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	bucket := client.Bucket(bucketName)
	bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
		RequesterPays: false,
	}
	if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Requester pays disabled for bucket %v\n", bucketName)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class EnableRequesterPays {
  public static void enableRequesterPays(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket.toBuilder().setRequesterPays(true).build().update();

    System.out.println("Requester pays enabled for bucket " + bucketName);
  }
}

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class DisableRequesterPays {
  public static void disableRequesterPays(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName, Storage.BucketGetOption.userProject(projectId));
    bucket
        .toBuilder()
        .setRequesterPays(false)
        .build()
        .update(Storage.BucketTargetOption.userProject(projectId));

    System.out.println("Requester pays disabled for bucket " + bucketName);
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function enableRequesterPays() {
  await storage.bucket(bucketName).enableRequesterPays();

  console.log(
    `Requester-pays requests have been enabled for bucket ${bucketName}`
  );
}

enableRequesterPays().catch(console.error);

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function disableRequesterPays() {
  // Disables requester-pays requests
  await storage.bucket(bucketName).disableRequesterPays();

  console.log(
    `Requester-pays requests have been disabled for bucket ${bucketName}`
  );
}

disableRequesterPays().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function enable_requester_pays(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => true
        ]
    ]);
    printf('Requester pays has been enabled for %s' . PHP_EOL, $bucketName);
}

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。

use Google\Cloud\Storage\StorageClient;

/**
 * Disable a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function disable_requester_pays(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => false
        ]
    ]);
    printf('Requester pays has been disabled for %s' . PHP_EOL, $bucketName);
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

from google.cloud import storage


def enable_requester_pays(bucket_name):
    """Enable a bucket's requesterpays metadata"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = True
    bucket.patch()

    print(f"Requester Pays has been enabled for {bucket_name}")

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。

from google.cloud import storage


def disable_requester_pays(bucket_name):
    """Disable a bucket's requesterpays metadata"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = False
    bucket.patch()

    print(f"Requester Pays has been disabled for {bucket_name}")

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

次のサンプルでは、バケットでリクエスト元による支払いを有効にします。

def enable_requester_pays bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.requester_pays = true

  puts "Requester pays has been enabled for #{bucket_name}"
end

次のサンプルでは、バケットでリクエスト元による支払いを無効にします。

def disable_requester_pays bucket_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name

  bucket.requester_pays = false

  puts "Requester pays has been disabled for #{bucket_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる JSON ファイルを作成します。

    {
      "billing": {
        "requesterPays": STATE
      }
    }

    ここで、STATEtrue または false です。

  3. cURL を使用して JSON API を呼び出し、PATCH Bucket リクエストを行います。

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    ここで

    • JSON_FILE_NAME は、手順 2 で作成した JSON ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンの名前です。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. 次の情報が含まれる XML ファイルを作成します。

    <BillingConfiguration>
      <RequesterPays>STATE</RequesterPays>
    </BillingConfiguration>

    ここで、STATEEnabled または Disabled です。

  3. cURL を使用して、PUT Bucket リクエストと billing クエリ文字列パラメータを含めた XML API を呼び出します。

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    ここで

    • XML_FILE_NAME は、手順 2 で作成した XML ファイルのパスです。
    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンの名前です。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

リクエスト元による支払いが有効かどうかを確認する

バケットでリクエスト元による支払いが有効かどうかを確認するには:

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットリストの [リクエスト元による支払い] 列に、各バケットのリクエスト元による支払いのステータスが表示されます。

有効の場合、ステータスは緑色で、[オン] と表示されます。

コマンドライン

gcloud storage buckets describe コマンドを使用し、--format フラグを指定します。

gcloud storage buckets describe gs://BUCKET_NAME --format="default(requester_pays)"

ここで、BUCKET_NAME はステータスを表示するバケットの名前です。例: my-bucket

正常に終了すると、レスポンスは次の例のようになります。

requester_pays: true

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& user_project) {
  StatusOr<gcs::BucketMetadata> metadata =
      client.GetBucketMetadata(bucket_name, gcs::UserProject(user_project));
  if (!metadata) throw std::move(metadata).status();

  if (!metadata->has_billing()) {
    std::cout
        << "The bucket " << metadata->name() << " does not have a"
        << " billing configuration. The default applies, i.e., the project"
        << " that owns the bucket pays for the requests.\n";
    return;
  }

  if (metadata->billing().requester_pays) {
    std::cout
        << "The bucket " << metadata->name()
        << " is configured to charge the calling project for the requests.\n";
  } else {
    std::cout << "The bucket " << metadata->name()
              << " is configured to charge the project that owns the bucket "
                 "for the requests.\n";
  }
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;

public class GetRequesterPaysStatusSample
{
    public bool GetRequesterPaysStatus(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions
        {
            UserProject = projectId
        });
        bool requesterPays = bucket.Billing?.RequesterPays ?? false;
        Console.WriteLine($"RequesterPays: {requesterPays}");
        return requesterPays;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getRequesterPaysStatus gets requester pays status.
func getRequesterPaysStatus(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	attrs, err := client.Bucket(bucketName).Attrs(ctx)
	if err != nil {
		return fmt.Errorf("Bucket(%q).Attrs: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Is requester pays enabled? %v\n", attrs.RequesterPays)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;

public class GetRequesterPaysStatus {
  public static void getRequesterPaysStatus(String projectId, String bucketName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket =
        storage.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.BILLING));

    System.out.println("Requester pays status : " + bucket.requesterPays());
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getRequesterPaysStatus() {
  // Gets the requester-pays status of a bucket
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  let status;
  if (metadata && metadata.billing && metadata.billing.requesterPays) {
    status = 'enabled';
  } else {
    status = 'disabled';
  }
  console.log(
    `Requester-pays requests are ${status} for bucket ${bucketName}.`
  );
}

getRequesterPaysStatus().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Get a bucket's requesterpays metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 */
function get_requester_pays_status(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $requesterPaysStatus = $bucketInformation['billing']['requesterPays'];
    if ($requesterPaysStatus) {
        printf('Requester Pays is enabled for %s' . PHP_EOL, $bucketName);
    } else {
        printf('Requester Pays is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def get_requester_pays_status(bucket_name):
    """Get a bucket's requester pays metadata"""
    # bucket_name = "my-bucket"
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    requester_pays_status = bucket.requester_pays

    if requester_pays_status:
        print(f"Requester Pays is enabled for {bucket_name}")
    else:
        print(f"Requester Pays is disabled for {bucket_name}")

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して JSON API を呼び出し、GET Bucket リクエストを行います。

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンの名前です。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. cURL を使用して、GET Bucket リクエストと billing クエリ文字列パラメータを含めた XML API を呼び出します。

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンの名前です。
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket

リクエスト元による支払いバケットにアクセスする

次の例では、リクエスト元による支払いバケットに保存したオブジェクトをダウンロードできるように、請求先プロジェクトを追加する方法を説明します。同様の手順で、リクエスト元による支払いバケットやバケット内のオブジェクトに他のリクエストを実行します。前提条件については、リクエスト元による支払いのアクセス要件をご覧ください。

コンソール

  1. Google Cloud コンソールで、Cloud Storage の [バケット] ページに移動します。

    [バケット] に移動

  2. バケットのリストで、ダウンロードするオブジェクトを含むバケットの名前をクリックします。

  3. 表示されたウィンドウで、プルダウン メニューから請求先プロジェクトを選択します。

  4. 選択したプロジェクトを請求先として使用する権限があることを確認するチェックボックスをオンにします。

  5. [保存] をクリックします。

  6. 通常どおりオブジェクトをダウンロードします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Google Cloud コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

リクエストで --billing-project フラグを使用します。

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME SAVE_TO_LOCATION --billing-project=PROJECT_IDENTIFIER

ここで

  • BUCKET_NAME は、ダウンロードするオブジェクトが格納されているバケットの名前です。例: my-bucket
  • OBJECT_NAME は、ダウンロードするオブジェクトの名前です。例: pets/dog.png
  • SAVE_TO_LOCATION は、オブジェクトを保存するローカルパスです。例: Desktop/Images
  • PROJECT_IDENTIFIER は、課金対象のプロジェクトの ID または番号です。例: my-project

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& billed_project) {
  gcs::ObjectReadStream stream = client.ReadObject(
      bucket_name, object_name, gcs::UserProject(billed_project));

  std::string line;
  while (std::getline(stream, line, '\n')) {
    std::cout << line << "\n";
  }
  if (stream.bad()) throw google::cloud::Status(stream.status());
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class DownloadFileRequesterPaysSample
{
    public void DownloadFileRequesterPays(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string localPath = "my-local-path/my-file-name")
    {
        var storage = StorageClient.Create();
        using var outputFile = File.OpenWrite(localPath);
        storage.DownloadObject(bucketName, objectName, outputFile, new DownloadObjectOptions
        {
            UserProject = projectId
        });
        Console.WriteLine($"Downloaded {objectName} to {localPath} paid by {projectId}.");
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadUsingRequesterPays downloads an object using billing project.
func downloadUsingRequesterPays(w io.Writer, bucket, object, billingProjectID string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// billingProjectID := "billing_account_id"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	b := client.Bucket(bucket).UserProject(billingProjectID)
	src := b.Object(object)

	// Open local file.
	f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		return fmt.Errorf("os.OpenFile: %w", err)
	}

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	rc, err := src.NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %w", object, err)
	}
	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}
	if err := rc.Close(); err != nil {
		return fmt.Errorf("Reader.Close: %w", err)
	}
	fmt.Fprintf(w, "Downloaded using %v as billing project.\n", billingProjectID)
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.file.Path;

public class DownloadRequesterPaysObject {
  public static void downloadRequesterPaysObject(
      String projectId, String bucketName, String objectName, Path destFilePath) {
    // The project ID to bill
    // String projectId = "my-billable-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    Storage storage = StorageOptions.getDefaultInstance().getService();
    Blob blob =
        storage.get(
            BlobId.of(bucketName, objectName), Storage.BlobGetOption.userProject(projectId));
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));

    System.out.println(
        "Object " + objectName + " downloaded to " + destFilePath + " and billed to " + projectId);
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The project ID to bill
// const projectId = 'my-billable-project-id';

// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const srcFileName = 'your-file-name';

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadFileUsingRequesterPays() {
  const options = {
    destination: destFileName,
    userProject: projectId,
  };

  // Downloads the file
  await storage.bucket(bucketName).file(srcFileName).download(options);

  console.log(
    `gs://${bucketName}/${srcFileName} downloaded to ${destFileName} using requester-pays requests`
  );
}

downloadFileUsingRequesterPays().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

use Google\Cloud\Storage\StorageClient;

/**
 * Download file using specified project as requester
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 *        (e.g. 'my-project-id')
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $destination The local destination to save the object.
 *        (e.g. '/path/to/your/file')
 */
function download_file_requester_pays(string $projectId, string $bucketName, string $objectName, string $destination): void
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $userProject = true;
    $bucket = $storage->bucket($bucketName, $userProject);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf('Downloaded gs://%s/%s to %s using requester-pays requests.' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import storage


def download_file_requester_pays(
    bucket_name, project_id, source_blob_name, destination_file_name
):
    """Download file using specified project as the requester"""
    # bucket_name = "your-bucket-name"
    # project_id = "your-project-id"
    # source_blob_name = "source-blob-name"
    # destination_file_name = "local-destination-file-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name, user_project=project_id)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {} using a requester-pays request.".format(
            source_blob_name, destination_file_name
        )
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

def download_file_requester_pays bucket_name:, file_name:, local_file_path:
  # The ID of a GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of a GCS object
  # file_name = "your-file-name"

  # The path to which the file should be downloaded
  # local_file_path = "/local/path/to/file.txt"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true, user_project: true
  file    = bucket.file file_name

  file.download local_file_path

  puts "Downloaded #{file.name} using billing project #{storage.project}"
end

REST API

JSON API

  1. OAuth 2.0 Playground から認可アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. リクエストに、請求先プロジェクトの ID を設定した userProject クエリ文字列パラメータを含めます。

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media&userProject=PROJECT_IDENTIFIER"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • SAVE_TO_LOCATION は、オブジェクトを保存する場所です。例: Desktop/dog.png
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket
    • OBJECT_NAME は、ダウンロードするオブジェクトの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png
    • PROJECT_IDENTIFIER は、課金対象のプロジェクトの ID または番号です。例: my-project

XML API

  1. OAuth 2.0 Playground から認証アクセス トークンを取得します。固有の OAuth 認証情報を使用するように Playground を構成します。手順については、API 認証をご覧ください。
  2. リクエストに、請求先プロジェクトの ID を設定した x-goog-user-project ヘッダーを含めます。

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-user-project: PROJECT_ID" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    ここで

    • OAUTH2_TOKEN は、手順 1 で生成したアクセス トークンです。
    • PROJECT_ID は、課金対象のプロジェクトの ID です。例: my-project
    • SAVE_TO_LOCATION は、オブジェクトを保存する場所です。例: Desktop/dog.png
    • BUCKET_NAME は、関連するバケットの名前です。例: my-bucket
    • OBJECT_NAME は、ダウンロードするオブジェクトの URL エンコード名です。例: pets%2Fdog.png として URL エンコードされている pets/dog.png

次のステップ