Set an object's metadata

Set the metadata for an object in a Cloud Storage bucket.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample


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

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

public class SetObjectMetadataSample
    public Google.Apis.Storage.v1.Data.Object SetObjectMetadata(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        string key = "key-to-add",
        string value = "value-to-add")
        var storage = StorageClient.Create();
        var file = storage.GetObject(bucketName, objectName);

        if (file.Metadata == null)
            file.Metadata = new Dictionary<string, string>();
        file.Metadata.Add(key, value);

        file = storage.UpdateObject(file);
        Console.WriteLine($"Updated custom metadata for object {objectName} in bucket {bucketName}");
        return file;


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

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& key,
   std::string const& value) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.GetObjectMetadata(bucket_name, object_name);

  if (!object_metadata) {
    throw std::runtime_error(object_metadata.status().message());

  gcs::ObjectMetadata desired = *object_metadata;
  desired.mutable_metadata().emplace(key, value);

  StatusOr<gcs::ObjectMetadata> updated =
      client.UpdateObject(bucket_name, object_name, desired,

  if (!updated) throw std::runtime_error(updated.status().message());
  std::cout << "Object updated. The full metadata after the update is: "
            << *updated << "\n";


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

import (


// setMetadata sets an object's metadata.
func setMetadata(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	defer client.Close()

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

	o := client.Bucket(bucket).Object(object)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to upload is aborted if the
	// object's generation number does not match your precondition.
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("object.Attrs: %v", 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 {
		return fmt.Errorf("ObjectHandle(%q).Update: %v", object, err)
	fmt.Fprintf(w, "Updated custom metadata for object %v in bucket %v.\n", object, bucket)
	return nil


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

import java.util.HashMap;
import java.util.Map;

public class SetObjectMetadata {
  public static void setObjectMetadata(String projectId, String bucketName, String objectName) {
    // 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";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Map<String, String> newMetadata = new HashMap<>();
    newMetadata.put("keyToAddOrUpdate", "value");
    Blob blob = storage.get(bucketName, objectName);
    // Does an upsert operation, if the key already exists it's replaced by the new value, otherwise
    // it's added.

        "Updated custom metadata for object " + objectName + " in bucket " + bucketName);


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

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

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

 * 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';

async function setFileMetadata() {
  // Set file metadata.
  const [metadata] = await storage
      // 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',

    'Updated metadata for object',
    'in bucket ',



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

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.
 * @param string $objectName The name of your Cloud Storage object.
function set_metadata($bucketName, $objectName)
    // $bucketName = 'my-bucket';
    // $objectName = 'my-object';

    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
        'metadata' => [
            'keyToAddOrUpdate' => 'value',

    printf('Updated custom metadata for object %s in bucket %s', $objectName, $bucketName);


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

from import storage

def set_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)
    metadata = {'color': 'Red', 'name': 'Test'}
    blob.metadata = metadata

    print(f"The metadata for the blob {} is {blob.metadata}")


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

def set_metadata bucket_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 =
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.update do |file|
    # Fixed key file metadata
    file.content_type = "text/plain"

    # Custom file metadata
    file.metadata["your-metadata-key"] = "your-metadata-value"

  puts "Metadata for #{file_name} has been updated."

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.