Making data public

This page shows you how to make objects you own readable to everyone on the public internet. To learn how to access data that has been made public, see Accessing Public Data.

Making individual objects publicly readable

To make individual objects readable to everyone on the public internet:

Console

  1. Open the Cloud Storage browser in the Google Cloud Console.
    Open the Cloud Storage browser
  2. Check the Access control column for the bucket containing the object you want to make public. If the column reads Fine-grained, proceed to the next step. If the column reads Uniform, you cannot use the following steps to make individual objects in the bucket publicly readable. Instead, grant public readability to all objects in the bucket, or use signed URLs.

  3. Click on the name of the bucket that contains the object you want to make public, and navigate to the object if it's in a subdirectory.

  4. Click the more actions menu () associated with the object that you want to make public.

  5. Select Edit permissions from the drop-down menu. If the option does not exist, you may have Uniform access control enabled. See Step 2 for more details.

  6. In the overlay that appears, click the + Add entry button.

  7. Add a permission for allUsers.

    • Select Public for the Entity.
    • Select allUsers for the Name.
    • Select Reader for the Access.
  8. Click Save.

Once shared publicly, a link icon appears in the public access column. You can click on this icon to get the URL for the object.

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

gsutil

Use the gsutil acl ch command:

gsutil acl ch -u AllUsers:R gs://BUCKET_NAME/OBJECT_NAME

Where:

  • BUCKET_NAME is the name of the bucket containing the object you want to make public. For example, my-bucket.
  • OBJECT_NAME is the name of the object you want to make public. For example, pets/dog.png.

If successful, the response looks like the following example:

Updated ACL on gs://my-bucket/pets/dog.png

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> updated = client.PatchObject(
      bucket_name, object_name, gcs::ObjectMetadataPatchBuilder(),
      gcs::PredefinedAcl::PublicRead());

  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.

private void MakePublic(string bucketName, string objectName)
{
    var storage = StorageClient.Create();
    var storageObject = storage.GetObject(bucketName, objectName);
    storageObject.Acl = storageObject.Acl ?? new List<ObjectAccessControl>();
    storage.UpdateObject(storageObject, new UpdateObjectOptions
    {
        PredefinedAcl = PredefinedObjectAcl.PublicRead
    });
    Console.WriteLine(objectName + " is now public and can be fetched from " +
        storageObject.MediaLink);
}

Go

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

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

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

// makePublic gives all users read access to an object.
func makePublic(w io.Writer, bucket, object string, entity storage.ACLEntity, role storage.ACLRole) 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()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %v", err)
	}
	fmt.Fprintf(w, "Blob %v is now publicly accessible.\n", object)
	return nil
}

Java

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

import com.google.cloud.storage.Acl;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class MakeObjectPublic {
  public static void makeObjectPublic(String projectId, String bucketName, String objectName) {
    // String projectId = "your-project-id";
    // String bucketName = "your-bucket-name";
    // String objectName = "your-object-name";
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    storage.createAcl(blobId, Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));

    System.out.println(
        "Object " + objectName + " in bucket " + bucketName + " was made publicly readable");
  }
}

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 make public, 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 makePublic() {
  // Makes the file public
  await storage.bucket(bucketName).file(filename).makePublic();

  console.log(`gs://${bucketName}/${filename} is now public.`);
}

makePublic().catch(console.error);

PHP

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

use Google\Cloud\Storage\StorageClient;

/**
 * Make an object publically accessible.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 *
 * @return void
 */
function make_public($bucketName, $objectName)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
    printf('gs://%s/%s is now public' . PHP_EOL, $bucketName, $objectName);
}

Python

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

from google.cloud import storage


def make_blob_public(bucket_name, blob_name):
    """Makes a blob publicly accessible."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.make_public()

    print(
        "Blob {} is publicly accessible at {}".format(
            blob.name, blob.public_url
        )
    )

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 to make public"

require "google/cloud/storage"

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

file.acl.public!

puts "#{file.name} is publicly accessible at #{file.public_url}"

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 following information:

    {
      "entity": "allUsers",
      "role": "READER"
    }
  3. Use cURL to call the JSON API with an Insert ACL request:

    curl -X POST --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/acl"

    Where:

    • JSON_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the access token you created in Step 1.
    • BUCKET_NAME is the name of the bucket containing the object you want to make public. For example, my-bucket.
    • OBJECT_NAME is the name of the object you want to make public. 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. Create a .xml file that contains the following information:

    <AccessControlList>
      <Entries>
        <Entry>
          <Scope type="AllUsers"/>
          <Permission>READ</Permission>
        </Entry>
      </Entries>
    </AccessControlList>
  3. Use cURL to call the XML API with a Set Object ACL request:

    curl -X PUT --data-binary @XML_FILE_NAME.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME?acl"

    Where:

    • XML_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the access token you created in Step 1.
    • BUCKET_NAME is the name of the bucket containing the object you want to make public. For example, my-bucket.
    • OBJECT_NAME is the name of the object you want to make public. For example, pets/dog.png.

Making all objects in a bucket publicly readable

To make all objects in a bucket readable to everyone on the public internet:

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 you want to make public.

  3. Select the Permissions tab near the top of the page.

  4. Click the Add members button.

    The Add members dialog box appears.

  5. In the New members field, enter allUsers.

  6. In the Select a role drop down, select the Cloud Storage sub-menu, and click the Storage Object Viewer option.

  7. Click Save.

Once shared publicly, a link icon appears for each object in the public access column. You can click on this icon to get the URL for the object.

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

gsutil

Use the gsutil iam ch command:

gsutil iam ch allUsers:objectViewer gs://BUCKET_NAME

Where BUCKET_NAME is the name of the bucket whose objects you want to make public. For example, my-bucket.

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) {
  StatusOr<google::cloud::IamPolicy> current_policy =
      client.GetBucketIamPolicy(bucket_name);

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

  current_policy->bindings.AddMember("roles/storage.objectViewer",
                                     "allUsers");

  // Update the policy. Note the use of `gcs::IfMatchEtag` to implement
  // optimistic concurrency control.
  StatusOr<google::cloud::IamPolicy> updated_policy =
      client.SetBucketIamPolicy(bucket_name, *current_policy,
                                gcs::IfMatchEtag(current_policy->etag));

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

  auto role = updated_policy->bindings.find("roles/storage.objectViewer");
  if (role == updated_policy->bindings.end()) {
    std::cout << "Cannot find 'roles/storage.objectViewer' in the updated"
              << " policy. This can happen if another application updates"
              << " the IAM policy at the same time. Please retry the"
              << " operation.\n";
    return;
  }
  auto member = role->second.find("allUsers");
  if (member == role->second.end()) {
    std::cout << "'allUsers' is not a member of the"
              << " 'roles/storage.objectViewer' role in the updated"
              << " policy. This can happen if another application updates"
              << " the IAM policy at the same time. Please retry the"
              << " operation.\n";
    return;
  }
  std::cout << "IamPolicy successfully updated for bucket " << bucket_name
            << '\n';
}

Java

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

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.StorageRoles;

public class MakeBucketPublic {
  public static void makeBucketPublic(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Policy originalPolicy = storage.getIamPolicy(bucketName);
    storage.setIamPolicy(
        bucketName,
        originalPolicy
            .toBuilder()
            .addIdentity(StorageRoles.objectViewer(), Identity.allUsers()) // All users can view
            .build());

    System.out.println("Bucket " + bucketName + " is now publicly readable");
  }
}

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 following information:

    {
      "bindings":[
        {
          "role": "roles/storage.objectViewer",
          "members":["allUsers"]
        }
      ]
    }
  3. Use cURL to call the JSON API with a PUT Bucket request:

    curl -X PUT --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/iam"

    Where:

    • JSON_FILE_NAME is the name of the file you created in Step 2.
    • OAUTH2_TOKEN is the access token you created in Step 1.
    • BUCKET_NAME is the name of the bucket whose objects you want to make public. For example, my-bucket.

XML API

Making all objects in a bucket publicly readable is not supported by the XML API. Use gsutil or the JSON API instead.

What's next