View and edit object metadata

Concepts

This page describes how to view and edit the metadata associated with objectsstored in Cloud Storage.

This page does not cover viewing or editing Identity and Access Management (IAM)policies or object Access Control Lists (ACLs), both of which control whois allowed to access your data. SeeIdentity and Access Management andCreating and Managing ACLs for guides to accomplishing these tasks.

Required roles

In order to get the required permissions for viewing and editing the metadata ofobjects, ask your administrator to grant you the Storage Object User(roles/storage.objectUser) role on the bucket.

This role contains the permissions required to view and edit the metadata ofobjects. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

  • storage.buckets.list
    • This permission is only required if you plan on using the Google Cloud console to perform the tasks on this page.
  • storage.objects.get
  • storage.objects.getIamPolicy
    • This permission is only required if you want to return an object'sIAM policies.
  • storage.objects.list
  • storage.objects.setRetention
  • storage.objects.update

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

For instructions on granting roles on buckets, seeSet and manage IAM policies on buckets.

View object metadata

Complete the following instructions to view the metadata associated with anobject:

Console

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

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that containsthe object for which you want to view metadata.

    TheBucket details page opens, with theObjects tab selected.

  3. Navigate to the object, which might be located in a folder.

    Certain object metadata values, such as the object's size andstorage class, are displayed along with the object's name.

  4. Click the name of the object.

    TheObject details page opens, which displays additional objectmetadata.

  5. ClickEdit metadata.

    The overlay window that appears shows the current values for severalmore object metadata keys, including custom metadata.

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

Command line

Use thegcloud storage objects describe command:

gcloud storage objects describe gs://BUCKET_NAME/OBJECT_NAME

Where:

  • BUCKET_NAME is the name of the bucketcontaining the object whose metadata you want to view. For example,my-awesome-bucket.
  • OBJECT_NAME is the name of the object whosemetadata you want to view. For example,cat.jpeg.

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

bucket: my-awesome-bucketcontent_type: image/pngcrc32c_hash: pNKjPQ==creation_time: 2024-01-26T21:33:04+0000custom_fields:  Animal: Cat  Type: Cutecustom_time: 1970-01-01T00:00:00+0000etag: CMXyydSA/IMDEAE=generation: '1706304784726341'md5_hash: KCbI3PYk1aHfekIvf/osrw==metageneration: 1name: kitten.pngsize: 168276storage_class: STANDARDstorage_class_update_time: 2024-01-26T21:33:04+0000storage_url: gs://my-awesome-bucket/kitten.png#1706304784726341update_time: 2024-01-26T21:33:04+0000

Client libraries

C++

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

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

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name){StatusOr<gcs::ObjectMetadata>object_metadata=client.GetObjectMetadata(bucket_name,object_name);if(!object_metadata)throwstd::move(object_metadata).status();std::cout <<"The metadata for object " <<object_metadata->name()            <<" in bucket " <<object_metadata->bucket() <<" is "            <<*object_metadata <<"\n";}

C#

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

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

usingGoogle.Cloud.Storage.V1;usingSystem;publicclassGetMetadataSample{publicGoogle.Apis.Storage.v1.Data.ObjectGetMetadata(stringbucketName="your-unique-bucket-name",stringobjectName="your-object-name"){varstorage=StorageClient.Create();varstorageObject=storage.GetObject(bucketName,objectName,newGetObjectOptions{Projection=Projection.Full});Console.WriteLine($"Bucket:\t{storageObject.Bucket}");Console.WriteLine($"CacheControl:\t{storageObject.CacheControl}");Console.WriteLine($"ComponentCount:\t{storageObject.ComponentCount}");Console.WriteLine($"ContentDisposition:\t{storageObject.ContentDisposition}");Console.WriteLine($"ContentEncoding:\t{storageObject.ContentEncoding}");Console.WriteLine($"ContentLanguage:\t{storageObject.ContentLanguage}");Console.WriteLine($"ContentType:\t{storageObject.ContentType}");Console.WriteLine($"Crc32c:\t{storageObject.Crc32c}");Console.WriteLine($"ETag:\t{storageObject.ETag}");Console.WriteLine($"Generation:\t{storageObject.Generation}");Console.WriteLine($"Id:\t{storageObject.Id}");Console.WriteLine($"Kind:\t{storageObject.Kind}");Console.WriteLine($"KmsKeyName:\t{storageObject.KmsKeyName}");Console.WriteLine($"Md5Hash:\t{storageObject.Md5Hash}");Console.WriteLine($"MediaLink:\t{storageObject.MediaLink}");Console.WriteLine($"Metageneration:\t{storageObject.Metageneration}");Console.WriteLine($"Name:\t{storageObject.Name}");Console.WriteLine($"Retention:\t{storageObject.Retention}");Console.WriteLine($"Size:\t{storageObject.Size}");Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");Console.WriteLine($"Updated:\t{storageObject.Updated}");booleventBasedHold=storageObject.EventBasedHold??false;Console.WriteLine("Event-based hold enabled? {0}",eventBasedHold);booltemporaryHold=storageObject.TemporaryHold??false;Console.WriteLine("Temporary hold enabled? {0}",temporaryHold);Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");if(storageObject.Metadata!=null){Console.WriteLine("Metadata: ");foreach(varmetadatainstorageObject.Metadata){Console.WriteLine($"{metadata.Key}:\t{metadata.Value}");}}Console.WriteLine($"CustomTime:\t{storageObject.CustomTime}");returnstorageObject;}}

Go

For more information, see theCloud StorageGo API reference documentation.

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

import("context""fmt""io""time""cloud.google.com/go/storage")// getMetadata prints all of the object attributes.funcgetMetadata(wio.Writer,bucket,objectstring)(*storage.ObjectAttrs,error){// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnnil,fmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)attrs,err:=o.Attrs(ctx)iferr!=nil{returnnil,fmt.Errorf("Object(%q).Attrs: %w",object,err)}fmt.Fprintf(w,"Bucket: %v\n",attrs.Bucket)fmt.Fprintf(w,"CacheControl: %v\n",attrs.CacheControl)fmt.Fprintf(w,"ContentDisposition: %v\n",attrs.ContentDisposition)fmt.Fprintf(w,"ContentEncoding: %v\n",attrs.ContentEncoding)fmt.Fprintf(w,"ContentLanguage: %v\n",attrs.ContentLanguage)fmt.Fprintf(w,"ContentType: %v\n",attrs.ContentType)fmt.Fprintf(w,"Crc32c: %v\n",attrs.CRC32C)fmt.Fprintf(w,"Generation: %v\n",attrs.Generation)fmt.Fprintf(w,"KmsKeyName: %v\n",attrs.KMSKeyName)fmt.Fprintf(w,"Md5Hash: %v\n",attrs.MD5)fmt.Fprintf(w,"MediaLink: %v\n",attrs.MediaLink)fmt.Fprintf(w,"Metageneration: %v\n",attrs.Metageneration)fmt.Fprintf(w,"Name: %v\n",attrs.Name)fmt.Fprintf(w,"Size: %v\n",attrs.Size)fmt.Fprintf(w,"StorageClass: %v\n",attrs.StorageClass)fmt.Fprintf(w,"TimeCreated: %v\n",attrs.Created)fmt.Fprintf(w,"Updated: %v\n",attrs.Updated)fmt.Fprintf(w,"Event-based hold enabled? %t\n",attrs.EventBasedHold)fmt.Fprintf(w,"Temporary hold enabled? %t\n",attrs.TemporaryHold)fmt.Fprintf(w,"Retention expiration time %v\n",attrs.RetentionExpirationTime)fmt.Fprintf(w,"Custom time %v\n",attrs.CustomTime)fmt.Fprintf(w,"Retention: %+v\n",attrs.Retention)fmt.Fprintf(w,"\n\nMetadata\n")forkey,value:=rangeattrs.Metadata{fmt.Fprintf(w,"\t%v = %v\n",key,value)}returnattrs,nil}

Java

For more information, see theCloud StorageJava API reference documentation.

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

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageException;importcom.google.cloud.storage.StorageOptions;importjava.util.Date;importjava.util.Map;publicclassGetObjectMetadata{publicstaticvoidgetObjectMetadata(StringprojectId,StringbucketName,StringblobName)throwsStorageException{// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();// Select all fields// Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROLBlobblob=storage.get(bucketName,blobName,Storage.BlobGetOption.fields(Storage.BlobField.values()));// Print blob metadataSystem.out.println("Bucket: "+blob.getBucket());System.out.println("CacheControl: "+blob.getCacheControl());System.out.println("ComponentCount: "+blob.getComponentCount());System.out.println("ContentDisposition: "+blob.getContentDisposition());System.out.println("ContentEncoding: "+blob.getContentEncoding());System.out.println("ContentLanguage: "+blob.getContentLanguage());System.out.println("ContentType: "+blob.getContentType());System.out.println("CustomTime: "+blob.getCustomTime());System.out.println("Crc32c: "+blob.getCrc32c());System.out.println("Crc32cHexString: "+blob.getCrc32cToHexString());System.out.println("ETag: "+blob.getEtag());System.out.println("Generation: "+blob.getGeneration());System.out.println("Id: "+blob.getBlobId());System.out.println("KmsKeyName: "+blob.getKmsKeyName());System.out.println("Md5Hash: "+blob.getMd5());System.out.println("Md5HexString: "+blob.getMd5ToHexString());System.out.println("MediaLink: "+blob.getMediaLink());System.out.println("Metageneration: "+blob.getMetageneration());System.out.println("Name: "+blob.getName());System.out.println("Size: "+blob.getSize());System.out.println("StorageClass: "+blob.getStorageClass());System.out.println("TimeCreated: "+newDate(blob.getCreateTime()));System.out.println("Last Metadata Update: "+newDate(blob.getUpdateTime()));System.out.println("Object Retention Policy: "+blob.getRetention());BooleantemporaryHoldIsEnabled=(blob.getTemporaryHold()!=null &&blob.getTemporaryHold());System.out.println("temporaryHold: "+(temporaryHoldIsEnabled?"enabled":"disabled"));BooleaneventBasedHoldIsEnabled=(blob.getEventBasedHold()!=null &&blob.getEventBasedHold());System.out.println("eventBasedHold: "+(eventBasedHoldIsEnabled?"enabled":"disabled"));if(blob.getRetentionExpirationTime()!=null){System.out.println("retentionExpirationTime: "+newDate(blob.getRetentionExpirationTime()));}if(blob.getMetadata()!=null){System.out.println("\n\n\nUser metadata:");for(Map.Entry<String,String>userMetadata:blob.getMetadata().entrySet()){System.out.println(userMetadata.getKey()+"="+userMetadata.getValue());}}}}

Node.js

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

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

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();asyncfunctiongetMetadata(){// Gets the metadata for the fileconst[metadata]=awaitstorage.bucket(bucketName).file(fileName).getMetadata();console.log(`Bucket:${metadata.bucket}`);console.log(`CacheControl:${metadata.cacheControl}`);console.log(`ComponentCount:${metadata.componentCount}`);console.log(`ContentDisposition:${metadata.contentDisposition}`);console.log(`ContentEncoding:${metadata.contentEncoding}`);console.log(`ContentLanguage:${metadata.contentLanguage}`);console.log(`ContentType:${metadata.contentType}`);console.log(`CustomTime:${metadata.customTime}`);console.log(`Crc32c:${metadata.crc32c}`);console.log(`ETag:${metadata.etag}`);console.log(`Generation:${metadata.generation}`);console.log(`Id:${metadata.id}`);console.log(`KmsKeyName:${metadata.kmsKeyName}`);console.log(`Md5Hash:${metadata.md5Hash}`);console.log(`MediaLink:${metadata.mediaLink}`);console.log(`Metageneration:${metadata.metageneration}`);console.log(`Name:${metadata.name}`);console.log(`Size:${metadata.size}`);console.log(`StorageClass:${metadata.storageClass}`);console.log(`TimeCreated:${newDate(metadata.timeCreated)}`);console.log(`Last Metadata Update:${newDate(metadata.updated)}`);console.log(`TurboReplication:${metadata.rpo}`);console.log(`temporaryHold:${metadata.temporaryHold?'enabled':'disabled'}`);console.log(`eventBasedHold:${metadata.eventBasedHold?'enabled':'disabled'}`);if(metadata.retentionExpirationTime){console.log(`retentionExpirationTime:${newDate(metadata.retentionExpirationTime)}`);}if(metadata.metadata){console.log('\n\n\nUser metadata:');for(constkeyinmetadata.metadata){console.log(`${key}=${metadata.metadata[key]}`);}}}getMetadata().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

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

use Google\Cloud\Storage\StorageClient;/** * List object metadata. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function object_metadata(string $bucketName, string $objectName): void{    $storage = new StorageClient();    $bucket = $storage->bucket($bucketName);    $object = $bucket->object($objectName);    $info = $object->info();    if (isset($info['name'])) {        printf('Blob: %s' . PHP_EOL, $info['name']);    }    if (isset($info['bucket'])) {        printf('Bucket: %s' . PHP_EOL, $info['bucket']);    }    if (isset($info['storageClass'])) {        printf('Storage class: %s' . PHP_EOL, $info['storageClass']);    }    if (isset($info['id'])) {        printf('ID: %s' . PHP_EOL, $info['id']);    }    if (isset($info['size'])) {        printf('Size: %s' . PHP_EOL, $info['size']);    }    if (isset($info['updated'])) {        printf('Updated: %s' . PHP_EOL, $info['updated']);    }    if (isset($info['generation'])) {        printf('Generation: %s' . PHP_EOL, $info['generation']);    }    if (isset($info['metageneration'])) {        printf('Metageneration: %s' . PHP_EOL, $info['metageneration']);    }    if (isset($info['etag'])) {        printf('Etag: %s' . PHP_EOL, $info['etag']);    }    if (isset($info['crc32c'])) {        printf('Crc32c: %s' . PHP_EOL, $info['crc32c']);    }    if (isset($info['md5Hash'])) {        printf('MD5 Hash: %s' . PHP_EOL, $info['md5Hash']);    }    if (isset($info['contentType'])) {        printf('Content-type: %s' . PHP_EOL, $info['contentType']);    }    if (isset($info['temporaryHold'])) {        printf('Temporary hold: %s' . PHP_EOL, ($info['temporaryHold'] ? 'enabled' : 'disabled'));    }    if (isset($info['eventBasedHold'])) {        printf('Event-based hold: %s' . PHP_EOL, ($info['eventBasedHold'] ? 'enabled' : 'disabled'));    }    if (isset($info['retentionExpirationTime'])) {        printf('Retention Expiration Time: %s' . PHP_EOL, $info['retentionExpirationTime']);    }    if (isset($info['retention'])) {        printf('Retention mode: %s' . PHP_EOL, $info['retention']['mode']);        printf('Retain until time is: %s' . PHP_EOL, $info['retention']['retainUntilTime']);    }    if (isset($info['customTime'])) {        printf('Custom Time: %s' . PHP_EOL, $info['customTime']);    }    if (isset($info['metadata'])) {        printf('Metadata: %s' . PHP_EOL, print_r($info['metadata'], true));    }}

Python

For more information, see theCloud StoragePython API reference documentation.

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

fromgoogle.cloudimportstoragedefblob_metadata(bucket_name,blob_name):"""Prints out a blob's metadata."""# bucket_name = 'your-bucket-name'# blob_name = 'your-object-name'storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)# Retrieve a blob, and its metadata, from Google Cloud Storage.# Note that `get_blob` differs from `Bucket.blob`, which does not# make an HTTP request.blob=bucket.get_blob(blob_name)print(f"Blob:{blob.name}")print(f"Bucket:{blob.bucket.name}")print(f"Storage class:{blob.storage_class}")print(f"ID:{blob.id}")print(f"Size:{blob.size} bytes")print(f"Updated:{blob.updated}")print(f"Generation:{blob.generation}")print(f"Metageneration:{blob.metageneration}")print(f"Etag:{blob.etag}")print(f"Owner:{blob.owner}")print(f"Component count:{blob.component_count}")print(f"Crc32c:{blob.crc32c}")print(f"md5_hash:{blob.md5_hash}")print(f"Cache-control:{blob.cache_control}")print(f"Content-type:{blob.content_type}")print(f"Content-disposition:{blob.content_disposition}")print(f"Content-encoding:{blob.content_encoding}")print(f"Content-language:{blob.content_language}")print(f"Metadata:{blob.metadata}")print(f"Medialink:{blob.media_link}")print(f"Custom Time:{blob.custom_time}")print("Temporary hold: ","enabled"ifblob.temporary_holdelse"disabled")print("Event based hold: ","enabled"ifblob.event_based_holdelse"disabled",)print(f"Retention mode:{blob.retention.mode}")print(f"Retention retain until time:{blob.retention.retain_until_time}")ifblob.retention_expiration_time:print(f"retentionExpirationTime:{blob.retention_expiration_time}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

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

defget_metadatabucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_namefile=bucket.filefile_nameputs"Name:#{file.name}"puts"Bucket:#{bucket.name}"puts"Storage class:#{bucket.storage_class}"puts"ID:#{file.id}"puts"Size:#{file.size} bytes"puts"Created:#{file.created_at}"puts"Updated:#{file.updated_at}"puts"Generation:#{file.generation}"puts"Metageneration:#{file.metageneration}"puts"Etag:#{file.etag}"puts"Owners:#{file.acl.owners.join','}"puts"Crc32c:#{file.crc32c}"puts"md5_hash:#{file.md5}"puts"Cache-control:#{file.cache_control}"puts"Content-type:#{file.content_type}"puts"Content-disposition:#{file.content_disposition}"puts"Content-encoding:#{file.content_encoding}"puts"Content-language:#{file.content_language}"puts"KmsKeyName:#{file.kms_key}"puts"Event-based hold enabled?:#{file.event_based_hold?}"puts"Temporary hold enaled?:#{file.temporary_hold?}"puts"Retention Expiration:#{file.retention_expires_at}"puts"Custom Time:#{file.custom_time}"puts"Metadata:"file.metadata.eachdo|key,value|puts" -#{key} =#{value}"endend

Terraform

You can use aTerraform resource to view an object'smetadata.

# Get object metadatadata "google_storage_bucket_object" "default" {  name   = google_storage_bucket_object.default.name  bucket = google_storage_bucket.static.id}output "object_metadata" {  value = data.google_storage_bucket_object.default}

REST APIs

JSON API

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

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

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

    Where:

    • BUCKET_NAME is the name of the bucketcontaining the object whose metadata you want to view. Forexample,my-bucket.
    • OBJECT_NAME is the URL-encoded name ofthe object whose metadata you want to view.For example,pets/dog.png, URL-encoded aspets%2Fdog.png.

XML API

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

  2. UsecURL to call theXML API with aHEAD Object request:

    curl -I HEAD \  -H "Authorization: Bearer $(gcloud auth print-access-token)" \  "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Where:

    • BUCKET_NAME is the name of the bucketcontaining the object whose metadata you want to view. Forexample,my-bucket.
    • OBJECT_NAME is the URL-encoded name ofthe object whose metadata you want to view.For example,pets/dog.png, URL-encoded aspets%2Fdog.png.

Edit object metadata

Complete the following steps to edit the metadata associated with an object:

Console

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

    Go to Buckets

  2. In the list of buckets, click the name of the bucket that containsthe object for which you want to edit metadata.

    TheBucket details page opens, with theObjects tab selected.

  3. Navigate to the object, which might be located in a folder.

  4. Click the name of the object.

    TheObject details page opens, which displays object metadata.

  5. Click the pencil icon associated with the metadata that you want to edit,if it appears on the page.

  6. Otherwise, clickEdit metadata to access additional editablemetadata.

    In the overlay window that appears, edit the metadata as needed.

    • For standard metadata fields, edit theValue.

    • Add your own custom metadata by clicking theAdditem button.

    • You can edit both theKey andValue of your custom metadata.

    • Delete your custom metadata by clicking the associatedX.

    Once you are finished editing metadata in the overlay window, clickSave.

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

Command line

Use thegcloud storage objects update command:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAMEMETADATA_FLAG

Where:

  • BUCKET_NAME is the name of the bucketcontaining the object whose metadata you want to edit. For example,my-bucket.
  • OBJECT_NAME is the name of the object whosemetadata you want to edit. For example,pets/dog.png.
  • METADATA_FLAG is the flag for the metadata youwant to edit. For example--content-type=image/png.

If successful, the response looks like the following example:

Patching gs://my-bucket/pets/dog.png#1560574162144861...  Completed 1

For a complete list of metadata that you can update with this command,see thecommand reference page.

Client libraries

C++

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

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

namespacegcs=::google::cloud::storage;using::google::cloud::StatusOr;[](gcs::Clientclient,std::stringconst&bucket_name,std::stringconst&object_name,std::stringconst&key,std::stringconst&value){StatusOr<gcs::ObjectMetadata>object_metadata=client.GetObjectMetadata(bucket_name,object_name);if(!object_metadata)throwstd::move(object_metadata).status();gcs::ObjectMetadatadesired=*object_metadata;desired.mutable_metadata().emplace(key,value);StatusOr<gcs::ObjectMetadata>updated=client.UpdateObject(bucket_name,object_name,desired,gcs::Generation(object_metadata->generation()));if(!updated)throwstd::move(updated).status();std::cout <<"Object updated. The full metadata after the update is: "            <<*updated <<"\n";}

C#

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

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

usingGoogle.Cloud.Storage.V1;usingSystem;usingSystem.Collections.Generic;publicclassSetObjectMetadataSample{publicGoogle.Apis.Storage.v1.Data.ObjectSetObjectMetadata(stringbucketName="your-bucket-name",stringobjectName="your-object-name",stringkey="key-to-add",stringvalue="value-to-add"){varstorage=StorageClient.Create();varfile=storage.GetObject(bucketName,objectName);if(file.Metadata==null){file.Metadata=newDictionary<string,string>();}file.Metadata.Add(key,value);file=storage.UpdateObject(file);Console.WriteLine($"Updated custom metadata for object {objectName} in bucket {bucketName}");returnfile;}}

Go

For more information, see theCloud StorageGo API reference documentation.

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

import("context""fmt""io""time""cloud.google.com/go/storage")// setMetadata sets an object's metadata.funcsetMetadata(wio.Writer,bucket,objectstring)error{// bucket := "bucket-name"// object := "object-name"ctx:=context.Background()client,err:=storage.NewClient(ctx)iferr!=nil{returnfmt.Errorf("storage.NewClient: %w",err)}deferclient.Close()ctx,cancel:=context.WithTimeout(ctx,time.Second*10)defercancel()o:=client.Bucket(bucket).Object(object)// Optional: set a metageneration-match precondition to avoid potential race// conditions and data corruptions. The request to update is aborted if the// object's metageneration does not match your precondition.attrs,err:=o.Attrs(ctx)iferr!=nil{returnfmt.Errorf("object.Attrs: %w",err)}o=o.If(storage.Conditions{MetagenerationMatch:attrs.Metageneration})// Update the object to set the metadata.objectAttrsToUpdate:=storage.ObjectAttrsToUpdate{Metadata:map[string]string{"keyToAddOrUpdate":"value",},}if_,err:=o.Update(ctx,objectAttrsToUpdate);err!=nil{returnfmt.Errorf("ObjectHandle(%q).Update: %w",object,err)}fmt.Fprintf(w,"Updated custom metadata for object %v in bucket %v.\n",object,bucket)returnnil}

Java

For more information, see theCloud StorageJava API reference documentation.

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

importcom.google.cloud.storage.Blob;importcom.google.cloud.storage.BlobId;importcom.google.cloud.storage.BlobInfo;importcom.google.cloud.storage.Storage;importcom.google.cloud.storage.StorageOptions;importjava.util.HashMap;importjava.util.Map;publicclassSetObjectMetadata{publicstaticvoidsetObjectMetadata(StringprojectId,StringbucketName,StringobjectName){// The ID of your GCP project// String projectId = "your-project-id";// The ID of your GCS bucket// String bucketName = "your-unique-bucket-name";// The ID of your GCS object// String objectName = "your-object-name";Storagestorage=StorageOptions.newBuilder().setProjectId(projectId).build().getService();Map<String,String>newMetadata=newHashMap<>();newMetadata.put("keyToAddOrUpdate","value");BlobIdblobId=BlobId.of(bucketName,objectName);Blobblob=storage.get(blobId);if(blob==null){System.out.println("The object "+objectName+" was not found in "+bucketName);return;}// Optional: set a generation-match precondition to avoid potential race// conditions and data corruptions. The request to upload returns a 412 error if// the object's generation number does not match your precondition.Storage.BlobTargetOptionprecondition=Storage.BlobTargetOption.generationMatch();// Does an upsert operation, if the key already exists it's replaced by the new value, otherwise// it's added.BlobInfopendingUpdate=blob.toBuilder().setMetadata(newMetadata).build();storage.update(pendingUpdate,precondition);System.out.println("Updated custom metadata for object "+objectName+" in bucket "+bucketName);}}

Node.js

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

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

// Imports the Google Cloud client libraryconst{Storage}=require('@google-cloud/storage');// Creates a clientconststorage=newStorage();/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of your GCS bucket// const bucketName = 'your-unique-bucket-name';// The ID of your GCS file// const fileName = 'your-file-name';asyncfunctionsetFileMetadata(){// Optional: set a meta-generation-match precondition to avoid potential race// conditions and data corruptions. The request to set metadata is aborted if the// object's metageneration number does not match your precondition.constoptions={ifMetagenerationMatch:metagenerationMatchPrecondition,};// Set file metadata.const[metadata]=awaitstorage.bucket(bucketName).file(fileName).setMetadata({// Predefined metadata for server e.g. 'cacheControl', 'contentDisposition',// 'contentEncoding', 'contentLanguage', 'contentType'contentDisposition:'attachment; filename*=utf-8\'\'"anotherImage.jpg"',contentType:'image/jpeg',// A note or actionable items for user e.g. uniqueId, object description,// or other useful information.metadata:{description:'file description...',modified:'1900-01-01',},},options);console.log('Updated metadata for object',fileName,'in bucket ',bucketName);console.log(metadata);}setFileMetadata().catch(console.error);

PHP

For more information, see theCloud StoragePHP API reference documentation.

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

use Google\Cloud\Storage\StorageClient;/** * Set a metadata key and value on the specified object. * * @param string $bucketName The name of your Cloud Storage bucket. *        (e.g. 'my-bucket') * @param string $objectName The name of your Cloud Storage object. *        (e.g. 'my-object') */function set_metadata(string $bucketName, string $objectName): void{    $storage = new StorageClient();    $bucket = $storage->bucket($bucketName);    $object = $bucket->object($objectName);    $object->update([        'metadata' => [            'keyToAddOrUpdate' => 'value',        ]    ]);    printf('Updated custom metadata for object %s in bucket %s', $objectName, $bucketName);}

Python

For more information, see theCloud StoragePython API reference documentation.

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

fromgoogle.cloudimportstoragedefset_blob_metadata(bucket_name,blob_name):"""Set a blob's metadata."""# bucket_name = 'your-bucket-name'# blob_name = 'your-object-name'storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.get_blob(blob_name)metageneration_match_precondition=None# Optional: set a metageneration-match precondition to avoid potential race# conditions and data corruptions. The request to patch is aborted if the# object's metageneration does not match your precondition.metageneration_match_precondition=blob.metagenerationmetadata={'color':'Red','name':'Test'}blob.metadata=metadatablob.patch(if_metageneration_match=metageneration_match_precondition)print(f"The metadata for the blob{blob.name} is{blob.metadata}")

Ruby

For more information, see theCloud StorageRuby API reference documentation.

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

defset_metadatabucket_name:,file_name:# The ID of your GCS bucket# bucket_name = "your-unique-bucket-name"# The ID of your GCS object# file_name = "your-file-name"require"google/cloud/storage"storage=Google::Cloud::Storage.newbucket=storage.bucketbucket_name,skip_lookup:truefile=bucket.filefile_namefile.updatedo|file|# Fixed key file metadatafile.content_type="text/plain"# Custom file metadatafile.metadata["your-metadata-key"]="your-metadata-value"endputs"Metadata for#{file_name} has been updated."end

REST APIs

JSON API

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

  2. Create a JSON file that contains the metadata youwant to modify. For more information about metadata associated with an object, see theCloud Storage Objects resource.

    To add or modify thefixed-key metadata such ascontentType,use the following format:

    {"STANDARD_METADATA_KEY":"STANDARD_METADATA_VALUE"}

    Where:

    • STANDARD_METADATA_KEY is the key for themetadata you want to add or modify. For example,contentType.
    • STANDARD_METADATA_VALUE is the value forthe metadata you want to add or modify. For example,image/png.

    To add or modify custom metadata, use the following format:

    {"metadata":{"CUSTOM_METADATA_KEY":"CUSTOM_METADATA_VALUE"}}

    Where:

    • CUSTOM_METADATA_KEY is the custom metadatakey that you want to add or modify. For example,dogbreed.
    • CUSTOM_METADATA_VALUE is the value youwant associated with the custom metadata key. For example,shibainu.

    To delete a custom metadata entry, use the following format:

    {"metadata":{"CUSTOM_METADATA_KEY":null}}

    Where:

    • CUSTOM_METADATA_KEY is the key for thecustom metadata that you want to delete. For example,dogbreed.
  3. UsecURL to call theJSON API with aPATCH Object request:

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

    Where:

    • JSON_FILE_NAME is the path for the filethat you created in Step 2.
    • BUCKET_NAME is the name of the bucketcontaining the object whose metadata you want to edit. Forexample,my-bucket.
    • OBJECT_NAME is the URL-encoded name of theobject whose metadata you want to edit.For example,pets/dog.png, URL-encoded aspets%2Fdog.png.

Note that you can also change an object's metadata with anUPDATE Object request. When using this method, any metadatathat is not explicitly specified in the request is removed from theobject's metadata.

XML API

When working with theXML API, metadata can only be set at thetime the object is written, such as when uploading, moving, orreplacing the object. Follow instructions such asuploading an object with the following guidelines:

  • Add-H "METADATA_KEY:METADATA_VALUE"to the request header for each metadata value you are setting. Forexample,-H "Content-Type:image/png".

  • Prefixx-goog-meta- to any custom metadata values. An example ofcustom"METADATA_KEY:METADATA_VALUE"is"x-goog-meta-dogbreed:shibainu".

For more information, seeUpload an Object for XML.

What's next

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

Last updated 2025-12-15 UTC.