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 API Client Libraries, in Client Libraries Explained.

Installing the client library

C++

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

C#

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

For more information, see Setting Up a Go Development Environment.

go get -u cloud.google.com/go/storage

Java

For more information, see Setting Up a Java Development Environment.

Se você estiver usando o Maven, adicione o código abaixo ao arquivo pom.xml. Para mais informações sobre BOMs, consulte BOM das bibliotecas do Google Cloud Platform.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>20.8.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-storage</artifactId>
  </dependency>

Se você estiver usando o Gradle, adicione isto às dependências:

implementation platform('com.google.cloud:libraries-bom:20.8.0')

compile 'com.google.cloud:google-cloud-storage'

Se você estiver usando o sbt, adicione o seguinte às suas dependências:

libraryDependencies += "com.google.cloud" % "google-cloud-storage" % "1.118.0"

Se você estiver usando o Visual Studio Code, o IntelliJ ou o Eclipse, poderá adicionar bibliotecas de cliente ao projeto usando estes plug-ins de IDE:

Os plug-ins também oferecem outras funcionalidades, como gerenciamento de chaves de contas de serviço. Consulte a documentação de cada plug-in para mais detalhes.

Node.js

For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/storage

PHP

For more information, see Using PHP on Google Cloud.

composer require google/cloud-storage

Python

For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-storage

Ruby

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.

Console do Cloud

Crie uma conta de serviço:

  1. No Console do Cloud, acesse a página Criar conta de serviço.

    Acesse Criar conta de serviço
  2. Selecione um projeto.
  3. No campo Nome da conta de serviço, insira um nome. O Console do Cloud preenche o campo ID da conta de serviço com base nesse nome.

    No campo Descrição da conta de serviço, insira uma descrição. Por exemplo, Service account for quickstart.

  4. Clique em Criar.
  5. Clique no campo Selecionar um papel.

    Em Acesso rápido, clique em Básico e em Proprietário.

  6. Clique em Continuar.
  7. Clique em Concluído para terminar a criação da conta de serviço.

    Não feche a janela do navegador. Você vai usá-lo na próxima etapa.

Crie uma chave de conta de serviço:

  1. No Console do Cloud, clique no endereço de e-mail da conta de serviço que você criou.
  2. Clique em Chaves.
  3. Clique em Adicionar chave e em Criar nova chave.
  4. Clique em Criar. O download de um arquivo de chave JSON é feito no seu computador.
  5. Clique em Fechar.

Linha de comando

É possível executar os seguintes comandos usando o SDK do Cloud na máquina local ou no Cloud Shell.

  1. Crie a conta de serviço. Substitua NAME por um nome para a conta de serviço.

    gcloud iam service-accounts create NAME
  2. Conceda permissões à conta de serviço. Substitua PROJECT_ID pelo ID do seu projeto.

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Gere o arquivo de chave. Substitua FILE_NAME pelo nome do arquivo de chave.

    gcloud iam service-accounts keys create FILE_NAME.json --iam-account=NAME@PROJECT_ID.iam.gserviceaccount.com

Forneça credenciais de autenticação ao código do aplicativo definindo a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS. Essa variável só se aplica à sessão de shell atual. Assim, se você abrir uma nova sessão, precisará definir a variável novamente.

Linux ou macOS

export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Substitua KEY_PATH pelo caminho do arquivo JSON que contém a chave da conta de serviço.

Exemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Substitua KEY_PATH pelo caminho do arquivo JSON que contém a chave da conta de serviço.

Exemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Para prompt de comando:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Substitua KEY_PATH pelo caminho do arquivo JSON que contém a chave da conta de serviço.

Using the client library

The following example shows how to use the client library.

C++

#include "google/cloud/storage/client.h"
#include <iostream>
void StorageQuickstart(std::string const& bucket_name) {
  // Create an 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.
  auto client = gcs::Client();

  // Create a bucket
  google::cloud::StatusOr<gcs::BucketMetadata> metadata = client.CreateBucket(
      bucket_name, gcs::BucketMetadata().set_location("US").set_storage_class(
                       gcs::storage_class::Standard()));
  if (!metadata) throw std::runtime_error(metadata.status().message());

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

C#


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class CreateBucketSample
{
    public Bucket CreateBucket(
        string projectId = "your-project-id",
        string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.CreateBucket(projectId, bucketName);
        Console.WriteLine($"Created {bucketName}.");
        return bucket;
    }
}

Go


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

import (
	"context"
	"fmt"
	"log"
	"time"

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

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)
	}
	defer client.Close()

	// 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)
}

Java

// Imports the Google Cloud client library
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

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());
  }
}

Node.js

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

// For more information on ways to initialize Storage, please see
// https://googleapis.dev/nodejs/storage/latest/Storage.html

// Creates a client using Application Default Credentials
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.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

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

createBucket().catch(console.error);

PHP

# 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.';

Python

# Imports the Google Cloud client library
from google.cloud 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(bucket.name))

Ruby

def quickstart bucket_name:
  # Imports the Google Cloud client library
  require "google/cloud/storage"

  # Instantiates a client
  storage = Google::Cloud::Storage.new

  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # Creates the new bucket
  bucket = storage.create_bucket bucket_name

  puts "Bucket #{bucket.name} was created."
end

More Examples

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

Additional resources

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how Cloud Storage performs in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Try Cloud Storage free