Datastore mode Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Google Cloud Datastore 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

C#

For more information, see Setting Up a C# Development Environment.
Install-Package Google.Cloud.Datastore.V1

Go

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

Java

For more information, see Setting Up a Java Development Environment. Se você está usando o Maven, adicione ao seu arquivo pom.xml:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-datastore</artifactId>
  <version>1.49.0</version>
</dependency>
Se você está usando o Gradle, adicione às suas dependências:
compile 'com.google.cloud:google-cloud-datastore:1.49.0'
Se você está usando o SBT, adicione às suas dependências:
libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "1.49.0"

Node.js

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

PHP

composer require google/cloud-datastore

Python

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

Ruby

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

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 more information, see the GCP authentication documentation .

Console do GCP

  1. Acesse a página Criar chave da conta de serviço no Console do GCP.

    Acessar a página "Criar chave da conta de serviço"
  2. Na lista suspensa Conta de serviço, selecione Nova conta de serviço.
  3. Insira um nome no campo Nome da conta de serviço.
  4. Na lista suspensa Papel, selecione Projeto > Proprietário.

    Observação: o campo Papel autoriza sua conta de serviço a acessar recursos. É possível visualizar e alterar esse campo mais tarde no Console do GCP. Para desenvolver um aplicativo de produção, especifique permissões mais granulares do que Projeto> Proprietário. Para mais informações, consulte Como atribuir papéis a contas de serviço.
  5. Clique em Criar. O download de um arquivo JSON que contém sua chave é feito no seu computador.

Linha de comando

Você pode executar os seguintes comandos usando o Cloud SDK na sua máquina local ou no Cloud Shell.

  1. Crie a conta de serviço. Substitua [NAME] pelo nome que você quer atribuir à sua conta de serviço.

    gcloud iam service-accounts create [NAME]
  2. Conceda permissões à conta de serviço. Substitua [PROJECT-ID] pelo código do projeto.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Observação: o campo Papel autoriza sua conta de serviço a acessar recursos. É possível visualizar e alterar esse campo mais tarde no Console do GCP. Para desenvolver um aplicativo de produção, especifique permissões mais granulares do que Projeto > Proprietário. Para mais informações, consulte Como atribuir papéis a contas de serviço.
  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

Para fornecer credenciais de autenticação ao código do seu aplicativo, configure a variável de ambiente GOOGLE_APPLICATION_CREDENTIALS. Substitua [PATH] pelo caminho do arquivo JSON que contém a chave da sua conta de serviço e [FILE_NAME] pelo nome do arquivo.

Linux ou Mac OS X

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por exemplo:

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

Windows

Com o PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por exemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

Com o prompt de comando:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

Before trying this sample, follow the C# setup instructions in Setting Up a C# Development Environment . For more information, see the Datastore mode C# API reference documentation .

using Google.Cloud.Datastore.V1;

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

            // Instantiates a client
            DatastoreDb db = DatastoreDb.Create(projectId);

            // The kind for the new entity
            string kind = "Task";
            // The name/ID for the new entity
            string name = "sampletask1";
            KeyFactory keyFactory = db.CreateKeyFactory(kind);
            // The Cloud Datastore key for the new entity
            Key key = keyFactory.CreateKey(name);

            var task = new Entity
            {
                Key = key,
                ["description"] = "Buy milk"
            };
            using (DatastoreTransaction transaction = db.BeginTransaction())
            {
                // Saves the task
                transaction.Upsert(task);
                transaction.Commit();

                Console.WriteLine($"Saved {task.Key.Path[0].Name}: {(string)task["description"]}");
            }
        }
    }
}

Go

To use this sample, prepare your machine for Go development, and complete the Datastore mode quickstart. For more information, see the Datastore mode Go API reference documentation .

// Sample datastore-quickstart fetches an entity from Google Cloud Datastore.
package main

import (
	"context"
	"fmt"
	"log"

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

type Task struct {
	Description string
}

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

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

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

	// Sets the kind for the new entity.
	kind := "Task"
	// Sets the name/ID for the new entity.
	name := "sampletask1"
	// Creates a Key instance.
	taskKey := datastore.NameKey(kind, name, nil)

	// Creates a Task instance.
	task := Task{
		Description: "Buy milk",
	}

	// Saves the new entity.
	if _, err := client.Put(ctx, taskKey, &task); err != nil {
		log.Fatalf("Failed to save task: %v", err)
	}

	fmt.Printf("Saved %v: %v\n", taskKey, task.Description)
}

Java

Before trying this sample, follow the Java setup instructions in Setting Up a Java Development Environment . For more information, see the Datastore mode Java API reference documentation .

// Imports the Google Cloud client library
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.Entity;
import com.google.cloud.datastore.Key;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

    // The kind for the new entity
    String kind = "Task";
    // The name/ID for the new entity
    String name = "sampletask1";
    // The Cloud Datastore key for the new entity
    Key taskKey = datastore.newKeyFactory().setKind(kind).newKey(name);

    // Prepares the new entity
    Entity task = Entity.newBuilder(taskKey)
        .set("description", "Buy milk")
        .build();

    // Saves the entity
    datastore.put(task);

    System.out.printf("Saved %s: %s%n", task.getKey().getName(), task.getString("description"));

    //Retrieve entity
    Entity retrieved = datastore.get(taskKey);

    System.out.printf("Retrieved %s: %s%n", taskKey.getName(), retrieved.getString("description"));

  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in Setting Up a Node.js Development Environment . For more information, see the Datastore mode Node.js API reference documentation .

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

async function quickStart() {
  // Your Google Cloud Platform project ID
  const projectId = 'YOUR_PROJECT_ID';

  // Creates a client
  const datastore = new Datastore({
    projectId: projectId,
  });

  // The kind for the new entity
  const kind = 'Task';
  // The name/ID for the new entity
  const name = 'sampletask1';
  // The Cloud Datastore key for the new entity
  const taskKey = datastore.key([kind, name]);

  // Prepares the new entity
  const task = {
    key: taskKey,
    data: {
      description: 'Buy milk',
    },
  };

  // Saves the entity
  await datastore.save(task);
  console.log(`Saved ${task.key.name}: ${task.data.description}`);
}
quickStart().catch(console.error);

PHP

To use this sample, prepare your machine for PHP development, and complete the Datastore mode quickstart. For more information, see the Datastore mode PHP API reference documentation .

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

# Imports the Google Cloud client library
use Google\Cloud\Datastore\DatastoreClient;

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

# Instantiates a client
$datastore = new DatastoreClient([
    'projectId' => $projectId
]);

# The kind for the new entity
$kind = 'Task';

# The name/ID for the new entity
$name = 'sampletask1';

# The Cloud Datastore key for the new entity
$taskKey = $datastore->key($kind, $name);

# Prepares the new entity
$task = $datastore->entity($taskKey, ['description' => 'Buy milk']);

# Saves the entity
$datastore->upsert($task);

echo 'Saved ' . $task->key() . ': ' . $task['description'] . PHP_EOL;

Python

Before trying this sample, follow the Python setup instructions in Setting Up a Python Development Environment . For more information, see the Datastore mode Python API reference documentation .

# Imports the Google Cloud client library
from google.cloud import datastore

# Instantiates a client
datastore_client = datastore.Client()

# The kind for the new entity
kind = 'Task'
# The name/ID for the new entity
name = 'sampletask1'
# The Cloud Datastore key for the new entity
task_key = datastore_client.key(kind, name)

# Prepares the new entity
task = datastore.Entity(key=task_key)
task['description'] = 'Buy milk'

# Saves the entity
datastore_client.put(task)

print('Saved {}: {}'.format(task.key.name, task['description']))

Ruby

Before trying this sample, follow the Ruby setup instructions in Setting Up a Ruby Development Environment . For more information, see the Datastore mode Ruby API reference documentation .

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

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

# Instantiates a client
datastore = Google::Cloud::Datastore.new project: project_id

# The kind for the new entity
kind = "Task"
# The name/ID for the new entity
name = "sampletask1"
# The Cloud Datastore key for the new entity
task_key = datastore.key kind, name

# Prepares the new entity
task = datastore.entity task_key do |t|
  t["description"] = "Buy milk"
end

# Saves the entity
datastore.save task

puts "Saved #{task.key.name}: #{task['description']}"

Additional Resources

Dependency on App Engine application

If you are using a Google Cloud library to access Datastore mode, your Cloud project requires an active App Engine application. Open the App Engine dashboard and confirm your Cloud project has an active App Engine app. Create an App Engine app if needed. The app must not be disabled.

Google App Engine Standard Environment Client Libraries

Integrate Datastore mode with your App Engine Standard Environment applications by using the App Engine client libraries.

Language Library
Go Google App Engine SDK for Go
Java Google App Engine SDK for Java
Python 2 Google Datastore NDB Client Library
Python 3 Google Cloud Datastore client library.

Third party Datastore API client libraries

In addition to the Google-supported client libraries listed in the tables above, a set of third-party libraries are available.

Language Library
Java Objectify
Java Catatumbo
PHP Datastore Library for PHP
Node.js js-data-cloud-datastore

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…

Cloud Datastore Documentation