Google Cloud Storage C++ Client 2.13.0
A C++ Client Library for Google Cloud Storage
Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Public Member Functions | List of all members
google::cloud::storage::Client Class Reference

The Google Cloud Storage (GCS) Client. More...

#include <google/cloud/storage/client.h>

Classes

struct  NoDecorations
 Define a tag to disable automatic decorations of the RawClient. More...
 

Public Member Functions

 Client (Options opts={})
 Build a new client. More...
 
template<typename... Options>
StatusOr< PolicyDocumentResultCreateSignedPolicyDocument (PolicyDocument document, Options &&... options)
 Create a signed policy document. More...
 
template<typename... Options>
StatusOr< PolicyDocumentV4ResultGenerateSignedPostPolicyV4 (PolicyDocumentV4 document, Options &&... options)
 Create a signed V4 policy document. More...
 
template<typename... Policies>
 Client (ClientOptions options, Policies &&... policies)
 Creates the default client type given the options. More...
 
template<typename... Policies>
 Client (std::shared_ptr< oauth2::Credentials > credentials, Policies &&... policies)
 Creates the default client type given the credentials and policies. More...
 
template<typename... Policies>
 Client (std::shared_ptr< internal::RawClient > client, Policies &&... policies)
 Builds a client and maybe override the retry, idempotency, and/or backoff policies. More...
 
 Client (std::shared_ptr< internal::RawClient > client, NoDecorations)
 Builds a client with a specific RawClient, without decorations. More...
 
std::shared_ptr< internal::RawClient > raw_client () const
 Access the underlying RawClient. More...
 
Bucket operations.

Buckets are the basic containers that hold your data.

Everything that you store in GCS must be contained in a bucket. You can use buckets to organize your data and control access to your data, but unlike directories and folders, you cannot nest buckets.

See also
https://cloud.google.com/storage/docs/key-terms#buckets for more information about GCS buckets.
template<typename... Options>
ListBucketsReader ListBucketsForProject (std::string const &project_id, Options &&... options)
 Fetches the list of buckets for a given project. More...
 
template<typename... Options>
ListBucketsReader ListBuckets (Options &&... options)
 Fetches the list of buckets for the default project. More...
 
template<typename... Options>
StatusOr< BucketMetadataCreateBucket (std::string bucket_name, BucketMetadata metadata, Options &&... options)
 Creates a new Google Cloud Storage bucket using the default project. More...
 
template<typename... Options>
StatusOr< BucketMetadataCreateBucketForProject (std::string bucket_name, std::string project_id, BucketMetadata metadata, Options &&... options)
 Creates a new Google Cloud Storage Bucket in a given project. More...
 
template<typename... Options>
StatusOr< BucketMetadataGetBucketMetadata (std::string const &bucket_name, Options &&... options)
 Fetches the bucket metadata. More...
 
template<typename... Options>
Status DeleteBucket (std::string const &bucket_name, Options &&... options)
 Deletes a Google Cloud Storage Bucket. More...
 
template<typename... Options>
StatusOr< BucketMetadataUpdateBucket (std::string bucket_name, BucketMetadata metadata, Options &&... options)
 Updates the metadata in a Google Cloud Storage Bucket. More...
 
template<typename... Options>
StatusOr< BucketMetadataPatchBucket (std::string bucket_name, BucketMetadata const &original, BucketMetadata const &updated, Options &&... options)
 Computes the difference between two BucketMetadata objects and patches a bucket based on that difference. More...
 
template<typename... Options>
StatusOr< BucketMetadataPatchBucket (std::string bucket_name, BucketMetadataPatchBuilder const &builder, Options &&... options)
 Patches the metadata in a Google Cloud Storage Bucket given a desired set changes. More...
 
template<typename... Options>
StatusOr< NativeIamPolicyGetNativeBucketIamPolicy (std::string const &bucket_name, Options &&... options)
 Fetches the native IAM policy for a Bucket. More...
 
template<typename... Options>
StatusOr< NativeIamPolicySetNativeBucketIamPolicy (std::string const &bucket_name, NativeIamPolicy const &iam_policy, Options &&... options)
 Sets the native IAM Policy for a Bucket. More...
 
template<typename... Options>
StatusOr< std::vector< std::string > > TestBucketIamPermissions (std::string bucket_name, std::vector< std::string > permissions, Options &&... options)
 Tests the IAM permissions of the caller against a Bucket. More...
 
template<typename... Options>
StatusOr< BucketMetadataLockBucketRetentionPolicy (std::string const &bucket_name, std::uint64_t metageneration, Options &&... options)
 Locks the retention policy for a bucket. More...
 
Object operations

Objects are the individual pieces of data that you store in GCS.

Objects have two components: object data and object metadata. Object data (sometimes referred to as media) is typically a file that you want to store in GCS. Object metadata is information that describe various object qualities.

See also
https://cloud.google.com/storage/docs/key-terms#objects for more information about GCS objects.
template<typename... Options>
StatusOr< ObjectMetadataInsertObject (std::string const &bucket_name, std::string const &object_name, absl::string_view contents, Options &&... options)
 Creates an object given its name and contents. More...
 
template<typename... Options>
StatusOr< ObjectMetadataInsertObject (std::string const &bucket_name, std::string const &object_name, std::string const &contents, Options &&... options)
 Creates an object given its name and contents. More...
 
template<typename... Options>
StatusOr< ObjectMetadataInsertObject (std::string const &bucket_name, std::string const &object_name, char const *contents, Options &&... options)
 Creates an object given its name and contents. More...
 
template<typename... Options>
StatusOr< ObjectMetadataCopyObject (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, Options &&... options)
 Copies an existing object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataGetObjectMetadata (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Fetches the object metadata. More...
 
template<typename... Options>
ListObjectsReader ListObjects (std::string const &bucket_name, Options &&... options)
 Lists the objects in a bucket. More...
 
template<typename... Options>
ListObjectsAndPrefixesReader ListObjectsAndPrefixes (std::string const &bucket_name, Options &&... options)
 Lists the objects and prefixes in a bucket. More...
 
template<typename... Options>
ObjectReadStream ReadObject (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Reads the contents of an object. More...
 
template<typename... Options>
ObjectWriteStream WriteObject (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Writes contents into an object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataUploadFile (std::string const &file_name, std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Uploads a file to an object. More...
 
template<typename... Options>
Status DeleteResumableUpload (std::string const &upload_session_url, Options &&... options)
 Cancel a resumable upload. More...
 
template<typename... Options>
Status DownloadToFile (std::string const &bucket_name, std::string const &object_name, std::string const &file_name, Options &&... options)
 Downloads a Cloud Storage object to a file. More...
 
template<typename... Options>
Status DeleteObject (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Deletes an object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataUpdateObject (std::string bucket_name, std::string object_name, ObjectMetadata metadata, Options &&... options)
 Updates the metadata in a Google Cloud Storage Object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataPatchObject (std::string bucket_name, std::string object_name, ObjectMetadata const &original, ObjectMetadata const &updated, Options &&... options)
 Patches the metadata in a Google Cloud Storage Object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataPatchObject (std::string bucket_name, std::string object_name, ObjectMetadataPatchBuilder const &builder, Options &&... options)
 Patches the metadata in a Google Cloud Storage Object. More...
 
template<typename... Options>
StatusOr< ObjectMetadataComposeObject (std::string bucket_name, std::vector< ComposeSourceObject > source_objects, std::string destination_object_name, Options &&... options)
 Composes existing objects into a new object in the same bucket. More...
 
template<typename... Options>
ObjectRewriter RewriteObject (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, Options &&... options)
 Creates an ObjectRewriter to copy the source object. More...
 
template<typename... Options>
ObjectRewriter ResumeRewriteObject (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, std::string rewrite_token, Options &&... options)
 Creates an ObjectRewriter to resume a previously created rewrite. More...
 
template<typename... Options>
StatusOr< ObjectMetadataRewriteObjectBlocking (std::string source_bucket_name, std::string source_object_name, std::string destination_bucket_name, std::string destination_object_name, Options &&... options)
 Rewrites the object, blocking until the rewrite completes, and returns the resulting ObjectMetadata. More...
 
Bucket Access Control List operations.

You can control who has access to your GCS buckets and objects as well as what level of access they have.

Note
In most cases, you should use IAM permissions instead of ACLs to control access to buckets.
All buckets are owned by the project owners group. Project owners are granted OWNER permissions to all buckets inside their project. Bucket and object ownership cannot be changed by modifying ACLs.
When you apply a new ACL to a bucket, GCS adds OWNER permission to the bucket if you omit the grants. You cannot remove the project owners group from a bucket ACL. Attempts to do so will appear to succeed, but the service will add the project owners group into the new ACL before applying it.
See also
https://cloud.google.com/storage/docs/access-control/ for more information about access control in GCS.
https://cloud.google.com/storage/docs/access-control/lists#defaultbuckets for more details about the default owners for a bucket.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameters.
template<typename... Options>
StatusOr< std::vector< BucketAccessControl > > ListBucketAcl (std::string const &bucket_name, Options &&... options)
 Retrieves the list of BucketAccessControl items for a bucket. More...
 
template<typename... Options>
StatusOr< BucketAccessControlCreateBucketAcl (std::string const &bucket_name, std::string const &entity, std::string const &role, Options &&... options)
 Creates a new entry in a bucket ACL. More...
 
template<typename... Options>
Status DeleteBucketAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Deletes an entry from a bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlGetBucketAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Gets the value of an existing bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlUpdateBucketAcl (std::string const &bucket_name, BucketAccessControl const &acl, Options &&... options)
 Updates the value of an existing bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlPatchBucketAcl (std::string const &bucket_name, std::string const &entity, BucketAccessControl const &original_acl, BucketAccessControl const &new_acl, Options &&... options)
 Patches the value of an existing bucket ACL. More...
 
template<typename... Options>
StatusOr< BucketAccessControlPatchBucketAcl (std::string const &bucket_name, std::string const &entity, BucketAccessControlPatchBuilder const &builder, Options &&... options)
 Patches the value of an existing bucket ACL. More...
 
Object Access Control List operations.

You can control who has access to your GCS buckets and objects as well as what level of access they have.

Note
When you upload (create) an object the entity that uploads the object is listed as the object owner. This can be a user or a service account, depending on what credentials are used to authenticate with GCS. Object ownership cannot be changed by modifying ACLs. You can change object ownership only by overwriting the object while authenticated as the desired owner.
When you apply a new ACL to an object, GCS adds OWNER permission to the object if you omit the grants.
See also
https://cloud.google.com/storage/docs/access-control/ for more information about access control in GCS.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameters.
template<typename... Options>
StatusOr< std::vector< ObjectAccessControl > > ListObjectAcl (std::string const &bucket_name, std::string const &object_name, Options &&... options)
 Retrieves the list of ObjectAccessControl items for an object. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlCreateObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, std::string const &role, Options &&... options)
 Creates a new entry in the object ACL. More...
 
template<typename... Options>
Status DeleteObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, Options &&... options)
 Deletes one access control entry in one object. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlGetObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, Options &&... options)
 Gets the value of an existing object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlUpdateObjectAcl (std::string const &bucket_name, std::string const &object_name, ObjectAccessControl const &acl, Options &&... options)
 Updates the value of an existing object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, ObjectAccessControl const &original_acl, ObjectAccessControl const &new_acl, Options &&... options)
 Patches the value of an existing object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchObjectAcl (std::string const &bucket_name, std::string const &object_name, std::string const &entity, ObjectAccessControlPatchBuilder const &builder, Options &&... options)
 Patches the value of an existing object ACL. More...
 
Bucket Default Object Access Control List operations.

When you upload an object to GCS without specifying an ACL, the object is created with the Default Object ACL for its bucket.

These operations are used to query and modify the Default Object ACL of a bucket.

See also
https://cloud.google.com/storage/docs/access-control/lists#defaultobjects for more information on default object ACLs.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameters.
template<typename... Options>
StatusOr< std::vector< ObjectAccessControl > > ListDefaultObjectAcl (std::string const &bucket_name, Options &&... options)
 Retrieves the default object ACL for a bucket as a vector of ObjectAccessControl items. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlCreateDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, std::string const &role, Options &&... options)
 Creates a new entry in the default object ACL for a bucket. More...
 
template<typename... Options>
Status DeleteDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Deletes an entry from the default object ACL in a bucket. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlGetDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, Options &&... options)
 Gets the value of a default object ACL in a bucket. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlUpdateDefaultObjectAcl (std::string const &bucket_name, ObjectAccessControl const &acl, Options &&... options)
 Updates the value of an existing default object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, ObjectAccessControl const &original_acl, ObjectAccessControl const &new_acl, Options &&... options)
 Patches the value of an existing default object ACL. More...
 
template<typename... Options>
StatusOr< ObjectAccessControlPatchDefaultObjectAcl (std::string const &bucket_name, std::string const &entity, ObjectAccessControlPatchBuilder const &builder, Options &&... options)
 Patches the value of an existing default object ACL. More...
 
Service account operations.

Service accounts allow applications to authenticate and access GCP resources and services.

When acting on your behalf, GCS uses such a service account. GCS creates one service account per project. These operations allow you to query the GCS service account for a project.

See also
https://cloud.google.com/storage/docs/projects#service-accounts for more information on service accounts.
template<typename... Options>
StatusOr< ServiceAccountGetServiceAccountForProject (std::string const &project_id, Options &&... options)
 Gets the GCS service account for a given project. More...
 
template<typename... Options>
StatusOr< ServiceAccountGetServiceAccount (Options &&... options)
 Gets the GCS service account for the default project. More...
 
template<typename... Options>
ListHmacKeysReader ListHmacKeys (Options &&... options)
 List the available HMAC keys. More...
 
template<typename... Options>
StatusOr< std::pair< HmacKeyMetadata, std::string > > CreateHmacKey (std::string service_account, Options &&... options)
 Create a new HMAC key. More...
 
template<typename... Options>
Status DeleteHmacKey (std::string access_id, Options &&... options)
 Delete a HMAC key in a given project. More...
 
template<typename... Options>
StatusOr< HmacKeyMetadataGetHmacKey (std::string access_id, Options &&... options)
 Get an existing HMAC key in a given project. More...
 
template<typename... Options>
StatusOr< HmacKeyMetadataUpdateHmacKey (std::string access_id, HmacKeyMetadata resource, Options &&... options)
 Update an existing HMAC key in a given project. More...
 
Signed URL support operations.
template<typename... Options>
StatusOr< std::string > CreateV2SignedUrl (std::string verb, std::string bucket_name, std::string object_name, Options &&... options)
 Create a V2 signed URL for the given parameters. More...
 
template<typename... Options>
StatusOr< std::string > CreateV4SignedUrl (std::string verb, std::string bucket_name, std::string object_name, Options &&... options)
 Create a V4 signed URL for the given parameters. More...
 
Pub/Sub operations.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Cloud Pub/Sub, where the information is added to a Cloud Pub/Sub topic of your choice in the form of messages.

See also
https://cloud.google.com/storage/docs/pubsub-notifications for more information about Cloud Pub/Sub in the context of GCS.
template<typename... Options>
StatusOr< std::vector< NotificationMetadata > > ListNotifications (std::string const &bucket_name, Options &&... options)
 Retrieves the list of Notifications for a Bucket. More...
 
template<typename... Options>
StatusOr< NotificationMetadataCreateNotification (std::string const &bucket_name, std::string const &topic_name, NotificationMetadata metadata, Options &&... options)
 Creates a new notification config for a Bucket. More...
 
template<typename... Options>
StatusOr< NotificationMetadataCreateNotification (std::string const &bucket_name, std::string const &topic_name, std::string const &payload_format, NotificationMetadata metadata, Options &&... options)
 Creates a new notification config for a Bucket. More...
 
template<typename... Options>
StatusOr< NotificationMetadataGetNotification (std::string const &bucket_name, std::string const &notification_id, Options &&... options)
 Gets the details about a notification config in a given Bucket. More...
 
template<typename... Options>
Status DeleteNotification (std::string const &bucket_name, std::string const &notification_id, Options &&... options)
 Delete an existing notification config in a given Bucket. More...
 

Static Public Member Functions

static StatusOr< ClientCreateDefaultClient ()
 Create a Client using ClientOptions::CreateDefaultClientOptions(). More...
 

Friends

Equality
bool operator== (Client const &a, Client const &b)
 
bool operator!= (Client const &a, Client const &b)
 

Detailed Description

The Google Cloud Storage (GCS) Client.

This is the main class to interact with GCS. It provides member functions to invoke all the APIs in the service.

Performance
Creating an object of this type is a relatively low-cost operation. Connections to the service are created on demand. Copy-assignment and copy-construction are also relatively low-cost operations, they should be comparable to copying a few shared pointers. The first request (or any request that requires a new connection) incurs the cost of creating the connection and authenticating with the service. Note that the library may need to perform other bookkeeping operations that may impact performance. For example, access tokens need to be refreshed from time to time, and this may impact the performance of some operations.
Connection Pool
By default this class uses HTTPS to communicate with the service. Creating a new HTTPS session is relatively expensive, as it must go through the TCP/IP and SSL handshakes. To minimize this overhead the class maintains a connection pool to the service. After each request completes the connection is returned to the pool, and reused in future requests. Note that for downloads (implemented by the ReadObject() member function) the connection remains in use until the download completes. Therefore, having multiple downloads open at the same time requires multiple connections.

The application can limit the maximum size of this connection pool using storage::ConnectionPoolSizeOption. If returning a connection to the pool would make the pool larger than this limit then the oldest connection in the pool is closed (recall that all connections in the pool are inactive). Note that this is the maximum size of the pool, the client library does not create connections until needed.

Note that the application may (at times) use more connections than the maximum size of the pool. For example if N downloads are in progress the library may need N connections, even if the pool size is smaller.

Two clients that compare equal share the same connection pool. Two clients created with the default constructor or with the constructor from a google::cloud::Options are never equal and do not share connection pools. Clients created via copy (or move) construction compare equal and share the connection pool.

Thread-safety
Instances of this class created via copy-construction or copy-assignment share the underlying pool of connections. Access to these copies via multiple threads is guaranteed to work. Two threads operating on the same instance of this class is not guaranteed to work.
Credentials
The default approach for creating a Client uses Google Application Default Credentials (ADCs). Note that a default-constructed client uses the ADCs:
namespace gcs = ::google::cloud::storage;
[](std::string const& bucket_name, std::string const& object_name) {
auto client = gcs::Client();
PerformSomeOperations(client, bucket_name, object_name);
}

Finding or loading the ADCs can fail. This will result in run-time errors when making requests.

If you prefer to explicitly load the ADCs use:

namespace gcs = ::google::cloud::storage;
using ::google::cloud::Options;
using ::google::cloud::UnifiedCredentialsOption;
[](std::string const& bucket_name, std::string const& object_name) {
auto client = gcs::Client(Options{}.set<UnifiedCredentialsOption>(
PerformSomeOperations(client, bucket_name, object_name);
}
Options & set(ValueTypeT< T > v)
std::shared_ptr< Credentials > MakeGoogleDefaultCredentials(Options opts={})

To load a service account credentials key file use:

namespace gcs = ::google::cloud::storage;
[](std::string const& filename, std::string const& bucket_name,
std::string const& object_name) {
auto is = std::ifstream(filename);
is.exceptions(std::ios::badbit);
auto json_string =
std::string(std::istreambuf_iterator<char>(is.rdbuf()), {});
auto credentials =
auto client = gcs::Client(
credentials));
PerformSomeOperations(client, bucket_name, object_name);
}
std::shared_ptr< Credentials > MakeServiceAccountCredentials(std::string json_object, Options opts={})

Other credential types are available, including:

Error Handling
This class uses StatusOr<T> to report errors. When an operation fails to perform its work the returned StatusOr<T> contains the error details. If the ok() member function in the StatusOr<T> returns true then it contains the expected result. Please consult the `StatusOr<T>` documentation for more details.
namespace gcs = google::cloud::storage;
gcs::Client client = ...;
client.GetBucketMetadata("my-bucket");
if (!bucket_metadata) {
std::cerr << "Error getting metadata for my-bucket: "
<< bucket_metadata.status() << "\n";
return;
}
// Use bucket_metadata as a smart pointer here, e.g.:
std::cout << "The generation for " << bucket_metadata->name() " is "
<< bucket_metadata->generation() << "\n";
Status const & status() const &
Contains all the Google Cloud Storage C++ client APIs.
Definition: auto_finalize.h:24

In addition, the main page contains examples using StatusOr<T> to handle errors.

Optional Request Options
Most of the member functions in this class can receive optional request options. For example, the default when reading multi-version objects is to retrieve the latest version:
auto stream = gcs.ReadObject("my-bucket", "my-object");

Some applications may want to retrieve specific versions. In this case just provide the Generation request option:

auto stream = gcs.ReadObject(
"my-bucket", "my-object", gcs::Generation(generation));

Each function documents the types accepted as optional request options. These parameters can be specified in any order. Specifying a request option that is not applicable to a member function results in a compile-time error.

All operations support the following common request options:

Per-operation Overrides

In addition to the request options, which are passed on to the service to modify the request, you can specify options that override the local behavior of the library. For example, you can override the local retry policy:

namespace g = ::google::cloud;
namespace gcs = ::google::cloud::storage;
[](std::string const& bucket_name, std::string const& object_name_1,
std::string const& object_name_2) {
auto client = gcs::Client();
auto metadata = client.InsertObject(
bucket_name, object_name_1,
"The quick brown fox jumps over the lazy dog",
g::Options{}.set<gcs::RetryPolicyOption>(
gcs::LimitedTimeRetryPolicy(std::chrono::minutes(5)).clone()));
if (!metadata) throw std::move(metadata).status();
auto is =
client.ReadObject(bucket_name, object_name_1,
g::Options{}.set<gcs::RetryPolicyOption>(
gcs::LimitedErrorCountRetryPolicy(10).clone()));
auto contents = std::string{std::istreambuf_iterator<char>(is.rdbuf()), {}};
if (is.bad()) throw google::cloud::Status(is.status());
auto os = client.WriteObject(
bucket_name, object_name_2,
g::Options{}.set<gcs::RetryPolicyOption>(
gcs::LimitedTimeRetryPolicy(std::chrono::minutes(5)).clone()));
os << contents;
os.Close();
if (os.bad()) throw google::cloud::Status(os.metadata().status());
auto result = client.DeleteObject(
bucket_name, object_name_1, gcs::Generation(metadata->generation()),
g::Options{}.set<gcs::RetryPolicyOption>(
gcs::LimitedErrorCountRetryPolicy(12).clone()));
if (!result.ok()) throw std::move(metadata).status();
metadata = os.metadata();
result = client.DeleteObject(
bucket_name, object_name_2, gcs::Generation(metadata->generation()),
g::Options{}.set<gcs::RetryPolicyOption>(
gcs::LimitedErrorCountRetryPolicy(12).clone()));
if (!result.ok()) throw std::move(metadata).status();
}
Retry, Backoff, and Idempotency Policies

The library automatically retries requests that fail with transient errors, and follows the recommended practice to backoff between retries.

The default policies are to continue retrying for up to 15 minutes, and to use truncated (at 5 minutes) exponential backoff, doubling the maximum backoff period between retries. Likewise, the idempotency policy is configured to retry all operations.

The application can override these policies when constructing objects of this class. The documentation for the constructors show examples of this in action.

See also
https://cloud.google.com/storage/ for an overview of GCS.
https://cloud.google.com/storage/docs/key-terms for an introduction of the key terms used in GCS.
https://cloud.google.com/storage/docs/json_api/ for an overview of the underlying API.
https://cloud.google.com/docs/authentication/production for details about Application Default Credentials.
google::cloud::StatusOr.
LimitedTimeRetryPolicy and LimitedErrorCountRetryPolicy for alternative retry policies.
ExponentialBackoffPolicy to configure different parameters for the exponential backoff policy.
AlwaysRetryIdempotencyPolicy and StrictIdempotencyPolicy for alternative idempotency policies.

Constructor & Destructor Documentation

◆ Client() [1/5]

google::cloud::storage::Client::Client ( Options  opts = {})
explicit

Build a new client.

Parameters
optsthe configuration parameters for the Client.
See also
ClientOptionList for a list of useful Client Library Configuration.
Idempotency Policy Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](std::string const& bucket_name, std::string const& object_name,
std::string const& contents) {
// Create a client that only retries idempotent operations, the default is
// to retry all operations.
auto client =
gcs::Client(google::cloud::Options{}.set<gcs::IdempotencyPolicyOption>(
gcs::StrictIdempotencyPolicy().clone()));
client.InsertObject(bucket_name, object_name, std::move(contents),
gcs::IfGenerationMatch(0));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Modified Retry Policy Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](std::string const& bucket_name, std::string const& object_name,
std::string const& contents) {
// Create a client that only gives up on the third error. The default policy
// is to retry for several minutes.
auto client =
gcs::Client(google::cloud::Options{}.set<gcs::RetryPolicyOption>(
gcs::LimitedErrorCountRetryPolicy(3).clone()));
client.InsertObject(bucket_name, object_name, std::move(contents),
gcs::IfGenerationMatch(0));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Change Credentials Example
namespace gcs = ::google::cloud::storage;
[](std::string const& filename, std::string const& bucket_name,
std::string const& object_name) {
auto is = std::ifstream(filename);
is.exceptions(std::ios::badbit);
auto json_string =
std::string(std::istreambuf_iterator<char>(is.rdbuf()), {});
auto credentials =
auto client = gcs::Client(
credentials));
PerformSomeOperations(client, bucket_name, object_name);
}

◆ Client() [2/5]

template<typename... Policies>
google::cloud::storage::Client::Client ( ClientOptions  options,
Policies &&...  policies 
)
inlineexplicit

Creates the default client type given the options.

Parameters
optionsthe client options, these are used to control credentials, buffer sizes, etc.
policiesthe client policies, these control the behavior of the client, for example, how to backoff when an operation needs to be retried, or what operations cannot be retried because they are not idempotent.
Deprecated:
use the constructor from google::cloud::Options instead.

◆ Client() [3/5]

template<typename... Policies>
google::cloud::storage::Client::Client ( std::shared_ptr< oauth2::Credentials credentials,
Policies &&...  policies 
)
inlineexplicit

Creates the default client type given the credentials and policies.

Parameters
credentialsa set of credentials to initialize the ClientOptions.
policiesthe client policies, these control the behavior of the client, for example, how to backoff when an operation needs to be retried, or what operations cannot be retried because they are not idempotent.
Deprecated:
use the constructor from google::cloud::Options instead.

◆ Client() [4/5]

template<typename... Policies>
google::cloud::storage::Client::Client ( std::shared_ptr< internal::RawClient >  client,
Policies &&...  policies 
)
inlineexplicit

Builds a client and maybe override the retry, idempotency, and/or backoff policies.

Deprecated:
This was intended only for test code, applications should not use it.

◆ Client() [5/5]

google::cloud::storage::Client::Client ( std::shared_ptr< internal::RawClient >  client,
NoDecorations   
)
inlineexplicit

Builds a client with a specific RawClient, without decorations.

Deprecated:
This was intended only for test code, applications should not use it.

Member Function Documentation

◆ ComposeObject()

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::ComposeObject ( std::string  bucket_name,
std::vector< ComposeSourceObject source_objects,
std::string  destination_object_name,
Options &&...  options 
)
inline

Composes existing objects into a new object in the same bucket.

Parameters
bucket_namethe name of the bucket used for source object and destination object.
source_objectsobjects used to compose destination_object_name.
destination_object_namethe composed object name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfMetagenerationMatch, KmsKeyName, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& destination_object_name,
std::vector<gcs::ComposeSourceObject> const& compose_objects) {
StatusOr<gcs::ObjectMetadata> composed_object = client.ComposeObject(
bucket_name, compose_objects, destination_object_name);
if (!composed_object) throw std::move(composed_object).status();
std::cout << "Composed new object " << composed_object->name()
<< " in bucket " << composed_object->bucket()
<< "\nFull metadata: " << *composed_object << "\n";
}
Example: using encrypted objects with CSEK
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& destination_object_name,
std::string const& base64_aes256_key,
std::vector<gcs::ComposeSourceObject> const& compose_objects) {
StatusOr<gcs::ObjectMetadata> composed_object = client.ComposeObject(
bucket_name, compose_objects, destination_object_name,
gcs::EncryptionKey::FromBase64Key(base64_aes256_key));
if (!composed_object) throw std::move(composed_object).status();
std::cout << "Composed new object " << composed_object->name()
<< " in bucket " << composed_object->bucket()
<< "\nFull metadata: " << *composed_object << "\n";
}

◆ CopyObject()

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::CopyObject ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
Options &&...  options 
)
inline

Copies an existing object.

Use CopyObject to copy between objects in the same location and storage class. Copying objects across locations or storage classes can fail for large objects and retrying the operation will not succeed.

Note
Prefer using RewriteObject() to copy objects, RewriteObject() can copy objects to different locations, with different storage class, and/or with different encryption keys.
Parameters
source_bucket_namethe name of the bucket that contains the object to be copied.
source_object_namethe name of the object to copy.
destination_bucket_namethe name of the bucket that will contain the new object.
destination_object_namethe name of the new object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl,EncryptionKey,IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, Projection, SourceGeneration, SourceEncryptionKey, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name) {
client.CopyObject(source_bucket_name, source_object_name,
destination_bucket_name, destination_object_name);
if (!new_copy_meta) throw std::move(new_copy_meta).status();
std::cout << "Successfully copied " << source_object_name << " in bucket "
<< source_bucket_name << " to bucket " << new_copy_meta->bucket()
<< " with name " << new_copy_meta->name()
<< ".\nThe full metadata after the copy is: " << *new_copy_meta
<< "\n";
}
Example: copy an encrypted object
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name,
std::string const& key_base64) {
StatusOr<gcs::ObjectMetadata> new_copy_meta = client.CopyObject(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name, gcs::EncryptionKey::FromBase64Key(key_base64));
if (!new_copy_meta) throw std::move(new_copy_meta).status();
std::cout << "Successfully copied " << source_object_name << " in bucket "
<< source_bucket_name << " to bucket " << new_copy_meta->bucket()
<< " with name " << new_copy_meta->name()
<< ".\nThe full metadata after the copy is: " << *new_copy_meta
<< "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/objects/copy for a full description of the advantages of Objects: rewrite over Objects: copy.

◆ CreateBucket()

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::CreateBucket ( std::string  bucket_name,
BucketMetadata  metadata,
Options &&...  options 
)
inline

Creates a new Google Cloud Storage bucket using the default project.

If the default project is not configured the server will reject the request, and this function returns the error status.

Parameters
bucket_namethe name of the new bucket.
metadatathe metadata for the new Bucket. The name field is ignored in favor of bucket_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include PredefinedAcl, PredefinedDefaultObjectAcl, Projection, UserProject, and OverrideDefaultProject.
Idempotency
This operation is always idempotent. It fails if the bucket already exists.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.CreateBucket(bucket_name, gcs::BucketMetadata());
if (!bucket_metadata) throw std::move(bucket_metadata).status();
std::cout << "Bucket " << bucket_metadata->name() << " created."
<< "\nFull Metadata: " << *bucket_metadata << "\n";
}
See also
Before enabling Uniform Bucket Level Access please review the feature documentation, as well as "Should you use uniform bucket-level access ?".

◆ CreateBucketAcl()

template<typename... Options>
StatusOr< BucketAccessControl > google::cloud::storage::Client::CreateBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
std::string const &  role,
Options &&...  options 
)
inline

Creates a new entry in a bucket ACL.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
rolethe role of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
client.CreateBucketAcl(bucket_name, entity, role);
if (!bucket_acl) throw std::move(bucket_acl).status();
std::cout << "Role " << bucket_acl->role() << " granted to "
<< bucket_acl->entity() << " on bucket " << bucket_acl->bucket()
<< "\n"
<< "Full attributes: " << *bucket_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ CreateBucketForProject()

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::CreateBucketForProject ( std::string  bucket_name,
std::string  project_id,
BucketMetadata  metadata,
Options &&...  options 
)
inline

Creates a new Google Cloud Storage Bucket in a given project.

Parameters
bucket_namethe name of the new bucket.
project_idthe id of the project that will host the new bucket.
metadatathe metadata for the new Bucket. The name field is ignored in favor of bucket_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject. OverrideDefaultProject is accepted, but has no effect.
Idempotency
This operation is always idempotent. It fails if the bucket already exists.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& project_id) {
client.CreateBucketForProject(bucket_name, project_id,
gcs::BucketMetadata{});
if (!bucket_metadata) throw std::move(bucket_metadata).status();
std::cout << "Bucket " << bucket_metadata->name() << " created for project "
<< project_id << " [" << bucket_metadata->project_number() << "]"
<< "\nFull Metadata: " << *bucket_metadata << "\n";
}
See also
Before enabling Uniform Bucket Level Access please review the feature documentation, as well as "Should you use uniform bucket-level access ?".

◆ CreateDefaultClient()

static StatusOr< Client > google::cloud::storage::Client::CreateDefaultClient ( )
static

◆ CreateDefaultObjectAcl()

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::CreateDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
std::string const &  role,
Options &&...  options 
)
inline

Creates a new entry in the default object ACL for a bucket.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
rolethe role of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
client.CreateDefaultObjectAcl(bucket_name, entity, role);
if (!default_object_acl) throw std::move(default_object_acl).status();
std::cout << "Role " << default_object_acl->role()
<< " will be granted default to " << default_object_acl->entity()
<< " on any new object created on bucket "
<< default_object_acl->bucket() << "\n"
<< "Full attributes: " << *default_object_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ CreateHmacKey()

template<typename... Options>
StatusOr< std::pair< HmacKeyMetadata, std::string > > google::cloud::storage::Client::CreateHmacKey ( std::string  service_account,
Options &&...  options 
)
inline

Create a new HMAC key.

Parameters
service_accountthe service account email where you want to create the new HMAC key.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata and the HMAC key secret (encoded as a base64 string). This is the only request that returns the secret.
Idempotency
This operation is not idempotent. Retrying the operation will create a new key each time.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& service_account_email) {
client.CreateHmacKey(service_account_email);
if (!key_info) throw std::move(key_info).status();
std::cout << "The base64 encoded secret is: " << key_info->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << key_info->first << "\n";
return key_info->first.access_id();
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
return [](gcs::Client client, std::string const& project_id,
std::string const& service_account_email) {
client.CreateHmacKey(service_account_email,
gcs::OverrideDefaultProject(project_id));
if (!hmac_key_details) throw std::move(hmac_key_details).status();
std::cout << "The base64 encoded secret is: " << hmac_key_details->second
<< "\nDo not miss that secret, there is no API to recover it."
<< "\nThe HMAC key metadata is: " << hmac_key_details->first
<< "\n";
return hmac_key_details->first.access_id();
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

◆ CreateNotification() [1/2]

template<typename... Options>
StatusOr< NotificationMetadata > google::cloud::storage::Client::CreateNotification ( std::string const &  bucket_name,
std::string const &  topic_name,
NotificationMetadata  metadata,
Options &&...  options 
)
inline

Creates a new notification config for a Bucket.

Cloud Pub/Sub Notifications send information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options.

Parameters
bucket_namethe name of the bucket.
topic_namethe Google Cloud Pub/Sub topic that will receive the notifications. This requires the full name of the topic, i.e.: projects/<PROJECT_ID>/topics/<TOPIC_ID>.
metadatadefine any optional parameters for the notification, such as the list of event types, or any custom attributes.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& topic_name) {
client.CreateNotification(bucket_name, topic_name,
gcs::NotificationMetadata());
if (!notification) throw std::move(notification).status();
std::cout << "Successfully created notification " << notification->id()
<< " for bucket " << bucket_name << "\n";
std::cout << "Full details for the notification:\n"
<< *notification << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

◆ CreateNotification() [2/2]

template<typename... Options>
StatusOr< NotificationMetadata > google::cloud::storage::Client::CreateNotification ( std::string const &  bucket_name,
std::string const &  topic_name,
std::string const &  payload_format,
NotificationMetadata  metadata,
Options &&...  options 
)
inline

Creates a new notification config for a Bucket.

Cloud Pub/Sub Notifications send information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options.

Parameters
bucket_namethe name of the bucket.
topic_namethe Google Cloud Pub/Sub topic that will receive the notifications. This requires the full name of the topic, i.e.: projects/<PROJECT_ID>/topics/<TOPIC_ID>.
payload_formathow will the data be formatted in the notifications, consider using the helpers in the payload_format namespace, or specify one of the valid formats defined in: https://cloud.google.com/storage/docs/json_api/v1/notifications
metadatadefine any optional parameters for the notification, such as the list of event types, or any custom attributes.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& topic_name) {
client.CreateNotification(bucket_name, topic_name,
gcs::NotificationMetadata());
if (!notification) throw std::move(notification).status();
std::cout << "Successfully created notification " << notification->id()
<< " for bucket " << bucket_name << "\n";
std::cout << "Full details for the notification:\n"
<< *notification << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

◆ CreateObjectAcl()

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::CreateObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
std::string const &  role,
Options &&...  options 
)
inline

Creates a new entry in the object ACL.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe name of the entity added to the ACL.
rolethe role of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
client.CreateObjectAcl(bucket_name, object_name, entity, role);
if (!object_acl) throw std::move(object_acl).status();
std::cout << "Role " << object_acl->role() << " granted to "
<< object_acl->entity() << " on " << object_acl->object()
<< "\nFull attributes: " << *object_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ CreateSignedPolicyDocument()

template<typename... Options>
StatusOr< PolicyDocumentResult > google::cloud::storage::Client::CreateSignedPolicyDocument ( PolicyDocument  document,
Options &&...  options 
)
inline

Create a signed policy document.

Note
The application must ensure that any document created with this function contains valid conditions. This function does not do any error checking, e.g. that a ExactMatchObject() condition contains two elements. Using the provided helper functions can prevent errors.
It is the application's responsibility to construct a POST request based on the value returned by this function. For example, a web application can create a HTML form containing these fields, the result of which is a POST request to GCS.
Parameters
documentthe policy document.
optionsa list of optional parameters, this includes: SigningAccount, and SigningAccountDelegates.
Helper Functions
The following functions create a PolicyDocumentCondition with less opportunities for typos: StartsWith(), ExactMatchObject(), ExactMatch(), ContentLengthRange().
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& signing_account) {
client.CreateSignedPolicyDocument(
gcs::PolicyDocument{
std::chrono::system_clock::now() + std::chrono::minutes(15),
{
gcs::PolicyDocumentCondition::StartsWith("key", ""),
gcs::PolicyDocumentCondition::ExactMatchObject(
"acl", "bucket-owner-read"),
gcs::PolicyDocumentCondition::ExactMatchObject(
"bucket", std::move(bucket_name)),
gcs::PolicyDocumentCondition::ExactMatch("Content-Type",
"image/jpeg"),
gcs::PolicyDocumentCondition::ContentLengthRange(0,
1000000),
}},
gcs::SigningAccount(signing_account));
if (!document) throw std::move(document).status();
std::cout << "The signed document is: " << *document << "\n\n"
<< "You can use this with an HTML form.\n";
}
See also
https://cloud.google.com/storage/docs/xml-api/post-object#policydocument for a general description of policy documents and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

◆ CreateV2SignedUrl()

template<typename... Options>
StatusOr< std::string > google::cloud::storage::Client::CreateV2SignedUrl ( std::string  verb,
std::string  bucket_name,
std::string  object_name,
Options &&...  options 
)
inline

Create a V2 signed URL for the given parameters.

Note
By default URLs created with this function expire after 7 days.
The application must ensure that any URL created with this function is a valid request via the XML API. For example, the options for bucket requests may include a sub-resource (e.g. WithBilling()) but not all sub-resources are valid for objects. Likewise, only a single sub-resource may be retrieved in each request.
Parameters
verbthe operation allowed through this signed URL, GET, POST, PUT, HEAD, etc. are valid values.
bucket_namethe name of the bucket.
object_namethe name of the object, note that the object may not exist for signed URLs that upload new objects. Use an empty string for requests that only affect a bucket.
optionsa list of optional parameters for the signed URL, this include: ExpirationTime, MD5HashValue, ContentType, SigningAccount, SigningAccountDelegates, AddExtensionHeaderOption, AddQueryParameterOption, and AddSubResourceOption. Note that only the last AddSubResourceOption option has any effect.
Helper Functions

The following functions create a AddSubResourceOption with less opportunities for typos in the sub-resource name: WithAcl(), WithBilling(), WithCompose(), WithCors(), WithEncryption(), WithEncryptionConfig(), WithLifecycle(), WithLocation(), WithLogging(), WithStorageClass(), and WithTagging().

Likewise, the following helper functions can create properly formatted AddExtensionHeaderOption objects: WithGeneration(), WithGenerationMarker(), WithMarker(), WithResponseContentDisposition(), WithResponseContentType(), and WithUserProject().

Returns
the signed URL.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& signing_account) {
StatusOr<std::string> signed_url = client.CreateV2SignedUrl(
"GET", std::move(bucket_name), std::move(object_name),
gcs::ExpirationTime(std::chrono::system_clock::now() +
std::chrono::minutes(15)),
gcs::SigningAccount(signing_account));
if (!signed_url) throw std::move(signed_url).status();
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl '" << *signed_url << "'\n";
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& signing_account) {
StatusOr<std::string> signed_url = client.CreateV2SignedUrl(
"PUT", std::move(bucket_name), std::move(object_name),
gcs::ExpirationTime(std::chrono::system_clock::now() +
std::chrono::minutes(15)),
gcs::ContentType("application/octet-stream"),
gcs::SigningAccount(signing_account));
if (!signed_url) throw std::move(signed_url).status();
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl -X PUT -H 'Content-Type: application/octet-stream'"
<< " --upload-file my-file '" << *signed_url << "'\n";
}
See also
https://cloud.google.com/storage/docs/access-control/signed-urls for a general description of signed URLs and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

◆ CreateV4SignedUrl()

template<typename... Options>
StatusOr< std::string > google::cloud::storage::Client::CreateV4SignedUrl ( std::string  verb,
std::string  bucket_name,
std::string  object_name,
Options &&...  options 
)
inline

Create a V4 signed URL for the given parameters.

Note
By default URLs created with this function expire after 7 days.
The application must ensure that any URL created with this function is a valid request via the XML API. For example, the options for bucket requests may include a sub-resource (e.g. WithBilling()) but not all sub-resources are valid for objects. Likewise, only a single sub-resource may be retrieved in each request.
Parameters
verbthe operation allowed through this signed URL, GET, POST, PUT, HEAD, etc. are valid values.
bucket_namethe name of the bucket.
object_namethe name of the object, note that the object may not exist for signed URLs that upload new objects. Use an empty string for requests that only affect a bucket.
optionsa list of optional parameters for the signed URL, this include: SignedUrlTimestamp, SignedUrlDuration, MD5HashValue, ContentType, SigningAccount, SigningAccountDelegates, AddExtensionHeaderOption, AddQueryParameterOption, and AddSubResourceOption. Note that only the last AddSubResourceOption option has any effect.
Helper Functions

The following functions create a AddSubResourceOption with less opportunities for typos in the sub-resource name: WithAcl(), WithBilling(), WithCompose(), WithCors(), WithEncryption(), WithEncryptionConfig(), WithLifecycle(), WithLocation(), WithLogging(), WithStorageClass(), and WithTagging().

Likewise, the following helper functions can create properly formatted AddExtensionHeaderOption objects: WithGeneration(), WithGenerationMarker(), WithMarker(), WithResponseContentDisposition(), WithResponseContentType(), and WithUserProject().

Returns
the signed URL.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& signing_account) {
StatusOr<std::string> signed_url = client.CreateV4SignedUrl(
"GET", std::move(bucket_name), std::move(object_name),
gcs::SignedUrlDuration(std::chrono::minutes(15)),
gcs::SigningAccount(signing_account));
if (!signed_url) throw std::move(signed_url).status();
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl '" << *signed_url << "'\n";
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& signing_account) {
StatusOr<std::string> signed_url = client.CreateV4SignedUrl(
"PUT", std::move(bucket_name), std::move(object_name),
gcs::SignedUrlDuration(std::chrono::minutes(15)),
gcs::AddExtensionHeader("content-type", "application/octet-stream"),
gcs::SigningAccount(signing_account));
if (!signed_url) throw std::move(signed_url).status();
std::cout << "The signed url is: " << *signed_url << "\n\n"
<< "You can use this URL with any user agent, for example:\n"
<< "curl -X PUT -H 'Content-Type: application/octet-stream'"
<< " --upload-file my-file '" << *signed_url << "'\n";
}
See also
https://cloud.google.com/storage/docs/access-control/signed-urls for a general description of signed URLs and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

◆ DeleteBucket()

template<typename... Options>
Status google::cloud::storage::Client::DeleteBucket ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Deletes a Google Cloud Storage Bucket.

Parameters
bucket_namethe bucket to be deleted.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
google::cloud::Status status = client.DeleteBucket(bucket_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "The bucket " << bucket_name << " was deleted successfully.\n";
}
std::string const & message() const

◆ DeleteBucketAcl()

template<typename... Options>
Status google::cloud::storage::Client::DeleteBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Deletes an entry from a bucket ACL.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
google::cloud::Status status = client.DeleteBucketAcl(bucket_name, entity);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted ACL entry for " << entity << " in bucket "
<< bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

◆ DeleteDefaultObjectAcl()

template<typename... Options>
Status google::cloud::storage::Client::DeleteDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Deletes an entry from the default object ACL in a bucket.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity added to the ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
client.DeleteDefaultObjectAcl(bucket_name, entity);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted ACL entry for " << entity << " in bucket "
<< bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

◆ DeleteHmacKey()

template<typename... Options>
Status google::cloud::storage::Client::DeleteHmacKey ( std::string  access_id,
Options &&...  options 
)
inline

Delete a HMAC key in a given project.

Parameters
access_idthe HMAC key access_id() that you want to delete. Each HMAC key is assigned an access_id() attribute at creation time.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata.
Idempotency
This operation is always idempotent. An access id identifies a single HMAC key, calling the operation multiple times can succeed only once.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& access_id) {
google::cloud::Status status = client.DeleteHmacKey(access_id);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "The key is deleted, though it may still appear"
<< " in ListHmacKeys() results.\n";
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

◆ DeleteNotification()

template<typename... Options>
Status google::cloud::storage::Client::DeleteNotification ( std::string const &  bucket_name,
std::string const &  notification_id,
Options &&...  options 
)
inline

Delete an existing notification config in a given Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options. This function deletes one of the notification configs.

Parameters
bucket_namethe name of the bucket.
notification_idthe id of the notification config.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is always idempotent because it only acts on a specific notification_id, the state after calling this function multiple times is to delete that notification. New notifications get different ids.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& notification_id) {
client.DeleteNotification(bucket_name, notification_id);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Successfully deleted notification " << notification_id
<< " on bucket " << bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

◆ DeleteObject()

template<typename... Options>
Status google::cloud::storage::Client::DeleteObject ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Deletes an object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be deleted.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, and UserProject.
Idempotency
This operation is only idempotent if:
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
client.DeleteObject(bucket_name, object_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted " << object_name << " in bucket " << bucket_name
<< "\n";
}

◆ DeleteObjectAcl()

template<typename... Options>
Status google::cloud::storage::Client::DeleteObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
Options &&...  options 
)
inline

Deletes one access control entry in one object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be deleted.
entitythe name of the entity (user, team, group) to be removed from the Object's ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity) {
client.DeleteObjectAcl(bucket_name, object_name, entity);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Deleted ACL entry for " << entity << " in object "
<< object_name << " in bucket " << bucket_name << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

◆ DeleteResumableUpload()

template<typename... Options>
Status google::cloud::storage::Client::DeleteResumableUpload ( std::string const &  upload_session_url,
Options &&...  options 
)
inline

Cancel a resumable upload.

Parameters
upload_session_urlthe url of the upload session. Returned by ObjectWriteStream::resumable_session_id.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is always idempotent because it only acts on a specific upload_session_url.

◆ DownloadToFile()

template<typename... Options>
Status google::cloud::storage::Client::DownloadToFile ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  file_name,
Options &&...  options 
)
inline

Downloads a Cloud Storage object to a file.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be downloaded.
file_namethe name of the destination file that will have the object media.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, Generation, ReadFromOffset, ReadRange, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& file_name) {
client.DownloadToFile(bucket_name, object_name, file_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Downloaded " << object_name << " to " << file_name << "\n";
}

◆ GenerateSignedPostPolicyV4()

template<typename... Options>
StatusOr< PolicyDocumentV4Result > google::cloud::storage::Client::GenerateSignedPostPolicyV4 ( PolicyDocumentV4  document,
Options &&...  options 
)
inline

Create a signed V4 policy document.

Note
The application must ensure that any document created with this function contains valid conditions. This function does not do any error checking, e.g. that a ExactMatchObject() condition contains two elements. Using the provided helper functions can prevent errors.
It is the application's responsibility to construct a POST request based on the value returned by this function. For example, a web application can create a HTML form containing these fields, the result of which is a POST request to GCS.
Parameters
documentthe policy document.
optionsa list of optional parameters, this includes: AddExtensionFieldOption, BucketBoundHostname, PredefinedAcl, Scheme, SigningAccountDelegates, SigningAccount, VirtualHostname
Helper Functions
The following functions create a PolicyDocumentCondition with less opportunities for typos: StartsWith(), ExactMatchObject(), ExactMatch(), ContentLengthRange().
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& signing_account) {
client.GenerateSignedPostPolicyV4(
gcs::PolicyDocumentV4{
std::move(bucket_name),
"scan_0001.jpg",
std::chrono::minutes(15),
std::chrono::system_clock::now(),
{
gcs::PolicyDocumentCondition::StartsWith("key", ""),
gcs::PolicyDocumentCondition::ExactMatchObject(
"acl", "bucket-owner-read"),
gcs::PolicyDocumentCondition::ExactMatch("Content-Type",
"image/jpeg"),
gcs::PolicyDocumentCondition::ContentLengthRange(0,
1000000),
}},
gcs::SigningAccount(signing_account));
if (!document) throw std::move(document).status();
std::cout << "The signed document is: " << *document << "\n\n"
<< "You can use this with an HTML form.\n";
}
See also
https://cloud.google.com/storage/docs/xml-api/post-object#policydocument for a general description of policy documents and how they can be used.
https://cloud.google.com/storage/docs/xml-api/overview for a detailed description of the XML API.

◆ GetBucketAcl()

template<typename... Options>
StatusOr< BucketAccessControl > google::cloud::storage::Client::GetBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Gets the value of an existing bucket ACL.

Parameters
bucket_namethe name of the bucket to query.
entitythe name of the entity to query.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
client.GetBucketAcl(bucket_name, entity);
if (!acl) throw std::move(acl).status();
std::cout << "ACL entry for " << acl->entity() << " in bucket "
<< acl->bucket() << " is " << *acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

◆ GetBucketMetadata()

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::GetBucketMetadata ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Fetches the bucket metadata.

Parameters
bucket_namequery metadata information about this bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, UserProject, and Projection.
Idempotency
This is a read-only operation and is always idempotent.
Example
// [START storage_get_bucket_metadata]
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.GetBucketMetadata(bucket_name);
if (!bucket_metadata) throw std::move(bucket_metadata).status();
std::cout << "The metadata for bucket " << bucket_metadata->name() << " is "
<< *bucket_metadata << "\n";
}
// [END storage_get_bucket_metadata]

◆ GetDefaultObjectAcl()

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::GetDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
Options &&...  options 
)
inline

Gets the value of a default object ACL in a bucket.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
entitythe name of the entity.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity) {
client.GetDefaultObjectAcl(bucket_name, entity);
if (!acl) throw std::move(acl).status();
std::cout << "Default Object ACL entry for " << acl->entity()
<< " in bucket " << acl->bucket() << " is " << *acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.

◆ GetHmacKey()

template<typename... Options>
StatusOr< HmacKeyMetadata > google::cloud::storage::Client::GetHmacKey ( std::string  access_id,
Options &&...  options 
)
inline

Get an existing HMAC key in a given project.

Parameters
access_idthe HMAC key access_id() that you want to delete. Each HMAC key is assigned an access_id() attribute at creation time.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata.
Idempotency
This is a read-only operation and therefore it is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id) {
StatusOr<gcs::HmacKeyMetadata> hmac_key = client.GetHmacKey(access_id);
if (!hmac_key) throw std::move(hmac_key).status();
std::cout << "The HMAC key metadata is: " << *hmac_key << "\n";
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

◆ GetNativeBucketIamPolicy()

template<typename... Options>
StatusOr< NativeIamPolicy > google::cloud::storage::Client::GetNativeBucketIamPolicy ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Fetches the native IAM policy for a Bucket.

Google Cloud Identity & Access Management (IAM) lets administrators authorize who can take action on specific resources, including Google Cloud Storage Buckets. This operation allows you to query the IAM policies for a Bucket. IAM policies are a superset of the Bucket ACL, changes to the Bucket ACL are reflected in the IAM policy, and vice-versa. The documentation describes the mapping between legacy Bucket ACLs and IAM policies.

Consult the documentation for a more detailed description of IAM policies and their use in Google Cloud Storage.

Parameters
bucket_namequery metadata information about this bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
auto policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3));
if (!policy) throw std::move(policy).status();
std::cout << "The IAM policy for bucket " << bucket_name << " is "
<< *policy << "\n";
}
See also
google::cloud::storage::NativeIamPolicy for details about the NativeIamPolicy class.

◆ GetNotification()

template<typename... Options>
StatusOr< NotificationMetadata > google::cloud::storage::Client::GetNotification ( std::string const &  bucket_name,
std::string const &  notification_id,
Options &&...  options 
)
inline

Gets the details about a notification config in a given Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service. You can create multiple notifications per Bucket, with different topics and filtering options. This function fetches the detailed information for a given notification config.

Parameters
bucket_namethe name of the bucket.
notification_idthe id of the notification config.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& notification_id) {
client.GetNotification(bucket_name, notification_id);
if (!notification) throw std::move(notification).status();
std::cout << "Notification " << notification->id() << " for bucket "
<< bucket_name << "\n";
if (notification->object_name_prefix().empty()) {
std::cout << "This notification is sent for all objects in the bucket\n";
} else {
std::cout << "This notification is sent only for objects starting with"
<< " the prefix " << notification->object_name_prefix() << "\n";
}
std::cout << "Full details for the notification:\n"
<< *notification << "\n";
}
See also
https://cloud.google.com/storage/docs/pubsub-notifications for general information on Cloud Pub/Sub Notifications for Google Cloud Storage.
https://cloud.google.com/pubsub/ for general information on Google Cloud Pub/Sub service.

◆ GetObjectAcl()

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::GetObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
Options &&...  options 
)
inline

Gets the value of an existing object ACL.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe name of the entity added to the ACL.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity) {
client.GetObjectAcl(bucket_name, object_name, entity);
if (!acl) throw std::move(acl).status();
std::cout << "ACL entry for " << acl->entity() << " in object "
<< acl->object() << " in bucket " << acl->bucket() << " is "
<< *acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

◆ GetObjectMetadata()

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::GetObjectMetadata ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Fetches the object metadata.

Parameters
bucket_namethe bucket containing the object.
object_namethe object name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, Projection, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
client.GetObjectMetadata(bucket_name, object_name);
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The metadata for object " << object_metadata->name()
<< " in bucket " << object_metadata->bucket() << " is "
<< *object_metadata << "\n";
}

◆ GetServiceAccount()

template<typename... Options>
StatusOr< ServiceAccount > google::cloud::storage::Client::GetServiceAccount ( Options &&...  options)
inline

Gets the GCS service account for the default project.

A service account is a special Google account that belongs to your application, virtual machine, or to a Google service when acting on your behalf. This API allows you to discover the GCS service account for the default project associated with this object.

The default project is required to be configured in the ClientOptions used to construct this object. If the application does not set the project id in the ClientOptions, the value of the GOOGLE_CLOUD_PROJECT is used. If neither the environment variable is set, nor a value is set explicitly by the application, the server will reject the request and this function will return the error status.

Parameters
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, and OverrideDefaultProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
StatusOr<gcs::ServiceAccount> account = client.GetServiceAccount();
if (!account) throw std::move(account).status();
std::cout << "The service account details are " << *account << "\n";
}
See also
https://cloud.google.com/iam/docs/service-accounts for general information on Google Cloud Platform service accounts.

◆ GetServiceAccountForProject()

template<typename... Options>
StatusOr< ServiceAccount > google::cloud::storage::Client::GetServiceAccountForProject ( std::string const &  project_id,
Options &&...  options 
)
inline

Gets the GCS service account for a given project.

A service account is a special Google account that belongs to your application, virtual machine, or to a Google service when acting on your behalf. This API allows you to discover the GCS service account for the project_id project.

Parameters
project_idthe project to query.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject. OverrideDefaultProject is accepted, but has no effect.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id) {
client.GetServiceAccountForProject(project_id);
if (!account) throw std::move(account).status();
std::cout << "The service account details for project " << project_id
<< " are " << *account << "\n";
}
See also
https://cloud.google.com/iam/docs/service-accounts for general information on Google Cloud Platform service accounts.

◆ InsertObject() [1/3]

template<typename... Options>
google::cloud::storage::Client::InsertObject ( std::string const &  bucket_name,
std::string const &  object_name,
absl::string_view  contents,
Options &&...  options 
)
inline

Creates an object given its name and contents.

Parameters
bucket_namethe name of the bucket that will contain the object.
object_namethe name of the object to be created.
contentsthe contents (media) for the new object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include ContentEncoding, ContentType, Crc32cChecksumValue, DisableCrc32cChecksum, DisableMD5Hash, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, KmsKeyName, MD5HashValue, PredefinedAcl, Projection, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& contents) {
client.InsertObject(bucket_name, object_name, std::move(contents));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& content_type,
std::string const& contents) {
// Setting the object metadata (via the `gcs::WithObjectMadata` option)
// requires a multipart upload, the library prefers simple uploads unless
// required as in this case.
StatusOr<gcs::ObjectMetadata> object_metadata = client.InsertObject(
bucket_name, object_name, std::move(contents),
gcs::WithObjectMetadata(
gcs::ObjectMetadata().set_content_type(content_type)));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nThe contentType was set to "
<< object_metadata->content_type()
<< "\nFull metadata: " << *object_metadata << "\n";
}

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ InsertObject() [2/3]

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::InsertObject ( std::string const &  bucket_name,
std::string const &  object_name,
char const *  contents,
Options &&...  options 
)
inline

Creates an object given its name and contents.

Parameters
bucket_namethe name of the bucket that will contain the object.
object_namethe name of the object to be created.
contentsthe contents (media) for the new object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include ContentEncoding, ContentType, Crc32cChecksumValue, DisableCrc32cChecksum, DisableMD5Hash, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, KmsKeyName, MD5HashValue, PredefinedAcl, Projection, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& contents) {
client.InsertObject(bucket_name, object_name, std::move(contents));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& content_type,
std::string const& contents) {
// Setting the object metadata (via the `gcs::WithObjectMadata` option)
// requires a multipart upload, the library prefers simple uploads unless
// required as in this case.
StatusOr<gcs::ObjectMetadata> object_metadata = client.InsertObject(
bucket_name, object_name, std::move(contents),
gcs::WithObjectMetadata(
gcs::ObjectMetadata().set_content_type(content_type)));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nThe contentType was set to "
<< object_metadata->content_type()
<< "\nFull metadata: " << *object_metadata << "\n";
}

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ InsertObject() [3/3]

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::InsertObject ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  contents,
Options &&...  options 
)
inline

Creates an object given its name and contents.

Parameters
bucket_namethe name of the bucket that will contain the object.
object_namethe name of the object to be created.
contentsthe contents (media) for the new object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include ContentEncoding, ContentType, Crc32cChecksumValue, DisableCrc32cChecksum, DisableMD5Hash, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, KmsKeyName, MD5HashValue, PredefinedAcl, Projection, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& contents) {
client.InsertObject(bucket_name, object_name, std::move(contents));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nFull metadata: " << *object_metadata << "\n";
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& content_type,
std::string const& contents) {
// Setting the object metadata (via the `gcs::WithObjectMadata` option)
// requires a multipart upload, the library prefers simple uploads unless
// required as in this case.
StatusOr<gcs::ObjectMetadata> object_metadata = client.InsertObject(
bucket_name, object_name, std::move(contents),
gcs::WithObjectMetadata(
gcs::ObjectMetadata().set_content_type(content_type)));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "The object " << object_metadata->name()
<< " was created in bucket " << object_metadata->bucket()
<< "\nThe contentType was set to "
<< object_metadata->content_type()
<< "\nFull metadata: " << *object_metadata << "\n";
}

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ ListBucketAcl()

template<typename... Options>
StatusOr< std::vector< BucketAccessControl > > google::cloud::storage::Client::ListBucketAcl ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Retrieves the list of BucketAccessControl items for a bucket.

Parameters
bucket_namethe name of the bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.ListBucketAcl(bucket_name);
if (!items) throw std::move(items).status();
std::cout << "ACLs for bucket=" << bucket_name << "\n";
for (gcs::BucketAccessControl const& acl : *items) {
std::cout << acl.role() << ":" << acl.entity() << "\n";
}
}

◆ ListBuckets()

template<typename... Options>
ListBucketsReader google::cloud::storage::Client::ListBuckets ( Options &&...  options)
inline

Fetches the list of buckets for the default project.

The default project is required to be configured in the ClientOptions used to construct this object. If the application does not set the project id in the ClientOptions, the value of the GOOGLE_CLOUD_PROJECT is used. If neither the environment variable is set, nor a value is set explicitly by the application, the returned ListBucketsReader will return an error status when used.

Parameters
optionsa list of optional query parameters and/or request headers. Valid types for this operation include MaxResults, Prefix, Projection, UserProject, and OverrideDefaultProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
int count = 0;
gcs::ListBucketsReader bucket_list = client.ListBuckets();
for (auto&& bucket_metadata : bucket_list) {
if (!bucket_metadata) throw std::move(bucket_metadata).status();
std::cout << bucket_metadata->name() << "\n";
++count;
}
if (count == 0) {
std::cout << "No buckets in default project\n";
}
}

◆ ListBucketsForProject()

template<typename... Options>
ListBucketsReader google::cloud::storage::Client::ListBucketsForProject ( std::string const &  project_id,
Options &&...  options 
)
inline

Fetches the list of buckets for a given project.

Parameters
project_idthe project to query.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include MaxResults, Prefix, Projection, and UserProject. OverrideDefaultProject is accepted, but has no effect.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& project_id) {
int count = 0;
for (auto&& bucket_metadata : client.ListBucketsForProject(project_id)) {
if (!bucket_metadata) throw std::move(bucket_metadata).status();
std::cout << bucket_metadata->name() << "\n";
++count;
}
if (count == 0) {
std::cout << "No buckets in project " << project_id << "\n";
}
}

◆ ListDefaultObjectAcl()

template<typename... Options>
StatusOr< std::vector< ObjectAccessControl > > google::cloud::storage::Client::ListDefaultObjectAcl ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Retrieves the default object ACL for a bucket as a vector of ObjectAccessControl items.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Parameters
bucket_namethe name of the bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.ListDefaultObjectAcl(bucket_name);
if (!items) throw std::move(items).status();
std::cout << "ACLs for bucket=" << bucket_name << "\n";
for (gcs::ObjectAccessControl const& acl : *items) {
std::cout << acl.role() << ":" << acl.entity() << "\n";
}
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects

◆ ListHmacKeys()

template<typename... Options>
ListHmacKeysReader google::cloud::storage::Client::ListHmacKeys ( Options &&...  options)
inline

List the available HMAC keys.

Warning
This GCS feature is not GA, it is subject to change without notice.
Parameters
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts Deleted MaxResults, OverrideDefaultProject, and ServiceAccountFilter.
Returns
A range to iterate over the available HMAC keys.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list = client.ListHmacKeys();
for (auto& key : hmac_keys_list) {
if (!key) throw std::move(key).status();
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys in default project\n";
}
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& service_account) {
int count = 0;
gcs::ListHmacKeysReader hmac_keys_list =
client.ListHmacKeys(gcs::ServiceAccountFilter(service_account));
for (auto& key : hmac_keys_list) {
if (!key) throw std::move(key).status();
std::cout << "service_account_email = " << key->service_account_email()
<< "\naccess_id = " << key->access_id() << "\n";
++count;
}
if (count == 0) {
std::cout << "No HMAC keys for service account " << service_account
<< " in default project\n";
}
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

◆ ListNotifications()

template<typename... Options>
StatusOr< std::vector< NotificationMetadata > > google::cloud::storage::Client::ListNotifications ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Retrieves the list of Notifications for a Bucket.

Cloud Pub/Sub Notifications sends information about changes to objects in your buckets to Google Cloud Pub/Sub service.

Parameters
bucket_namethe name of the bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.ListNotifications(bucket_name);
if (!items) throw std::move(items).status();
std::cout << "Notifications for bucket=" << bucket_name << "\n";
for (gcs::NotificationMetadata const& notification : *items) {
std::cout << notification << "\n";
}
}

◆ ListObjectAcl()

template<typename... Options>
StatusOr< std::vector< ObjectAccessControl > > google::cloud::storage::Client::ListObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Retrieves the list of ObjectAccessControl items for an object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be deleted.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, and UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
client.ListObjectAcl(bucket_name, object_name);
if (!items) throw std::move(items).status();
std::cout << "ACLs for object=" << object_name << " in bucket "
<< bucket_name << "\n";
for (gcs::ObjectAccessControl const& acl : *items) {
std::cout << acl.role() << ":" << acl.entity() << "\n";
}
}

◆ ListObjects()

template<typename... Options>
ListObjectsReader google::cloud::storage::Client::ListObjects ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Lists the objects in a bucket.

Parameters
bucket_namethe name of the bucket to list.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include MaxResults, Prefix, Delimiter, IncludeTrailingDelimiter, StartOffset, EndOffset, Projection, UserProject, and Versions.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name) {
for (auto&& object_metadata : client.ListObjects(bucket_name)) {
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "bucket_name=" << object_metadata->bucket()
<< ", object_name=" << object_metadata->name() << "\n";
}
}

◆ ListObjectsAndPrefixes()

template<typename... Options>
ListObjectsAndPrefixesReader google::cloud::storage::Client::ListObjectsAndPrefixes ( std::string const &  bucket_name,
Options &&...  options 
)
inline

Lists the objects and prefixes in a bucket.

Parameters
bucket_namethe name of the bucket to list.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, UserProject, Projection, Prefix, Delimiter, IncludeTrailingDelimiter, StartOffset, EndOffset, and Versions.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& bucket_prefix) {
for (auto&& item : client.ListObjectsAndPrefixes(
bucket_name, gcs::Prefix(bucket_prefix), gcs::Delimiter("/"))) {
if (!item) throw std::move(item).status();
auto result = *std::move(item);
if (absl::holds_alternative<gcs::ObjectMetadata>(result)) {
std::cout << "object_name="
<< absl::get<gcs::ObjectMetadata>(result).name() << "\n";
} else if (absl::holds_alternative<std::string>(result)) {
std::cout << "prefix =" << absl::get<std::string>(result) << "\n";
}
}
}

◆ LockBucketRetentionPolicy()

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::LockBucketRetentionPolicy ( std::string const &  bucket_name,
std::uint64_t  metageneration,
Options &&...  options 
)
inline

Locks the retention policy for a bucket.

Warning
Locking a retention policy is an irreversible action. Once locked, you must delete the entire bucket in order to "remove" the bucket's retention policy. However, before you can delete the bucket, you must be able to delete all the objects in the bucket, which itself is only possible if all the objects have reached the retention period set by the retention policy.

The Bucket Lock feature allows you to configure a data retention policy for a Cloud Storage bucket that governs how long objects in the bucket must be retained. The feature also allows you to lock the data retention policy, permanently preventing the policy from being reduced or removed.

Parameters
bucket_namethe name of the bucket.
metagenerationthe expected value of the metageneration on the bucket. The request will fail if the metageneration does not match the current value.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is always idempotent because the metageneration parameter is always required, and it acts as a pre-condition on the operation.
Example: lock the retention policy
// [START storage_lock_retention_policy]
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.GetBucketMetadata(bucket_name);
if (!original) throw std::move(original).status();
StatusOr<gcs::BucketMetadata> updated_metadata =
client.LockBucketRetentionPolicy(bucket_name,
original->metageneration());
if (!updated_metadata) throw std::move(updated_metadata).status();
if (!updated_metadata->has_retention_policy()) {
std::cerr << "The bucket " << updated_metadata->name()
<< " does not have a retention policy, even though the"
<< " operation to set it was successful.\n"
<< "This is unexpected, and may indicate that another"
<< " application has modified the bucket concurrently.\n";
return;
}
std::cout << "Retention policy successfully locked for bucket "
<< updated_metadata->name() << "\nNew retention policy is: "
<< updated_metadata->retention_policy()
<< "\nFull metadata: " << *updated_metadata << "\n";
}
// [END storage_lock_retention_policy]
Example: get the current retention policy
// [START storage_get_retention_policy]
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.GetBucketMetadata(bucket_name);
if (!bucket_metadata) throw std::move(bucket_metadata).status();
if (!bucket_metadata->has_retention_policy()) {
std::cout << "The bucket " << bucket_metadata->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << bucket_metadata->name()
<< " retention policy is set to "
<< bucket_metadata->retention_policy() << "\n";
}
// [END storage_get_retention_policy]
Example: set the current retention policy
// [START storage_set_retention_policy]
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::chrono::seconds period) {
client.GetBucketMetadata(bucket_name);
if (!original) throw std::move(original).status();
StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetRetentionPolicy(period),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched) throw std::move(patched).status();
if (!patched->has_retention_policy()) {
std::cout << "The bucket " << patched->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched->name()
<< " retention policy is set to " << patched->retention_policy()
<< "\n";
}
// [END storage_set_retention_policy]
Example: remove the retention policy
// [START storage_remove_retention_policy]
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
client.GetBucketMetadata(bucket_name);
if (!original) throw std::move(original).status();
StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
bucket_name, gcs::BucketMetadataPatchBuilder().ResetRetentionPolicy(),
gcs::IfMetagenerationMatch(original->metageneration()));
if (!patched) throw std::move(patched).status();
if (!patched->has_retention_policy()) {
std::cout << "The bucket " << patched->name()
<< " does not have a retention policy set.\n";
return;
}
std::cout << "The bucket " << patched->name()
<< " retention policy is set to " << patched->retention_policy()
<< ". This is unexpected, maybe a concurrent change by another"
<< " application?\n";
}
// [END storage_remove_retention_policy]
See also
https://cloud.google.com/storage/docs/bucket-lock for a description of the Bucket Lock feature.
https://cloud.google.com/storage/docs/using-bucket-lock for examples of how to use the Bucket Lock and retention policy features.

◆ PatchBucket() [1/2]

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::PatchBucket ( std::string  bucket_name,
BucketMetadata const &  original,
BucketMetadata const &  updated,
Options &&...  options 
)
inline

Computes the difference between two BucketMetadata objects and patches a bucket based on that difference.

A Buckets: update request changes all the writeable attributes of a bucket, in contrast, a Buckets: patch request only changes the subset of the attributes included in the request.

This function creates a patch request to change the writeable attributes in original to the values in updated. Non-writeable attributes are ignored, and attributes not present in updated are removed. Typically this function is used after the application obtained a value with GetBucketMetadata and has modified these parameters.

Parameters
bucket_namethe bucket to be updated.
originalthe initial value of the bucket metadata.
updatedthe updated value for the bucket metadata.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& storage_class) {
client.GetBucketMetadata(bucket_name);
if (!original) throw std::move(original).status();
gcs::BucketMetadata desired = *original;
desired.set_storage_class(storage_class);
client.PatchBucket(bucket_name, *original, desired);
if (!patched) throw std::move(patched).status();
std::cout << "Storage class for bucket " << patched->name()
<< " has been patched to " << patched->storage_class() << "."
<< "\nFull metadata: " << *patched << "\n";
}
See also
Before enabling Uniform Bucket Level Access please review the feature documentation, as well as "Should you use uniform bucket-level access?".

◆ PatchBucket() [2/2]

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::PatchBucket ( std::string  bucket_name,
BucketMetadataPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the metadata in a Google Cloud Storage Bucket given a desired set changes.

A Buckets: update request changes all the writeable attributes of a bucket, in contrast, a Buckets: patch request only changes the subset of the attributes included in the request. This function creates a patch request based on the given BucketMetadataPatchBuilder which represents the desired set of changes.

Parameters
bucket_namethe bucket to be updated.
builderthe set of updates to perform in the Bucket.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& storage_class) {
StatusOr<gcs::BucketMetadata> patched = client.PatchBucket(
bucket_name,
gcs::BucketMetadataPatchBuilder().SetStorageClass(storage_class));
if (!patched) throw std::move(patched).status();
std::cout << "Storage class for bucket " << patched->name()
<< " has been patched to " << patched->storage_class() << "."
<< "\nFull metadata: " << *patched << "\n";
}
See also
Before enabling Uniform Bucket Level Access please review the feature documentation, as well as "Should you use uniform bucket-level access ?".

◆ PatchBucketAcl() [1/2]

template<typename... Options>
StatusOr< BucketAccessControl > google::cloud::storage::Client::PatchBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
BucketAccessControl const &  original_acl,
BucketAccessControl const &  new_acl,
Options &&...  options 
)
inline

Patches the value of an existing bucket ACL.

Computes the delta between a previous value for an BucketAccessControl and the new value for an BucketAccessControl and apply that delta.

Note
For changing BucketAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
original_aclthe original ACL value.
new_aclthe new ACL value. Note that only changes on writeable fields will be accepted by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, and the standard options available to all operations.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
client.GetBucketAcl(bucket_name, entity);
if (!original_acl) throw std::move(original_acl).status();
auto new_acl = *original_acl;
new_acl.set_role(role);
client.PatchBucketAcl(bucket_name, entity, *original_acl, new_acl);
if (!patched_acl) throw std::move(patched_acl).status();
std::cout << "ACL entry for " << patched_acl->entity() << " in bucket "
<< patched_acl->bucket() << " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls for additional details on what fields are writeable.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

◆ PatchBucketAcl() [2/2]

template<typename... Options>
StatusOr< BucketAccessControl > google::cloud::storage::Client::PatchBucketAcl ( std::string const &  bucket_name,
std::string const &  entity,
BucketAccessControlPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the value of an existing bucket ACL.

This API allows the application to patch an BucketAccessControl without having to read the current value.

Note
For changing BucketAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
buildera builder ready to create the patch.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, UserProject, IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
StatusOr<gcs::BucketAccessControl> patched_acl = client.PatchBucketAcl(
bucket_name, entity,
gcs::BucketAccessControlPatchBuilder().set_role(role));
if (!patched_acl) throw std::move(patched_acl).status();
std::cout << "ACL entry for " << patched_acl->entity() << " in bucket "
<< patched_acl->bucket() << " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls for additional details on what fields are writeable.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.

◆ PatchDefaultObjectAcl() [1/2]

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::PatchDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
ObjectAccessControl const &  original_acl,
ObjectAccessControl const &  new_acl,
Options &&...  options 
)
inline

Patches the value of an existing default object ACL.

Compute the delta between a previous and new values for a default object access control, and apply that delta.

Note
For changing default object access controls, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
original_aclthe original ACL value.
new_aclthe new ACL value. Note that only changes on writeable fields will be accepted by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, as well as the standard parameters, such as IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
client.GetDefaultObjectAcl(bucket_name, entity);
if (!original_acl) throw std::move(original_acl).status();
auto new_acl = *original_acl;
new_acl.set_role(role);
client.PatchDefaultObjectAcl(bucket_name, entity, *original_acl,
new_acl);
if (!patched_acl) throw std::move(patched_acl).status();
std::cout << "Default Object ACL entry for " << patched_acl->entity()
<< " in bucket " << patched_acl->bucket() << " is now "
<< *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ PatchDefaultObjectAcl() [2/2]

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::PatchDefaultObjectAcl ( std::string const &  bucket_name,
std::string const &  entity,
ObjectAccessControlPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the value of an existing default object ACL.

This API allows the application to patch an ObjectAccessControl without having to read the current value.

Note
For changing default object access controls, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
buildera builder ready to create the patch.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject, as well as the standard parameters, such as IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
client.PatchDefaultObjectAcl(
bucket_name, entity,
gcs::ObjectAccessControlPatchBuilder().set_role(role));
if (!patched_acl) throw std::move(patched_acl).status();
std::cout << "Default Object ACL entry for " << patched_acl->entity()
<< " in bucket " << patched_acl->bucket() << " is now "
<< *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ PatchObject() [1/2]

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::PatchObject ( std::string  bucket_name,
std::string  object_name,
ObjectMetadata const &  original,
ObjectMetadata const &  updated,
Options &&...  options 
)
inline

Patches the metadata in a Google Cloud Storage Object.

This function creates a patch request to change the writeable attributes in original to the values in updated. Non-writeable attributes are ignored, and attributes not present in updated are removed. Typically this function is used after the application obtained a value with GetObjectMetadata and has modified these parameters.

Parameters
bucket_namethe bucket that contains the object to be updated.
object_namethe object to be updated.
originalthe initial value of the object metadata.
updatedthe updated value for the object metadata.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& key) {
client.GetObjectMetadata(bucket_name, object_name);
if (!original) throw std::move(original).status();
gcs::ObjectMetadata desired = *original;
desired.mutable_metadata().erase(key);
client.PatchObject(bucket_name, object_name, *original, desired);
if (!updated) throw std::move(updated).status();
std::cout << "Object updated. The full metadata after the update is: "
<< *updated << "\n";
}

◆ PatchObject() [2/2]

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::PatchObject ( std::string  bucket_name,
std::string  object_name,
ObjectMetadataPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the metadata in a Google Cloud Storage Object.

This function creates a patch request based on the given builder. Typically this function is used when the application needs to set an object's metadata fields regardless of their previous value (i.e. when calling GetObjectMetadata first is not necessary).

Parameters
bucket_namethe bucket that contains the object to be updated.
object_namethe object to be updated.
builderthe set of updates to perform in the Object metadata.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, EncryptionKey, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& content_type) {
StatusOr<gcs::ObjectMetadata> updated = client.PatchObject(
bucket_name, object_name,
gcs::ObjectMetadataPatchBuilder().SetContentType(content_type));
if (!updated) throw std::move(updated).status();
std::cout << "Object updated. The full metadata after the update is: "
<< *updated << "\n";
}

◆ PatchObjectAcl() [1/2]

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::PatchObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
ObjectAccessControl const &  original_acl,
ObjectAccessControl const &  new_acl,
Options &&...  options 
)
inline

Patches the value of an existing object ACL.

Compute the delta between a previous value for an ObjectAccessControl and the new value for an ObjectAccessControl and apply that delta.

Note
For changing ObjectAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
original_aclthe original ACL value.
new_aclthe new ACL value. Note that only changes on writeable fields will be accepted by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, UserProject, IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
client.GetObjectAcl(bucket_name, object_name, entity);
if (!original_acl) throw std::move(original_acl).status();
gcs::ObjectAccessControl new_acl = *original_acl;
new_acl.set_role(role);
StatusOr<gcs::ObjectAccessControl> patched_acl = client.PatchObjectAcl(
bucket_name, object_name, entity, *original_acl, new_acl);
if (!patched_acl) throw std::move(patched_acl).status();
std::cout << "ACL entry for " << patched_acl->entity() << " in object "
<< patched_acl->object() << " in bucket " << patched_acl->bucket()
<< " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls for additional details on what fields are writeable.

◆ PatchObjectAcl() [2/2]

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::PatchObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
std::string const &  entity,
ObjectAccessControlPatchBuilder const &  builder,
Options &&...  options 
)
inline

Patches the value of an existing object ACL.

This API allows the application to patch an ObjectAccessControl without having to read the current value.

Note
For changing ObjectAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
entitythe identifier for the user, group, service account, or predefined set of actors holding the permission.
buildera builder ready to create the patch.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, UserProject, IfMatchEtag, and IfNoneMatchEtag.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
StatusOr<gcs::ObjectAccessControl> patched_acl = client.PatchObjectAcl(
bucket_name, object_name, entity,
gcs::ObjectAccessControlPatchBuilder().set_role(role));
if (!patched_acl) throw std::move(patched_acl).status();
std::cout << "ACL entry for " << patched_acl->entity() << " in object "
<< patched_acl->object() << " in bucket " << patched_acl->bucket()
<< " is now " << *patched_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls for additional details on what fields are writeable.

◆ raw_client()

std::shared_ptr< internal::RawClient > google::cloud::storage::Client::raw_client ( ) const
inline

Access the underlying RawClient.

Deprecated:
Only intended for implementors, do not use.

◆ ReadObject()

template<typename... Options>
ObjectReadStream google::cloud::storage::Client::ReadObject ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Reads the contents of an object.

Returns an object derived from std::istream which can be used to read the contents of the GCS blob. The application should check the badbit (e.g. by calling stream.bad()) on the returned object to detect if there was an error reading from the blob. If badbit is set, the application can check the status() variable to get details about the failure. Applications can also set the exception mask on the returned stream, in which case an exception is thrown if an error is detected.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be read.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DisableCrc32cChecksum, DisableMD5Hash, EncryptionKey, Generation, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, ReadFromOffset, ReadRange, ReadLast, UserProject, and AcceptEncoding.
Idempotency
This is a read-only operation and is always idempotent.
Example
// [START storage_stream_file_download]
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
gcs::ObjectReadStream stream = client.ReadObject(bucket_name, object_name);
int count = 0;
std::string line;
while (std::getline(stream, line, '\n')) {
++count;
}
std::cout << "The object has " << count << " lines\n";
}
// [END storage_stream_file_download]
Example: read only a sub-range in the object.
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::int64_t start, std::int64_t end) {
gcs::ObjectReadStream stream =
client.ReadObject(bucket_name, object_name, gcs::ReadRange(start, end));
int count = 0;
std::string line;
while (std::getline(stream, line, '\n')) {
std::cout << line << "\n";
++count;
}
std::cout << "The requested range has " << count << " lines\n";
}
Example: read a object encrypted with a CSEK.
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& base64_aes256_key) {
gcs::ObjectReadStream stream =
client.ReadObject(bucket_name, object_name,
gcs::EncryptionKey::FromBase64Key(base64_aes256_key));
std::string data(std::istreambuf_iterator<char>{stream}, {});
std::cout << "The object contents are: " << data << "\n";
}
Example: disable decompressive transcoding.
namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
auto is =
client.ReadObject(bucket_name, object_name, gcs::AcceptEncodingGzip());
auto const contents = std::string{std::istream_iterator<char>(is), {}};
if (!is.status().ok()) throw google::cloud::Status(is.status());
std::cout << "The object has " << contents.size() << " characters\n";
}

◆ ResumeRewriteObject()

template<typename... Options>
ObjectRewriter google::cloud::storage::Client::ResumeRewriteObject ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
std::string  rewrite_token,
Options &&...  options 
)
inline

Creates an ObjectRewriter to resume a previously created rewrite.

Applications use this function to resume a rewrite operation, possibly created with RewriteObject(). Rewrite can reliably copy objects across location boundaries, and can rewrite objects with different encryption keys. For large objects this operation can take a long time, thus applications should consider checkpointing the rewrite token (accessible in the ObjectRewriter) and restarting the operation in the event the program is terminated.

Note
Application developers should be aware that rewriting large objects may take multiple hours. Multiple calls to ObjectRewriter::Iterate() may be required to completely rewrite an object.
Parameters
source_bucket_namethe name of the bucket containing the source object.
source_object_namethe name of the source object.
destination_bucket_namewhere the destination object will be located.
destination_object_namewhat to name the destination object.
rewrite_tokenthe token from a previous successful rewrite iteration. Can be the empty string, in which case this starts a new rewrite operation.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey, SourceGeneration, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name,
std::string const& rewrite_token) {
gcs::ObjectRewriter rewriter = client.ResumeRewriteObject(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name, rewrite_token,
gcs::MaxBytesRewrittenPerCall(1024 * 1024));
auto callback = [](StatusOr<gcs::RewriteProgress> progress) {
if (!progress) throw std::move(progress).status();
std::cout << "Rewrote " << progress->total_bytes_rewritten << "/"
<< progress->object_size << "\n";
};
rewriter.ResultWithProgressCallback(std::move(callback));
if (!metadata) throw std::move(metadata).status();
std::cout << "Rewrote object " << metadata->name() << " in bucket "
<< metadata->bucket() << "\nFull Metadata: " << *metadata << "\n";
}

◆ RewriteObject()

template<typename... Options>
ObjectRewriter google::cloud::storage::Client::RewriteObject ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
Options &&...  options 
)
inline

Creates an ObjectRewriter to copy the source object.

Applications use this function to reliably copy objects across location boundaries, and to rewrite objects with different encryption keys. The operation returns a ObjectRewriter, which the application can use to initiate the copy and to iterate if the copy requires more than one call to complete.

Note
Application developers should be aware that rewriting large objects may take multiple hours. Multiple calls to ObjectRewriter::Iterate() may be required to completely rewrite an object.
Parameters
source_bucket_namethe name of the bucket containing the source object.
source_object_namethe name of the source object.
destination_bucket_namewhere the destination object will be located.
destination_object_namewhat to name the destination object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey, SourceGeneration, UserProject, and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name) {
gcs::ObjectRewriter rewriter =
client.RewriteObject(source_bucket_name, source_object_name,
destination_bucket_name, destination_object_name);
auto callback = [](StatusOr<gcs::RewriteProgress> progress) {
if (!progress) throw std::move(progress).status();
std::cout << "Rewrote " << progress->total_bytes_rewritten << "/"
<< progress->object_size << "\n";
};
rewriter.ResultWithProgressCallback(std::move(callback));
if (!metadata) throw std::move(metadata).status();
std::cout << "Rewrote object " << metadata->name() << " in bucket "
<< metadata->bucket() << "\nFull Metadata: " << *metadata << "\n";
}
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name,
std::string const& rewrite_token) {
gcs::ObjectRewriter rewriter = client.ResumeRewriteObject(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name, rewrite_token,
gcs::MaxBytesRewrittenPerCall(1024 * 1024));
auto callback = [](StatusOr<gcs::RewriteProgress> progress) {
if (!progress) throw std::move(progress).status();
std::cout << "Rewrote " << progress->total_bytes_rewritten << "/"
<< progress->object_size << "\n";
};
rewriter.ResultWithProgressCallback(std::move(callback));
if (!metadata) throw std::move(metadata).status();
std::cout << "Rewrote object " << metadata->name() << " in bucket "
<< metadata->bucket() << "\nFull Metadata: " << *metadata << "\n";
}

◆ RewriteObjectBlocking()

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::RewriteObjectBlocking ( std::string  source_bucket_name,
std::string  source_object_name,
std::string  destination_bucket_name,
std::string  destination_object_name,
Options &&...  options 
)
inline

Rewrites the object, blocking until the rewrite completes, and returns the resulting ObjectMetadata.

Applications use this function to reliably copy objects across location boundaries, and to rewrite objects with different encryption keys. The operation blocks until the rewrite completes, and returns the resulting ObjectMetadata.

Note
Application developers should be aware that rewriting large objects may take multiple hours. In such cases the application should consider using RewriteObject() or ResumeRewriteObject().
Parameters
source_bucket_namethe name of the bucket containing the source object.
source_object_namethe name of the source object.
destination_bucket_namewhere the destination object will be located.
destination_object_namewhat to name the destination object.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include DestinationKmsKeyName, DestinationPredefinedAcl, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfSourceGenerationMatch, IfSourceGenerationNotMatch, IfSourceMetagenerationMatch, IfSourceMetagenerationNotMatch, MaxBytesRewrittenPerCall, Projection, SourceEncryptionKey, SourceGeneration, UserProject, and WithObjectMetadata.
Returns
The metadata of the newly created object.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& source_bucket_name,
std::string const& source_object_name,
std::string const& destination_bucket_name,
std::string const& destination_object_name) {
StatusOr<gcs::ObjectMetadata> metadata = client.RewriteObjectBlocking(
source_bucket_name, source_object_name, destination_bucket_name,
destination_object_name);
if (!metadata) throw std::move(metadata).status();
std::cout << "Rewrote object " << destination_object_name
<< " Metadata: " << *metadata << "\n";
}
Example: using rewrite object to rotate the encryption key
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& old_key_base64,
std::string const& new_key_base64) {
client.RewriteObjectBlocking(
bucket_name, object_name, bucket_name, object_name,
gcs::SourceEncryptionKey::FromBase64Key(old_key_base64),
gcs::EncryptionKey::FromBase64Key(new_key_base64));
if (!object_metadata) throw std::move(object_metadata).status();
std::cout << "Rotated key on object " << object_metadata->name()
<< " in bucket " << object_metadata->bucket()
<< "\nFull Metadata: " << *object_metadata << "\n";
}
Example: using rewrite object to rename an object
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& old_object_name, std::string const& new_object_name) {
StatusOr<gcs::ObjectMetadata> metadata = client.RewriteObjectBlocking(
bucket_name, old_object_name, bucket_name, new_object_name);
if (!metadata) throw std::move(metadata).status();
client.DeleteObject(bucket_name, old_object_name);
if (!status.ok()) throw std::runtime_error(status.message());
std::cout << "Renamed " << old_object_name << " to " << new_object_name
<< " in bucket " << bucket_name << "\n";
}

◆ SetNativeBucketIamPolicy()

template<typename... Options>
StatusOr< NativeIamPolicy > google::cloud::storage::Client::SetNativeBucketIamPolicy ( std::string const &  bucket_name,
NativeIamPolicy const &  iam_policy,
Options &&...  options 
)
inline

Sets the native IAM Policy for a Bucket.

Google Cloud Identity & Access Management (IAM) lets administrators authorize who can take action on specific resources, including Google Cloud Storage Buckets. This operation allows you to set the IAM policies for a Bucket. IAM policies are a superset of the Bucket ACL, changes to the Bucket ACL are reflected in the IAM policy, and vice-versa. The documentation describes the mapping between legacy Bucket ACLs and IAM policies.

Consult the documentation for a more detailed description of IAM policies their use in Google Cloud Storage.

Note
The server rejects requests where the ETag value of the policy does not match the current ETag. Effectively this means that applications must use GetNativeBucketIamPolicy() to fetch the current value and ETag before calling SetNativeBucketIamPolicy(). Applications should use optimistic concurrency control techniques to retry changes in case some other application modified the IAM policy between the GetNativeBucketIamPolicy and SetNativeBucketIamPolicy calls.
Parameters
bucket_namequery metadata information about this bucket.
iam_policythe new IAM policy.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example: adding a new member
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& role, std::string const& member) {
auto policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3));
if (!policy) throw std::move(policy).status();
policy->set_version(3);
for (auto& binding : policy->bindings()) {
if (binding.role() != role || binding.has_condition()) {
continue;
}
auto& members = binding.members();
if (std::find(members.begin(), members.end(), member) == members.end()) {
members.emplace_back(member);
}
}
auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
if (!updated) throw std::move(updated).status();
std::cout << "Updated IAM policy bucket " << bucket_name
<< ". The new policy is " << *updated << "\n";
}
Example: removing a IAM member
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& role, std::string const& member) {
auto policy = client.GetNativeBucketIamPolicy(
bucket_name, gcs::RequestedPolicyVersion(3));
if (!policy) throw std::move(policy).status();
policy->set_version(3);
std::vector<google::cloud::storage::NativeIamBinding> updated_bindings;
for (auto& binding : policy->bindings()) {
auto& members = binding.members();
if (binding.role() == role && !binding.has_condition()) {
members.erase(std::remove(members.begin(), members.end(), member),
members.end());
}
if (!members.empty()) {
updated_bindings.emplace_back(std::move(binding));
}
}
policy->bindings() = std::move(updated_bindings);
auto updated = client.SetNativeBucketIamPolicy(bucket_name, *policy);
if (!updated) throw std::move(updated).status();
std::cout << "Updated IAM policy bucket " << bucket_name
<< ". The new policy is " << *updated << "\n";
}
See also
google::cloud::storage::NativeIamPolicy for details about the NativeIamPolicy class.

◆ TestBucketIamPermissions()

template<typename... Options>
StatusOr< std::vector< std::string > > google::cloud::storage::Client::TestBucketIamPermissions ( std::string  bucket_name,
std::vector< std::string >  permissions,
Options &&...  options 
)
inline

Tests the IAM permissions of the caller against a Bucket.

Google Cloud Identity & Access Management (IAM) lets administrators authorize who can take action on specific resources, including Google Cloud Storage Buckets. This operation tests the permissions of the caller for a Bucket. You must provide a list of permissions, this API will return the subset of those permissions that the current caller has in the given Bucket.

Consult the documentation for a more detailed description of IAM policies their use in Google Cloud Storage.

Parameters
bucket_namequery metadata information about this bucket.
permissionsthe list of permissions to check.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This is a read-only operation and is always idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::vector<std::string> const& permissions) {
StatusOr<std::vector<std::string>> actual_permissions =
client.TestBucketIamPermissions(bucket_name, permissions);
if (!actual_permissions) throw std::move(actual_permissions).status();
if (actual_permissions->empty()) {
std::cout << "The caller does not hold any of the tested permissions the"
<< " bucket " << bucket_name << "\n";
return;
}
std::cout << "The caller is authorized for the following permissions on "
<< bucket_name << ": ";
for (auto const& permission : *actual_permissions) {
std::cout << "\n " << permission;
}
std::cout << "\n";
}

◆ UpdateBucket()

template<typename... Options>
StatusOr< BucketMetadata > google::cloud::storage::Client::UpdateBucket ( std::string  bucket_name,
BucketMetadata  metadata,
Options &&...  options 
)
inline

Updates the metadata in a Google Cloud Storage Bucket.

A Buckets: update request changes all the writeable attributes of a bucket, in contrast, a Buckets: patch request only changes the subset of the attributes included in the request. This function creates a Buckets: update request to change the writable attributes in BucketMetadata.

Parameters
bucket_namethe name of the new bucket.
metadatathe new metadata for the Bucket. The name field is ignored in favor of bucket_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, PredefinedDefaultObjectAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case,IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& storage_class) {
StatusOr<gcs::BucketMetadata> meta = client.GetBucketMetadata(bucket_name);
if (!meta) throw std::move(meta).status();
meta->set_storage_class(storage_class);
client.UpdateBucket(bucket_name, *meta);
if (!updated) throw std::move(updated).status();
std::cout << "Updated the storage class in " << updated->name() << " to "
<< updated->storage_class() << "."
<< "\nFull metadata:" << *updated << "\n";
}
See also
Before enabling Uniform Bucket Level Access please review the feature documentation, as well as "Should you use uniform bucket-level access ?".

◆ UpdateBucketAcl()

template<typename... Options>
StatusOr< BucketAccessControl > google::cloud::storage::Client::UpdateBucketAcl ( std::string const &  bucket_name,
BucketAccessControl const &  acl,
Options &&...  options 
)
inline

Updates the value of an existing bucket ACL.

Note
For changing BucketAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
aclthe new ACL value. Note that only the writable values of the ACL will be modified by the server.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
gcs::BucketAccessControl desired_acl =
gcs::BucketAccessControl().set_entity(entity).set_role(role);
client.UpdateBucketAcl(bucket_name, desired_acl);
if (!updated_acl) throw std::move(updated_acl).status();
std::cout << "Bucket ACL updated. The ACL entry for "
<< updated_acl->entity() << " in bucket " << updated_acl->bucket()
<< " is " << *updated_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls for additional details on what fields are writeable.
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ UpdateDefaultObjectAcl()

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::UpdateDefaultObjectAcl ( std::string const &  bucket_name,
ObjectAccessControl const &  acl,
Options &&...  options 
)
inline

Updates the value of an existing default object ACL.

The default object ACL sets the ACL for any object created in the bucket, unless a different ACL is specified when the object is created.

Note
For changing default object access controls, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket.
aclthe new ACL value. Note that only the writable values of the ACL will be modified by the server.
optionsa list of optional query parameters and/or request Valid types for this operation include UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& entity, std::string const& role) {
client.GetDefaultObjectAcl(bucket_name, entity);
if (!original_acl) throw std::move(original_acl).status();
original_acl->set_role(role);
client.UpdateDefaultObjectAcl(bucket_name, *original_acl);
if (!updated_acl) throw std::move(updated_acl).status();
std::cout << "Default Object ACL entry for " << updated_acl->entity()
<< " in bucket " << updated_acl->bucket() << " is now "
<< *updated_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/create-manage-lists#defaultobjects
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameter.
https://cloud.google.com/storage/docs/access-control/lists#permissions for the format of the role parameter.

◆ UpdateHmacKey()

template<typename... Options>
StatusOr< HmacKeyMetadata > google::cloud::storage::Client::UpdateHmacKey ( std::string  access_id,
HmacKeyMetadata  resource,
Options &&...  options 
)
inline

Update an existing HMAC key in a given project.

Parameters
access_idthe HMAC key access_id() that you want to delete. Each HMAC key is assigned an access_id() attribute at creation time.
resourcethe desired changes to the HMAC key resource. Only the state field may be changed. The etag field may be set but it is only used as a pre-condition, the application cannot set the etag.
optionsa list of optional query parameters and/or request headers. In addition to the options common to all requests, this operation accepts OverrideDefaultProject.
Returns
This operation returns the new HMAC key metadata.
Idempotency
This operation is only idempotent if the etag attribute in resource is set, or if the IfMatchEtag option is set.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& access_id,
std::string const& state) {
StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey(
access_id, gcs::HmacKeyMetadata().set_state(std::move(state)));
if (!updated) throw std::move(updated).status();
std::cout << "The updated HMAC key metadata is: " << *updated << "\n";
}
See also
https://cloud.google.com/storage/docs/authentication/hmackeys for general information on using HMAC keys for Google Cloud Platform service accounts authentication.
https://cloud.google.com/storage/docs/authentication/managing-hmackeys for a detailed description on how to use the feature.

◆ UpdateObject()

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::UpdateObject ( std::string  bucket_name,
std::string  object_name,
ObjectMetadata  metadata,
Options &&...  options 
)
inline

Updates the metadata in a Google Cloud Storage Object.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
metadatathe new metadata for the Object. Only the writeable fields accepted by the Objects: update API are used, all other fields are ignored. In particular, note that bucket and name are ignored in favor of bucket_name and object_name.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include Generation, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, PredefinedAcl, Projection, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfMetagenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& key,
std::string const& value) {
client.GetObjectMetadata(bucket_name, object_name);
if (!object_metadata) throw std::move(object_metadata).status();
gcs::ObjectMetadata desired = *object_metadata;
desired.mutable_metadata().emplace(key, value);
client.UpdateObject(bucket_name, object_name, desired,
gcs::Generation(object_metadata->generation()));
if (!updated) throw std::move(updated).status();
std::cout << "Object updated. The full metadata after the update is: "
<< *updated << "\n";
}

◆ UpdateObjectAcl()

template<typename... Options>
StatusOr< ObjectAccessControl > google::cloud::storage::Client::UpdateObjectAcl ( std::string const &  bucket_name,
std::string const &  object_name,
ObjectAccessControl const &  acl,
Options &&...  options 
)
inline

Updates the value of an existing object ACL.

Note
For changing ObjectAccessControl, the Patch and Update APIs basically offer the same functionality. The only field that can be modified by either API is role, and it may only be set to a new value (it cannot be removed). The API is offered for consistency with the other resource types where Patch and Update APIs have different semantics.
Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object.
aclthe new ACL value. Note that only the writable values of the ACL will be modified by the server.
optionsa list of optional query parameters and/or request Valid types for this operation include Generation, and UserProject.
Idempotency
This operation is only idempotent if restricted by pre-conditions. There are no pre-conditions for this operation that can make it idempotent.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& entity,
std::string const& role) {
client.GetObjectAcl(bucket_name, object_name, entity);
if (!current_acl) throw std::move(current_acl).status();
current_acl->set_role(role);
client.UpdateObjectAcl(bucket_name, object_name, *current_acl);
if (!updated_acl) throw std::move(updated_acl).status();
std::cout << "ACL entry for " << updated_acl->entity() << " in object "
<< updated_acl->object() << " in bucket " << updated_acl->bucket()
<< " is now " << *updated_acl << "\n";
}
See also
https://cloud.google.com/storage/docs/access-control/lists#scopes for the format of the entity parameters.
https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls for additional details on what fields are writeable.

◆ UploadFile()

template<typename... Options>
StatusOr< ObjectMetadata > google::cloud::storage::Client::UploadFile ( std::string const &  file_name,
std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Uploads a file to an object.

Note
Only regular files are supported. If you need to upload the results of reading a device, Named Pipe, FIFO, or other type of file system object that is not a regular file then WriteObject() is probably a better alternative.
Parameters
file_namethe name of the file to be uploaded.
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be read.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include ContentEncoding, ContentType, Crc32cChecksumValue, DisableCrc32cChecksum, DisableMD5Hash, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, KmsKeyName, MD5HashValue, PredefinedAcl, Projection, UserProject, UploadFromOffset, UploadLimit and WithObjectMetadata.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
std::string const& bucket_name, std::string const& object_name) {
// Note that the client library automatically computes a hash on the
// client-side to verify data integrity during transmission.
StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
file_name, bucket_name, object_name, gcs::IfGenerationMatch(0));
if (!metadata) throw std::move(metadata).status();
std::cout << "Uploaded " << file_name << " to object " << metadata->name()
<< " in bucket " << metadata->bucket()
<< "\nFull metadata: " << *metadata << "\n";
}
Example: manually selecting a resumable upload
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
std::string const& bucket_name, std::string const& object_name) {
// Note that the client library automatically computes a hash on the
// client-side to verify data integrity during transmission.
StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
file_name, bucket_name, object_name, gcs::IfGenerationMatch(0),
gcs::NewResumableUploadSession());
if (!metadata) throw std::move(metadata).status();
std::cout << "Uploaded " << file_name << " to object " << metadata->name()
<< " in bucket " << metadata->bucket()
<< "\nFull metadata: " << *metadata << "\n";
}

◆ WriteObject()

template<typename... Options>
ObjectWriteStream google::cloud::storage::Client::WriteObject ( std::string const &  bucket_name,
std::string const &  object_name,
Options &&...  options 
)
inline

Writes contents into an object.

This creates a std::ostream object to upload contents. The application can use either the regular operator<<(), or std::ostream::write() to upload data.

This function always uses resumable uploads. The application can provide a #RestoreResumableUploadSession() option to resume a previously created upload. The returned object has accessors to query the session id and the next byte expected by GCS.

Note
When resuming uploads it is the application's responsibility to save the session id to restart the upload later. Likewise, it is the application's responsibility to query the next expected byte and send the remaining data without gaps or duplications.

For small uploads we recommend using InsertObject, consult the documentation for details.

If the application does not provide a #RestoreResumableUploadSession() option, or it provides the #NewResumableUploadSession() option then a new resumable upload session is created.

More information about buffering and recommendations around performance in the ObjectWriteStream class documentation.

Parameters
bucket_namethe name of the bucket that contains the object.
object_namethe name of the object to be read.
optionsa list of optional query parameters and/or request headers. Valid types for this operation include ContentEncoding, ContentType, Crc32cChecksumValue, DisableCrc32cChecksum, DisableMD5Hash, EncryptionKey, IfGenerationMatch, IfGenerationNotMatch, IfMetagenerationMatch, IfMetagenerationNotMatch, KmsKeyName, MD5HashValue, PredefinedAcl, Projection, UseResumableUploadSession, UserProject, WithObjectMetadata, UploadContentLength, AutoFinalize, and UploadBufferSize.
Idempotency
This operation is only idempotent if restricted by pre-conditions, in this case, IfGenerationMatch.
Example
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, int desired_line_count) {
std::string const text = "Lorem ipsum dolor sit amet";
gcs::ObjectWriteStream stream =
client.WriteObject(bucket_name, object_name);
for (int lineno = 0; lineno != desired_line_count; ++lineno) {
// Add 1 to the counter, because it is conventional to number lines
// starting at 1.
stream << (lineno + 1) << ": " << text << "\n";
}
stream.Close();
StatusOr<gcs::ObjectMetadata> metadata = std::move(stream).metadata();
if (!metadata) throw std::move(metadata).status();
std::cout << "Successfully wrote to object " << metadata->name()
<< " its size is: " << metadata->size()
<< "\nFull metadata: " << *metadata << "\n";
}
Example: write an object with a CMEK.
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& kms_key_name) {
gcs::ObjectWriteStream stream = client.WriteObject(
bucket_name, object_name, gcs::KmsKeyName(kms_key_name));
// Line numbers start at 1.
for (int lineno = 1; lineno <= 10; ++lineno) {
stream << lineno << ": placeholder text for CMEK example.\n";
}
stream.Close();
StatusOr<gcs::ObjectMetadata> metadata = std::move(stream).metadata();
if (!metadata) throw std::move(metadata).status();
std::cout << "Successfully wrote to object " << metadata->name()
<< " its size is: " << metadata->size()
<< "\nFull metadata: " << *metadata << "\n";
}
Example: starting a resumable upload.
namespace gcs = ::google::cloud::storage;
return [](gcs::Client client, std::string const& bucket_name,
std::string const& object_name) {
gcs::ObjectWriteStream stream = client.WriteObject(
bucket_name, object_name, gcs::NewResumableUploadSession(),
gcs::AutoFinalizeDisabled());
auto session_id = stream.resumable_session_id();
std::cout << "Created resumable upload: " << session_id << "\n";
// Because this stream was created with `AutoFinalizeDisabled()` its
// destructor will *not* finalize the upload, allowing a separate process or
// function to resume and continue the upload.
stream << "This data will not get uploaded, it is too small\n";
return session_id;
}
Example: resuming a resumable upload.
namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
std::string const& object_name, std::string const& session_id) {
// Restore a resumable upload stream, the library automatically queries the
// state of the upload and discovers the next expected byte.
gcs::ObjectWriteStream stream =
client.WriteObject(bucket_name, object_name,
gcs::RestoreResumableUploadSession(session_id));
if (!stream.IsOpen() && stream.metadata().ok()) {
std::cout << "The upload has already been finalized. The object "
<< "metadata is: " << *stream.metadata() << "\n";
}
if (stream.next_expected_byte() == 0) {
// In this example we create a small object, smaller than the resumable
// upload quantum (256 KiB), so either all the data is there or not.
// Applications use `next_expected_byte()` to find the position in their
// input where they need to start uploading.
stream << R"""(
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
)""";
}
stream.Close();
StatusOr<gcs::ObjectMetadata> metadata = stream.metadata();
if (!metadata) throw std::move(metadata).status();
std::cout << "Upload completed, the new object metadata is: " << *metadata
<< "\n";
}
See also
Resumable Uploads for more information about resumable uploads.

Friends And Related Function Documentation

◆ operator!=

bool operator!= ( Client const &  a,
Client const &  b 
)
friend

◆ operator==

bool operator== ( Client const &  a,
Client const &  b 
)
friend