google-cloud-platformgoogle-cloud-storagecloud-storage

Is the project Id mandatory when using the GCP Cloud Storage API?


I am currently developing using the Cloud Storage XML API because managing a large number of dependencies seems challenging, and I only want to use the necessary parts from Cloud Storage.

However, I've encountered some questions while developing.

My first question is about where the projectId is being used. Despite searching the XML API documentation in the following link, I had difficulty finding where and why the projectId is used. - https://cloud.google.com/storage/docs/xml-api/reference-methods

However, the projectId is set in the Cloud Storage SDK examples. When I directly call the Cloud Storage XML API, I can use it without the projectId, which has been a point of confusion for me.

https://cloud.google.com/storage/docs/listing-objects?hl=ko#storage-list-objects-java

import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class ListObjects {
  public static void listObjects(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();
    Page<Blob> blobs = storage.list(bucketName);

    for (Blob blob : blobs.iterateAll()) {
      System.out.println(blob.getName());
    }
  }
}

My second question is, if I need to set the projectId or if I do set it, should I be setting the projectId of the project that the bucket belongs to, or should I be setting the projectId of the project that the service account belongs to?

I'm confused because I understand that buckets and service accounts can be managed on a per-project basis.

I would appreciate any help you can provide.


Solution

  • Some APIs benefit from or require the Project ID (list buckets). Other APIs do not use the Project ID at all (list bucket objects). To know for certain which APIs require the Project ID consult the JSON API.

    Cloud Storage JSON API

    Which Project ID to use is also documented. For example, List Buckets requires the Project ID that owns the buckets link. Most of the JSON APIs do not use the Project ID at all.

    For your example StorageOptions.newBuilder().setProjectId(projectId).build().getService();, the Project ID is stored for possible use by methods that you later call. Specify the Project ID that owns the bucket(s) that you plan to access. Cloud IAM does support cross-project bucket access. That means you can specify one Project ID and access buckets owned by a different Project ID.