Use Requester Pays

Overview

This page describes how to enable and disableRequester Pays, as well ashow to check to see if Requester Pays is enabled on a bucket.

Required roles

In order to get the required permissions for setting and managing RequesterPays, ask your administrator to grant you the Storage Admin(roles.storage.Admin) role on the project that contains the bucket.

This role contains the permissions required to set and manage Requester Pays.To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

  • storage.buckets.get
  • storage.buckets.update
  • resourcemanager.projects.createBillingAssignment
    • This permission is only required if you don't have a billing accountto use when disabling Requester Pays. For more information, seeUse and access requirements.

You might also be able to get these permissions with otherpredefined roles orcustom roles.

For instructions on granting roles on projects, seeGrant or revoke a role.

Set Requester Pays

To enable or disable Requester Pays on a bucket:

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, find the bucket you want to set and locate theRequester pays column.

    The value in the column indicates the current state of Requester Paysfor that bucket.

  3. Click the current state of Requester Pays for the bucket.

  4. In the window that appears, clickTurn on orTurn off, dependingon the state you want to set for Requester Pays.

When enabled, a green bubble andOn appear in theRequester payscolumn for the bucket. When disabled, a gray bubble andOff appear inthe column.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.

Command line

Use thegcloud storage buckets update command with theappropriate flag:

gcloud storage buckets update gs://BUCKET_NAMEFLAG

Where:

  • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.

  • FLAG is either--requester-pays to enableRequester Pays or--no-requester-pays to disable it.

If successful, the response looks similar to the following example:

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

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name){StatusOr<gcs::BucketMetadata>metadata=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{true}));if(!metadata)throwstd::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";}elseif(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";}}

The following sample disables Requester Pays on a bucket:

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&billed_project){StatusOr<gcs::BucketMetadata>metadata=client.PatchBucket(bucket_name,gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{false}),gcs::UserProject(billed_project));if(!metadata)throwstd::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";}elseif(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 theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassEnableRequesterPaysSample{publicBucketEnableRequesterPays(stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName);bucket.Billing??=newBucket.BillingData();bucket.Billing.RequesterPays=true;bucket=storage.UpdateBucket(bucket);Console.WriteLine($"Requester pays requests have been enabled for bucket {bucketName}.");returnbucket;}}

The following sample disables Requester Pays on a bucket:

usingGoogle.Apis.Storage.v1.Data;usingGoogle.Cloud.Storage.V1;usingSystem;publicclassDisableRequesterPaysSample{publicBucketDisableRequesterPays(stringprojectId="your-project-id",stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{UserProject=projectId});bucket.Billing??=newBucket.BillingData();bucket.Billing.RequesterPays=false;bucket=storage.UpdateBucket(bucket,newUpdateBucketOptions{UserProject=projectId});Console.WriteLine($"Requester pays disabled for bucket {bucketName}.");returnbucket;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

import("context""fmt""io""time""cloud.google.com/go/storage")// enableRequesterPays sets requester pays flag to true.funcenableRequesterPays(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{RequesterPays:true,}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Requester pays enabled for bucket %v\n",bucketName)returnnil}

The following sample disables Requester Pays on a bucket:

import("context""fmt""io""time""cloud.google.com/go/storage")// disableRequesterPays sets requester pays flag to false.funcdisableRequesterPays(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()bucket:=client.Bucket(bucketName)bucketAttrsToUpdate:=storage.BucketAttrsToUpdate{RequesterPays:false,}if_,err:=bucket.Update(ctx,bucketAttrsToUpdate);err!=nil{returnfmt.Errorf("Bucket(%q).Update: %w",bucketName,err)}fmt.Fprintf(w,"Requester pays disabled for bucket %v\n",bucketName)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassEnableRequesterPays{publicstaticvoidenableRequesterPays(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName);bucket.toBuilder().setRequesterPays(true).build().update();System.out.println("Requester pays enabled for bucket "+bucketName);}}

The following sample disables Requester Pays on a bucket:

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;publicclassDisableRequesterPays{publicstaticvoiddisableRequesterPays(StringprojectId,StringbucketName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=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

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctionenableRequesterPays(){awaitstorage.bucket(bucketName).enableRequesterPays();console.log(`Requester-pays requests have been enabled for bucket${bucketName}`);}enableRequesterPays().catch(console.error);

The following sample disables Requester Pays on a bucket:

/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiondisableRequesterPays(){// Disables requester-pays requestsawaitstorage.bucket(bucketName).disableRequesterPays();console.log(`Requester-pays requests have been disabled for bucket${bucketName}`);}disableRequesterPays().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

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

The following sample disables Requester Pays on a bucket:

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

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

fromgoogle.cloudimportstoragedefenable_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=Truebucket.patch()print(f"Requester Pays has been enabled for{bucket_name}")

The following sample disables Requester Pays on a bucket:

fromgoogle.cloudimportstoragedefdisable_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=Falsebucket.patch()print(f"Requester Pays has been disabled for{bucket_name}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

The following sample enables Requester Pays on a bucket:

defenable_requester_paysbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.requester_pays=trueputs"Requester pays has been enabled for#{bucket_name}"end

The following sample disables Requester Pays on a bucket:

defdisable_requester_paysbucket_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namebucket.requester_pays=falseputs"Requester pays has been disabled for#{bucket_name}"end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create a JSON file that contains the following information:

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

    WhereSTATE is eithertrue orfalse.

  3. UsecURL to call theJSON API with aPATCH Bucket request:

    curl -X PATCH --data-binary @JSON_FILE_NAME \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  -H "Content-Type: application/json" \  "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    Where:

    • JSON_FILE_NAME is the path for the JSONfile that you created in Step 2.
    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.

XML API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. Create an XML file that contains the following information:

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

    WhereSTATE is eitherEnabled orDisabled.

  3. UsecURL to call theXML API with aPUT Bucket request andbilling query string parameter:

    curl -X PUT --data-binary @XML_FILE_NAME \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  "https://storage.googleapis.com/BUCKET_NAME?billing"

    Where:

    • XML_FILE_NAME is the path for the XML filethat you created in Step 2.
    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.

Check whether Requester Pays is enabled

To check whether Requester Pays is enabled on a bucket:

Console

  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, the Requester Pays status of each bucket isfound in theRequester Pays column.

If enabled, the status is green and the wordOn appears.

Command line

Use thegcloud storage buckets describe command with the--format flag:

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

WhereBUCKET_NAME is the name of the bucketwhose status you want to view. For example,my-bucket.

If successful, the response looks similar to the following example:

requester_pays:true

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&user_project){StatusOr<gcs::BucketMetadata>metadata=client.GetBucketMetadata(bucket_name,gcs::UserProject(user_project));if(!metadata)throwstd::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#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetRequesterPaysStatusSample{publicboolGetRequesterPaysStatus(stringprojectId="your-project-id",stringbucketName="your-unique-bucket-name"){varstorage=StorageClient.Create();varbucket=storage.GetBucket(bucketName,newGetBucketOptions{UserProject=projectId});boolrequesterPays=bucket.Billing?.RequesterPays??false;Console.WriteLine($"RequesterPays: {requesterPays}");returnrequesterPays;}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""time""cloud.google.com/go/storage")// getRequesterPaysStatus gets requester pays status.funcgetRequesterPaysStatus(wio.Writer,bucketNamestring)error{// bucketName := "bucket-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()attrs,err:=client.Bucket(bucketName).Attrs(ctx)iferr!=nil{returnfmt.Errorf("Bucket(%q).Attrs: %w",bucketName,err)}fmt.Fprintf(w,"Is requester pays enabled? %v\n",attrs.RequesterPays)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.cloud.storage.Bucket;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;publicclassGetRequesterPaysStatus{publicstaticvoidgetRequesterPaysStatus(StringprojectId,StringbucketName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Bucketbucket=storage.get(bucketName,Storage.BucketGetOption.fields(Storage.BucketField.BILLING));System.out.println("Requester pays status : "+bucket.requesterPays());}}

Node.js

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetRequesterPaysStatus(){// Gets the requester-pays status of a bucketconst[metadata]=awaitstorage.bucket(bucketName).getMetadata();letstatus;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 theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theJSON API with aGET Bucket request:

    curl -X GET \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    WhereBUCKET_NAME is the name of therelevant bucket. For example,my-bucket.

XML API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. UsecURL to call theXML API with aGET Bucket request andbilling query string parameter:

    curl -X GET \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  "https://storage.googleapis.com/BUCKET_NAME?billing"

    WhereBUCKET_NAME is the name of therelevant bucket. For example,my-bucket.

Access Requester Pays buckets

The following example shows how to include a billing project so that youcandownload an object stored in a Requester Pays bucket. Use a similarprocedure to perform other requests on the Requester Pays bucket or on objectswithin it. SeeRequester Pays access requirements for prerequisiteconsiderations.

Important: Buckets that have Requester Pays disabled still accept requests thatinclude a billing project, and charges are applied to the billing projectsupplied in the request. Consider any billing implications prior to including abilling project in all of your requests.

Console

Note: If you previously used the Google Cloud console to access a givenRequester Pays bucket, you have immediate access to the bucket and candownload the object as you normally would. The project you previouslyspecified as the billing project is used for this subsequent access. You canchange the project you bill by clicking theChange project buttonlocated above the list of objects in the bucket.
  1. In the Google Cloud console, go to the Cloud StorageBuckets page.

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that containsthe object you want to download.

  3. In the window that appears, use the drop-down menu to select a projectfor billing.

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

  5. ClickSave.

  6. Download the object as you normally would.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, seeTroubleshooting.

Command line

Note: The--billing-project flag also sets the project againstwhich quota is charged.

Use the--billing-project flag in your request:

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

Where:

  • BUCKET_NAME is the name of the bucketcontaining the object you are downloading. For example,my-bucket.
  • OBJECT_NAME is the name of object you aredownloading. For example,pets/dog.png.
  • SAVE_TO_LOCATION is the local path where youare saving your object. For example,Desktop/Images.
  • PROJECT_IDENTIFIER is the ID or number of theproject to be billed. For example,my-project.

Client libraries

C++

For more information, see theCloud StorageC++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

namespacegcs=::google::cloud::storage;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::stringconst&billed_project){gcs::ObjectReadStreamstream=client.ReadObject(bucket_name,object_name,gcs::UserProject(billed_project));std::stringline;while(std::getline(stream,line,'\n')){std::cout <<line <<"\n";}if(stream.bad())throwgoogle::cloud::Status(stream.status());}

C#

For more information, see theCloud StorageC# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.IO;publicclassDownloadFileRequesterPaysSample{publicvoidDownloadFileRequesterPays(stringprojectId="your-project-id",stringbucketName="your-unique-bucket-name",stringobjectName="my-file-name",stringlocalPath="my-local-path/my-file-name"){varstorage=StorageClient.Create();usingvaroutputFile=File.OpenWrite(localPath);storage.DownloadObject(bucketName,objectName,outputFile,newDownloadObjectOptions{UserProject=projectId});Console.WriteLine($"Downloaded {objectName} to {localPath} paid by {projectId}.");}}

Go

For more information, see theCloud StorageGo API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

import("context""fmt""io""os""time""cloud.google.com/go/storage")// downloadUsingRequesterPays downloads an object using billing project.funcdownloadUsingRequesterPays(wio.Writer,bucket,object,billingProjectIDstring)error{// bucket := "bucket-name"// object := "object-name"// billingProjectID := "billing_account_id"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.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)iferr!=nil{returnfmt.Errorf("os.OpenFile: %w",err)}ctx,cancel:=context.WithTimeout(ctx,time.Second*50)defercancel()rc,err:=src.NewReader(ctx)iferr!=nil{returnfmt.Errorf("Object(%q).NewReader: %w",object,err)}if_,err:=io.Copy(f,rc);err!=nil{returnfmt.Errorf("io.Copy: %w",err)}iferr:=rc.Close();err!=nil{returnfmt.Errorf("Reader.Close: %w",err)}fmt.Fprintf(w,"Downloaded using %v as billing project.\n",billingProjectID)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.nio.file.Path;publicclassDownloadRequesterPaysObject{publicstaticvoiddownloadRequesterPaysObject(StringprojectId,StringbucketName,StringobjectName,PathdestFilePath){// 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");Storagestorage=StorageOptions.getDefaultInstance().getService();Blobblob=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

For more information, see theCloud StorageNode.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

/** * 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 libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiondownloadFileUsingRequesterPays(){constoptions={destination:destFileName,userProject:projectId,};// Downloads the fileawaitstorage.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 theCloud StoragePHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

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

For more information, see theCloud StoragePython API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

fromgoogle.cloudimportstoragedefdownload_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 theCloud StorageRuby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, seeSet up authentication for client libraries.

defdownload_file_requester_paysbucket_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.newbucket=storage.bucketbucket_name,skip_lookup:true,user_project:truefile=bucket.filefile_namefile.downloadlocal_file_pathputs"Downloaded#{file.name} using billing project#{storage.project}"end

REST APIs

JSON API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. In your request, include theuserProject query string parameter setto the ID of the project to be billed:

    curl -X GET \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  -o "SAVE_TO_LOCATION" \  "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media&userProject=PROJECT_IDENTIFIER"

    Where:

    • SAVE_TO_LOCATION is the location whereyou want to save your object. For example,Desktop/dog.png.
    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.
    • OBJECT_NAME is the URL-encoded name of theobject you want to download. For example,pets/dog.png,URL-encoded aspets%2Fdog.png.
    • PROJECT_IDENTIFIER is the ID or number ofthe project to be billed. For example,my-project.

XML API

  1. Have gcloud CLIinstalled and initialized, which lets you generate an access token for theAuthorization header.

  2. In your request, include thex-goog-user-project header set to theID of the project to be billed:

    curl -X GET \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  -H "x-goog-user-project:PROJECT_ID" \  -o "SAVE_TO_LOCATION" \  "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Where:

    • PROJECT_ID is the ID of the project to bebilled. For example,my-project.
    • SAVE_TO_LOCATION is the location where youwant to save your object. For example,Desktop/dog.png.
    • BUCKET_NAME is the name of the relevantbucket. For example,my-bucket.
    • OBJECT_NAME is the URL-encoded name of theobject you want to download. For example,pets/dog.png,URL-encoded aspets%2Fdog.png.

What's next

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.