Using Requester Pays

Go to concepts

This page describes how to set up the Requester Pays feature and gives an example of making a request on a bucket that has enabled the Requester Pays feature.

Setting up Requester Pays

The following sections show how to turn Requester Pays on and off, as well as how to check to see if Requester Pays is enabled on a bucket.

Prerequisites

  1. You should have the storage.buckets.get permission, which allows you to get the requester pays status for a bucket and is also required for enabling and disabling Requester Pays with the Google Cloud Console or gsutil.

  2. When enabling or disabling Requester Pays, you must have the storage.buckets.update permission.

  3. When disabling Requester Pays, you must either include a billing project in your request or else have the resourcemanager.projects.createBillingAssignment permission. See Requester Pays Use and access requirements for more information.

Permissions are given to users through roles. For example, users granted the Storage Admin role have all of the above storage.buckets permissions. Roles can be added to the project that contains the bucket.

Enabling Requester Pays

To enable Requester Pays on a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, find the bucket you want to enable, and click the Off button in the Requester pays column.

  3. In the window that appears, click Turn on.

Once enabled, a green bubble and On appear in the Requester pays column for the bucket.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil requesterpays set on command:

gsutil requesterpays set on gs://BUCKET_NAME

Where BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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::runtime_error(metadata.status().message());

  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";
  }
}

C#

For more information, see the Cloud Storage C# API reference documentation.

void EnableRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bucket.Billing = bucket.Billing ?? new Bucket.BillingData();
    bucket.Billing.RequesterPays = true;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
        UserProject = s_projectId
    });
}

Go

For more information, see the Cloud Storage Go API reference documentation.

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: %v", 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: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Requester pays enabled for bucket %v\n", bucketName)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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);
  }
}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

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

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

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

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

enableRequesterPays().catch(console.error);

PHP

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_requester_pays($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => true
        ]
    ]);
    printf('Requester pays has been enabled for %s' . PHP_EOL, $bucketName);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

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("Requester Pays has been enabled for {}".format(bucket_name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Name of your Google Cloud Storage bucket"

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}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "billing": {
        "requesterPays": true
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request:

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

    Where:

    • JSON_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create an .xml file that contains the following information:

    <BillingConfiguration>
      <RequesterPays>Enabled</RequesterPays>
    </BillingConfiguration>
  3. Use cURL to call the XML API with a PUT Bucket request and requesterpays query string parameter:

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

    Where:

    • XML_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

Disabling Requester Pays

To disable Requester Pays on a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, find the bucket you want to disable, and click the On button in the Requester pays column.

  3. In the window that appears, click Turn off.

Once disabled, a gray bubble and Off appear in the Requester pays column.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the gsutil requesterpays set off command:

gsutil requesterpays set off gs://BUCKET_NAME

Where BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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::runtime_error(metadata.status().message());

  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#

For more information, see the Cloud Storage C# API reference documentation.

void DisableRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bucket.Billing = bucket.Billing ?? new Bucket.BillingData();
    bucket.Billing.RequesterPays = false;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
        UserProject = s_projectId
    });
}

Go

For more information, see the Cloud Storage Go API reference documentation.

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: %v", 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: %v", bucketName, err)
	}
	fmt.Fprintf(w, "Requester pays disabled for bucket %v\n", bucketName)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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);
    bucket.toBuilder().setRequesterPays(false).build().update();

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

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.


/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// 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

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Disable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function disable_requester_pays($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => false
        ]
    ]);
    printf('Requester pays has been disabled for %s' . PHP_EOL, $bucketName);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

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("Requester Pays has been disabled for {}".format(bucket_name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Name of your Google Cloud Storage bucket"

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}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the following information:

    {
      "billing": {
        "requesterPays": false
      }
    }
  3. Use cURL to call the JSON API with a PATCH Bucket request:

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

    Where:

    • JSON_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create an .xml file that contains the following information:

    <BillingConfiguration>
      <RequesterPays>Disabled</RequesterPays>
    </BillingConfiguration>
  3. Use cURL to call the XML API with a PUT Bucket request and requesterpays query string parameter:

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

    Where:

    • XML_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

Checking whether Requester Pays is enabled

To check whether Requester Pays is enabled on a bucket:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, the Requester Pays status of each bucket is found in the Requester Pays column.

If enabled, the status is green and the word On appears.

gsutil

Use the gsutil requesterpays get command:

gsutil requesterpays get gs://BUCKET_NAME

Where BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

The response looks like the following if Requester Pays is enabled:

gs://my-bucket: Enabled

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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::runtime_error(metadata.status().message());

  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#

For more information, see the Cloud Storage C# API reference documentation.

bool GetRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bool? requesterPaysOrNull = bucket.Billing?.RequesterPays;
    bool requesterPays =
        requesterPaysOrNull.HasValue ? requesterPaysOrNull.Value : false;
    Console.WriteLine("RequesterPays: {0}", requesterPays);
    return requesterPays;
}

Go

For more information, see the Cloud Storage Go API reference documentation.

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Is requester pays enabled? %v\n", attrs.RequesterPays)

Java

For more information, see the Cloud Storage Java API reference documentation.

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of the bucket to retrieve requester-pays status, eg. "my-bucket"
// String bucketName = "my-bucket"
// Retrieve the bucket, throws StorageException on failure
Bucket bucket = storage.get(bucketName, Storage.BucketGetOption.fields(BucketField.BILLING));

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

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// 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

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Get a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function get_requester_pays_status($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $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

For more information, see the Cloud Storage Python API reference documentation.

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("Requester Pays is enabled for {}".format(bucket_name))
    else:
        print("Requester Pays is disabled for {}".format(bucket_name))

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

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

if bucket.requester_pays
  puts "Requester Pays is enabled for #{bucket_name}"
else
  puts "Requester Pays is disabled for #{bucket_name}"
end

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET Bucket request:

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

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a GET Bucket request and billing query string parameter:

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

    Where:

    • OAUTH2_TOKEN is the name of the access token you generated in Step 1.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.

Accessing Requester Pays buckets

The following example shows how to include a billing project so that you can download an object stored in a Requester Pays bucket. Use a similar procedure to perform other requests on the Requester Pays bucket or on objects within it. See Requester Pays access requirements for prerequisite considerations.

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. In the list of buckets, click on the name of the bucket that contains the object you want to download.

  3. In the window that appears, use the dropdown menu to select a project for billing.

  4. Check the checkbox to confirm you are authorized to use the selected project for billing purposes.

  5. Click Save.

  6. Download the object as you normally would.

See Troubleshooting for how to get detailed error information about failed operations in the Cloud Storage browser.

gsutil

Use the -u flag in your request:

gsutil -u PROJECT_ID cp gs://BUCKET_NAME/OBJECT_NAME OBJECT_DESTINATION

Where:

  • PROJECT_ID is the ID of the project to be billed. For example, my-project.
  • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.
  • OBJECT_NAME is the name of the object you want to download. For example, pets/dog.png.
  • OBJECT_DESTINATION is the location where you want to save your object. For example, Desktop/dog.png.

Code samples

C++

For more information, see the Cloud Storage C++ API reference documentation.

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";
  }
}

C#

For more information, see the Cloud Storage C# API reference documentation.

private void DownloadObjectRequesterPays(string bucketName,
    string objectName, string localPath = null)
{
    var storage = StorageClient.Create();
    localPath = localPath ?? Path.GetFileName(objectName);
    using (var outputFile = File.OpenWrite(localPath))
    {
        storage.DownloadObject(bucketName, objectName, outputFile,
            new DownloadObjectOptions()
            {
                UserProject = s_projectId
            });
    }
    Console.WriteLine(
        $"downloaded {objectName} to {localPath} paid by {s_projectId}.");
}

Go

For more information, see the Cloud Storage Go API reference documentation.

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: %v", 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: %v", 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: %v", object, err)
	}
	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}
	if err := rc.Close(); err != nil {
		return fmt.Errorf("Reader.Close: %v", err)
	}
	fmt.Fprintf(w, "Downloaded using %v as billing project.\n", billingProjectID)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

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));
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));

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

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The project ID to bill from, e.g. some-project-id';
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'Name of file to download, e.g. file.txt';
// const destFilename = 'Local destination of file, e.g. ./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 = {
    // The path to which the file should be downloaded, e.g. "./file.txt"
    destination: destFilename,

    // The project to bill from, if requester-pays requests are enabled
    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

For more information, see the Cloud Storage PHP API reference documentation.

use Google\Cloud\Storage\StorageClient;

/**
 * Download file using specified project as requester
 *
 * @param string $projectId Your Google Cloud billable project ID.
 * @param string $bucketName A Google Cloud Storage bucket name.
 * @param string $objectName Name of object in Google Cloud Storage to download locally.
 * @param string $destination Path to local file to save.
 *
 * @return void
 */
function download_file_requester_pays($projectId, $bucketName, $objectName, $destination)
{
    $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

For more information, see the Cloud Storage Python API reference documentation.

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

For more information, see the Cloud Storage Ruby API reference documentation.

# bucket_name = "A Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to download locally"
# local_path  = "Destination path for downloaded file"

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_path

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

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. In your request, include the userProject query string parameter set to the ID of the project to be billed:

    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_ID"

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • SAVE_TO_LOCATION is the location where you want to save your object. For example, Desktop/dog.png.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.
    • OBJECT_NAME is the name of the object you want to download. For example, pets/dog.png.
    • PROJECT_ID is the ID of the project to be billed. For example, my-project.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. In your request, include the x-goog-user-project header set to the ID of the project to be billed:

    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"

    Where:

    • OAUTH2_TOKEN is the access token you generated in Step 1.
    • PROJECT_ID is the ID of the project to be billed. For example, my-project.
    • SAVE_TO_LOCATION is the location where you want to save your object. For example, Desktop/dog.png.
    • BUCKET_NAME is the name of the relevant bucket. For example, my-bucket.
    • OBJECT_NAME is the name of the object you want to download. For example, pets/dog.png.

What's next