Viewing and editing object metadata

Go to concepts

This page describes how to view and edit the metadata associated with objects stored 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 who is allowed to access your data. See Using IAM Permissions and Creating and Managing ACLs for guides to accomplishing these tasks.

Viewing object metadata

To view the metadata associated with an object:

Console

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

    The Bucket details page opens, with the Objects tab selected.

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

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

  4. Click the more actions menu () associated with the object.

  5. Click Edit metadata.

    The overlay window that appears shows the current values for the object's editable metadata.

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

gsutil

Use the gsutil stat command:

gsutil stat gs://[BUCKET_NAME]/[OBJECT_NAME]

Where:

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

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

gs://my-awesome-bucket/cat.jpeg:
Creation time:          Fri, 03 Feb 2017 22:43:31 GMT
Update time:            Wed, 10 May 2017 18:33:07 GMT
Storage class:          STANDARD
Content-Length:         11012
Content-Type:           image/jpeg
Metadata:
    Breed:              Tabby
Hash (crc32c):          HQbzrB==
Hash (md5):             OBydg25+pPG1Cwawjsl7DA==
ETag:                   CJCh9apA9dECAEs=
Generation:             1486161811706000
Metageneration:         11

Code samples

C++

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

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

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

  std::cout << "The metadata for object " << object_metadata->name()
            << " in bucket " << object_metadata->bucket() << " is "
            << *object_metadata << "\n";
}

C#

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

private void GetMetadata(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    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($"Size:\t{storageObject.Size}");
    Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");
    Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");
    Console.WriteLine($"Updated:\t{storageObject.Updated}");
    bool? eventBasedHoldOrNull = storageObject?.EventBasedHold;
    bool eventBasedHold =
        eventBasedHoldOrNull.HasValue ? eventBasedHoldOrNull.Value : false;
    Console.WriteLine("Event-based hold enabled? {0}", eventBasedHold);
    bool? temporaryHoldOrNull = storageObject?.TemporaryHold;
    bool temporaryHold =
        temporaryHoldOrNull.HasValue ? temporaryHoldOrNull.Value : false;
    Console.WriteLine("Temporary hold enabled? {0}", temporaryHold);
    Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getMetadata prints all of the object attributes.
func getMetadata(w io.Writer, bucket, object string) (*storage.ObjectAttrs, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, 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)
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Object(%q).Attrs: %v", 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, "\n\nMetadata\n")
	for key, value := range attrs.Metadata {
		fmt.Fprintf(w, "\t%v = %v\n", key, value)
	}
	return attrs, nil
}

Java

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

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;
import java.util.Map;

public class GetObjectMetadata {
  public static void getObjectMetadata(String projectId, String bucketName, String blobName)
      throws StorageException {
    // 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();

    // Select all fields
    // Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROL
    Blob blob =
        storage.get(bucketName, blobName, Storage.BlobGetOption.fields(Storage.BlobField.values()));

    // Print blob metadata
    System.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("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: " + new Date(blob.getCreateTime()));
    System.out.println("Last Metadata Update: " + new Date(blob.getUpdateTime()));
    Boolean temporaryHoldIsEnabled = (blob.getTemporaryHold() != null && blob.getTemporaryHold());
    System.out.println("temporaryHold: " + (temporaryHoldIsEnabled ? "enabled" : "disabled"));
    Boolean eventBasedHoldIsEnabled =
        (blob.getEventBasedHold() != null && blob.getEventBasedHold());
    System.out.println("eventBasedHold: " + (eventBasedHoldIsEnabled ? "enabled" : "disabled"));
    if (blob.getRetentionExpirationTime() != null) {
      System.out.println("retentionExpirationTime: " + new Date(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 the Cloud Storage Node.js API reference documentation.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'File to access, e.g. file.txt';

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

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

async function getMetadata() {
  // Gets the metadata for the file
  const [metadata] = await storage
    .bucket(bucketName)
    .file(filename)
    .getMetadata();

  console.log(`File: ${metadata.name}`);
  console.log(`Bucket: ${metadata.bucket}`);
  console.log(`Storage class: ${metadata.storageClass}`);
  console.log(`Self link: ${metadata.selfLink}`);
  console.log(`ID: ${metadata.id}`);
  console.log(`Size: ${metadata.size}`);
  console.log(`Updated: ${metadata.updated}`);
  console.log(`Generation: ${metadata.generation}`);
  console.log(`Metageneration: ${metadata.metageneration}`);
  console.log(`Etag: ${metadata.etag}`);
  console.log(`Owner: ${metadata.owner}`);
  console.log(`Component count: ${metadata.component_count}`);
  console.log(`Crc32c: ${metadata.crc32c}`);
  console.log(`md5Hash: ${metadata.md5Hash}`);
  console.log(`Cache-control: ${metadata.cacheControl}`);
  console.log(`Content-type: ${metadata.contentType}`);
  console.log(`Content-disposition: ${metadata.contentDisposition}`);
  console.log(`Content-encoding: ${metadata.contentEncoding}`);
  console.log(`Content-language: ${metadata.contentLanguage}`);
  console.log(`Media link: ${metadata.mediaLink}`);
  console.log(`KMS Key Name: ${metadata.kmsKeyName}`);
  console.log(`Temporary Hold: ${metadata.temporaryHold}`);
  console.log(`Event-based hold: ${metadata.eventBasedHold}`);
  console.log(
    `Effective Expiration Time: ${metadata.effectiveExpirationTime}`
  );
  console.log(`Metadata: ${metadata.metadata}`);
}

getMetadata().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * List object metadata.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function object_metadata($bucketName, $objectName)
{
    $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: " . ($info['temporaryHold'] ? "enabled" : "disabled") . PHP_EOL);
    }
    if (isset($info['eventBasedHold'])) {
        printf("Event-based hold: " . ($info['eventBasedHold'] ? "enabled" : "disabled") . PHP_EOL);
    }
    if (isset($info['retentionExpirationTime'])) {
        printf("retentionExpirationTime: " . $info['retentionExpirationTime'] . PHP_EOL);
    }
    if (isset($info['metadata'])) {
        printf('Metadata: %s', print_r($info['metadata'], true));
    }
}

Python

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

from google.cloud import storage


def blob_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)
    blob = bucket.get_blob(blob_name)

    print("Blob: {}".format(blob.name))
    print("Bucket: {}".format(blob.bucket.name))
    print("Storage class: {}".format(blob.storage_class))
    print("ID: {}".format(blob.id))
    print("Size: {} bytes".format(blob.size))
    print("Updated: {}".format(blob.updated))
    print("Generation: {}".format(blob.generation))
    print("Metageneration: {}".format(blob.metageneration))
    print("Etag: {}".format(blob.etag))
    print("Owner: {}".format(blob.owner))
    print("Component count: {}".format(blob.component_count))
    print("Crc32c: {}".format(blob.crc32c))
    print("md5_hash: {}".format(blob.md5_hash))
    print("Cache-control: {}".format(blob.cache_control))
    print("Content-type: {}".format(blob.content_type))
    print("Content-disposition: {}".format(blob.content_disposition))
    print("Content-encoding: {}".format(blob.content_encoding))
    print("Content-language: {}".format(blob.content_language))
    print("Metadata: {}".format(blob.metadata))
    print("Temporary hold: ", "enabled" if blob.temporary_hold else "disabled")
    print(
        "Event based hold: ",
        "enabled" if blob.event_based_hold else "disabled",
    )
    if blob.retention_expiration_time:
        print(
            "retentionExpirationTime: {}".format(
                blob.retention_expiration_time
            )
        )

Ruby

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

# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage"

require "google/cloud/storage"

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

puts "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 "Metadata:"
file.metadata.each do |key, value|
  puts " - #{key} = #{value}"
end

REST APIs

JSON API

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

    curl -X GET \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket containing the object whose metadata you want to view. For example, my-bucket.
    • [OBJECT_NAME] is the name of the object whose metadata you want to view. For example, pets/dog.png.

XML API

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

    curl -I HEAD \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

    Where:

    • [OAUTH2_TOKEN] is the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket containing the object whose metadata you want to view. For example, my-bucket.
    • [OBJECT_NAME] is the name of the object whose metadata you want to view. For example, pets/dog.png.

Editing object metadata

To edit the metadata associated with an object:

Console

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

    The Bucket details page opens, with the Objects tab selected.

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

  4. Click the more actions menu () associated with the object.

  5. Click Edit metadata.

  6. In the overlay window that appears, make the desired edits to the metadata.

    • For standard metadata fields, edit the Value.

    • Add your own custom metadata by clicking the + Add item button.

    • You can edit both the Key and Value of your custom metadata.

    • Delete your custom metadata by clicking the associated X.

  7. Click Save.

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

gsutil

Use the gsutil setmeta -h command:

gsutil setmeta -h "[METADATA_KEY]:[METADATA_VALUE]" gs://[BUCKET_NAME]/[OBJECT_NAME]

Where:

  • [METADATA_KEY] is the key for the metadata you want to set. For example, Content-Type.
  • [METADATA_VALUE] is the value for the metadata you want to set. For example, image/png.
  • [BUCKET_NAME] is the name of the bucket containing the object whose metadata you want to edit. For example, my-bucket.
  • [OBJECT_NAME] is the name of the object whose metadata you want to edit. For example, pets/dog.png.

If successful, the response looks like the following example:

Operation completed over 1 objects.

Note that if you are adding custom metadata with gsutil, you must prefix your metadata key with x-goog-meta- for gsutil to recognize that this is a custom metadata attribute, rather than a standard HTTP header. The metadata key itself is not stored with the x-goog-meta- prefix. An example of custom "[METADATA_KEY]:[METADATA_VALUE]" is "x-goog-meta-dogbreed:shibainu".

Code samples

C++

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

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& 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,
                          gcs::Generation(object_metadata->generation()));

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

C#

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

To edit the metadata associated with an object using C#, see the PatchObject reference documentation.

Go

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

To edit the metadata associated with an object using Go, see the ObjectHandle reference documentation.

Java

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

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
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.
    blob.toBuilder().setMetadata(newMetadata).build().update();

    System.out.println(
        "Updated custom metadata for object " + objectName + " in bucket " + bucketName);
  }
}

Node.js

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

To edit the metadata associated with an object using NodeJS, see the File reference documentation.

PHP

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

To edit the metadata associated with an object using PHP, see the Google Cloud Client Library reference documentation.

Python

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

To edit the metadata associated with an object using Python, see the Blobs / Objects reference documentation.

Ruby

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

To edit the metadata associated with an object using Ruby, see the Google::Cloud::Storage::File class reference documentation.

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Create a .json file that contains the metadata you wish to modify.

    To add or modify fixed-key metadata such as contentType, use the following format:

    {
      "[STANDARD_METADATA_KEY]": "[STANDARD_METADATA_VALUE]"
    }

    Where:

    • [STANDARD_METADATA_KEY] is the key for the metadata you want to add or modify. For example, Content-Type.
    • [STANDARD_METADATA_VALUE] is the value for the 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 metadata key that you want to add or modify. For example, dogbreed.
    • [CUSTOM_METADATA_VALUE] is the value you want 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 the custom metadata that you want to delete. For example, dogbreed.
  3. Use cURL to call the JSON API with a PATCH Object request:

    curl -X PATCH --data-binary @[JSON_FILE_NAME].json \
      -H "Authorization: Bearer [OAUTH2_TOKEN]" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

    Where:

    • [JSON_FILE_NAME] is the name of the JSON file you created in Step 2.
    • [OAUTH2_TOKEN] is the name of the access token you generated in Step 1.
    • [BUCKET_NAME] is the name of the bucket containing the object whose metadata you want to edit. For example, my-bucket.
    • [OBJECT_NAME] is the name of the object whose metadata you want to edit. For example, pets/dog.png.

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

XML API

When working with the XML API, metadata can only be set at the time the object is written, such as when uploading, moving, or overwriting the object. Follow instructions such as uploading an object with the following guidelines:

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

  • Prefix x-goog-meta- to any custom metadata values. An example of custom "[METADATA_KEY]:[METADATA_VALUE]" is "x-goog-meta-dogbreed:shibainu".

For more information, see Upload an Object for XML.

What's next