Cloud Storage Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Google Cloud Storage API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library


See the GitHub README for details about this client library's requirements and install dependencies.


For more information, see Setting Up a C# Development Environment. If you are using Visual Studio 2017 or higher, open nuget package manager window and type the following:

Install-Package Google.Cloud.Storage.V1

If you are using .NET Core command-line interface tools to install your dependencies, run the following command:

dotnet add package Google.Cloud.Storage.V1


go get -u


For more information, see Setting Up a Java Development Environment. 如果您使用 Maven,請將下列指令新增到 pom.xml 檔案中:

如果您使用 Gradle,請將下列指令新增到依附元件中:
compile ''
如果您使用 SBT,請將下列指令新增到依附元件中:
libraryDependencies += "" % "google-cloud-storage" % "1.100.0"

如果您使用 IntelliJ 或 Eclipse,可以利用下列 IDE 外掛程式,將用戶端程式庫新增到專案中:



For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/storage


composer require google/cloud-storage


For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-storage


For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-storage

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

GCP 主控台

  1. 在 GCP 主控台中,前往「Create service account key」(建立服務帳戶金鑰) 頁面。

    前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面
  2. 從 [Service account] (服務帳戶) 清單中選取 [New service account] (新增服務帳戶)
  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
  4. 從 [Role] (角色) 清單中,選取 [Project] (專案) > [Owner] (擁有者)

    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。以後您可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  5. 點選 [建立]。一個包含您金鑰的 JSON 檔案會下載到電腦中。


您可以使用本機電腦上的 Cloud SDK,或在 Cloud Shell 內執行下列指令。

  1. 建立服務帳戶。將 [NAME] 換成服務帳戶的名稱。

    gcloud iam service-accounts create [NAME]
  2. 向服務帳戶授予權限。用您的專案 ID 取代 [PROJECT_ID]

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID]" --role "roles/owner"
    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。您稍後可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  3. 產生金鑰檔案。用金鑰檔案的名稱取代 [FILE_NAME]

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID]

設定環境變數 GOOGLE_APPLICATION_CREDENTIALS 來為應用程式程式碼提供驗證憑證。 將 [PATH] 改成包含您的服務帳戶金鑰的 JSON 檔案路徑,並將 [FILE_NAME] 改成檔案名稱。 此變數僅適用於您目前的殼層工作階段,所以如果您開啟新的工作階段,請再次設定變數。

Linux 或 macOS



export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"


使用 PowerShell:






Using the client library

The following example shows how to use the client library.


#include "google/cloud/storage/client.h"
#include <iostream>

int main(int argc, char* argv[]) {
  if (argc != 3) {
    std::cerr << "Missing project id and/or bucket name.\n";
    std::cerr << "Usage: storage_quickstart <bucket-name> <project-id>\n";
    return 1;
  std::string bucket_name = argv[1];
  std::string project_id = argv[2];

  // Create aliases to make the code easier to read.
  namespace gcs = google::cloud::storage;

  // Create a client to communicate with Google Cloud Storage. This client
  // uses the default configuration for authentication and project id.
  google::cloud::StatusOr<gcs::Client> client =
  if (!client) {
    std::cerr << "Failed to create Storage Client, status=" << client.status()
              << "\n";
    return 1;

  google::cloud::StatusOr<gcs::BucketMetadata> bucket_metadata =
      client->CreateBucketForProject(bucket_name, project_id,

  if (!bucket_metadata) {
    std::cerr << "Error creating bucket " << bucket_name
              << ", status=" << bucket_metadata.status() << "\n";
    return 1;

  std::cout << "Created bucket " << bucket_metadata->name() << "\n";

  return 0;


using Google.Cloud.Storage.V1;
using System;
using System.Diagnostics;

namespace GoogleCloudSamples
    class StorageQuickstart
        static void Main(string[] args)
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            // Instantiates a client.
            using (StorageClient storageClient = StorageClient.Create())
                // The name for the new bucket.
                string bucketName = projectId + "-test-bucket";
                    // Creates the new bucket.
                    storageClient.CreateBucket(projectId, bucketName);
                    Console.WriteLine($"Bucket {bucketName} created.");
                catch (Google.GoogleApiException e)
                when (e.Error.Code == 409)
                    // The bucket already exists.  That's fine.


// Sample storage-quickstart creates a Google Cloud Storage bucket.
package main

import (


func main() {
	ctx := context.Background()

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Creates a client.
	client, err := storage.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)

	// Sets the name for the new bucket.
	bucketName := "my-new-bucket"

	// Creates a Bucket instance.
	bucket := client.Bucket(bucketName)

	// Creates the new bucket.
	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()
	if err := bucket.Create(ctx, projectID, nil); err != nil {
		log.Fatalf("Failed to create bucket: %v", err)

	fmt.Printf("Bucket %v created.\n", bucketName)


// Imports the Google Cloud client library

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // The name for the new bucket
    String bucketName = args[0];  // "my-new-bucket";

    // Creates the new bucket
    Bucket bucket = storage.create(BucketInfo.of(bucketName));

    System.out.printf("Bucket %s created.%n", bucket.getName());


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

// Creates a client
const storage = new Storage();
// Creates a client from a Google service account key.
// const storage = new Storage({keyFilename: "key.json"});

 * TODO(developer): Uncomment these variables before running the sample.
// const bucketName = 'bucket-name';

async function createBucket() {
  // Creates the new bucket
  await storage.createBucket(bucketName);
  console.log(`Bucket ${bucketName} created.`);



# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$storage = new StorageClient([
    'projectId' => $projectId

# The name for the new bucket
$bucketName = 'my-new-bucket';

# Creates the new bucket
$bucket = $storage->createBucket($bucketName);

echo 'Bucket ' . $bucket->name() . ' created.';


# Imports the Google Cloud client library
from import storage

# Instantiates a client
storage_client = storage.Client()

# The name for the new bucket
bucket_name = "my-new-bucket"

# Creates the new bucket
bucket = storage_client.create_bucket(bucket_name)

print("Bucket {} created.".format(


# Imports the Google Cloud client library
require "google/cloud/storage"

# Your Google Cloud Platform project ID
project_id = "YOUR_PROJECT_ID"

# Instantiates a client
storage = project_id: project_id

# The name for the new bucket
bucket_name = "my-new-bucket"

# Creates the new bucket
bucket = storage.create_bucket bucket_name

puts "Bucket #{} was created."

More Examples

For more examples of using client libraries with Cloud Storage, see the following how-to guides:

Additional resources