Começar a usar a autenticação

O Application Default Credentials (ADC) permite que o aplicativo use as credenciais da conta de serviço para acessar os recursos do BigQuery como identidade própria.

O BigQuery não é compatível com o uso de chaves de API.

Antes de começar

Select the tab for how you plan to use the samples on this page:

C#

Para usar os exemplos do .NET desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

    Install the Google Cloud CLI.

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

               
    gcloud config set project PROJECT_ID

    Go

    Para usar os exemplos do Go desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

      Install the Google Cloud CLI.

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

                 
      gcloud config set project PROJECT_ID

      Java

      Para usar os exemplos do Java desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

        Install the Google Cloud CLI.

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

                   
        gcloud config set project PROJECT_ID

        Node.js

        Para usar os exemplos do Node.js desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

          Install the Google Cloud CLI.

          If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

                     
          gcloud config set project PROJECT_ID

          PHP

          Para usar os exemplos do PHP desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

            Install the Google Cloud CLI.

            If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

                       
            gcloud config set project PROJECT_ID

            Python

            Para usar os exemplos do Python desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

              Install the Google Cloud CLI.

              If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

                         
              gcloud config set project PROJECT_ID

              Ruby

              Para usar os exemplos do Ruby desta página em um ambiente de desenvolvimento local, instale e inicialize a gcloud CLI e configure o Application Default Credentials com suas credenciais de usuário.

                Install the Google Cloud CLI.

                If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

                           
                gcloud config set project PROJECT_ID

                Saiba como configurar a autenticação para um ambiente de produção em Set up Application Default Credentials for code running on Google Cloud.

                Application Default Credentials

                As bibliotecas de cliente podem usar o Application Default Credentials para se autenticar facilmente nas APIs do Google e enviar solicitações para elas. Com o Application Default Credentials, é possível testar seu aplicativo localmente e implantá-lo sem alterar o código. Para mais informações, consulte Autenticação para usar bibliotecas de cliente.

                Quando você cria um objeto de serviço com as bibliotecas de cliente do BigQuery e não transmite credenciais explícitas, o aplicativo faz a autenticação usando o Application Default Credentials. Os exemplos a seguir mostram como se autenticar no BigQuery usando o ADC.

                C#

                Antes de testar esta amostra, siga as instruções de configuração do C# no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em C#.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                
                using Google.Apis.Bigquery.v2.Data;
                using Google.Cloud.BigQuery.V2;
                
                public class BigQueryCreateDataset
                {
                    public BigQueryDataset CreateDataset(
                        string projectId = "your-project-id",
                        string location = "US"
                    )
                    {
                        BigQueryClient client = BigQueryClient.Create(projectId);
                        var dataset = new Dataset
                        {
                            // Specify the geographic location where the dataset should reside.
                            Location = location
                        };
                        // Create the dataset
                        return client.CreateDataset(
                            datasetId: "your_new_dataset_id", dataset);
                    }
                }

                Go

                Antes de testar esta amostra, siga as instruções de configuração do Go no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Go.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                
                // Sample bigquery-quickstart creates a Google BigQuery dataset.
                package main
                
                import (
                	"context"
                	"fmt"
                	"log"
                
                	"cloud.google.com/go/bigquery"
                )
                
                func main() {
                	ctx := context.Background()
                
                	// Sets your Google Cloud Platform project ID.
                	projectID := "YOUR_PROJECT_ID"
                
                	// Creates a client.
                	client, err := bigquery.NewClient(ctx, projectID)
                	if err != nil {
                		log.Fatalf("bigquery.NewClient: %v", err)
                	}
                	defer client.Close()
                
                	// Sets the name for the new dataset.
                	datasetName := "my_new_dataset"
                
                	// Creates the new BigQuery dataset.
                	if err := client.Dataset(datasetName).Create(ctx, &bigquery.DatasetMetadata{}); err != nil {
                		log.Fatalf("Failed to create dataset: %v", err)
                	}
                
                	fmt.Printf("Dataset created\n")
                }
                

                Java

                Antes de testar esta amostra, siga as instruções de configuração do Java no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Java.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                public static void implicit() {
                  // Instantiate a client. If you don't specify credentials when constructing a client, the
                  // client library will look for credentials in the environment, such as the
                  // GOOGLE_APPLICATION_CREDENTIALS environment variable.
                  BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
                
                  // Use the client.
                  System.out.println("Datasets:");
                  for (Dataset dataset : bigquery.listDatasets().iterateAll()) {
                    System.out.printf("%s%n", dataset.getDatasetId().getDataset());
                  }
                }

                Node.js

                Antes de testar esta amostra, siga as instruções de configuração do Node.js no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Node.js.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                // Import the Google Cloud client library using default credentials
                const {BigQuery} = require('@google-cloud/bigquery');
                const bigquery = new BigQuery();

                PHP

                Antes de testar esta amostra, siga as instruções de configuração do PHP no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em PHP.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                use Google\Cloud\BigQuery\BigQueryClient;
                
                /** Uncomment and populate these variables in your code */
                //$projectId = 'The Google project ID';
                
                $bigQuery = new BigQueryClient([
                    'projectId' => $projectId,
                ]);

                Python

                Antes de testar esta amostra, siga as instruções de configuração do Python no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Python.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                from google.cloud import bigquery
                
                # If you don't specify credentials when constructing the client, the
                # client library will look for credentials in the environment.
                client = bigquery.Client()

                Ruby

                Antes de testar esta amostra, siga as instruções de configuração do Ruby no Guia de início rápido do BigQuery: como usar bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API BigQuery em Ruby.

                Para autenticar no BigQuery, configure o Application Default Credentials. Para mais informações, consulte Antes de começar.

                require "google/cloud/bigquery"
                
                # This uses Application Default Credentials to authenticate.
                # @see https://cloud.google.com/bigquery/docs/authentication/getting-started
                bigquery = Google::Cloud::Bigquery.new
                
                sql     = "SELECT " \
                          "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_count " \
                          "FROM `bigquery-public-data.stackoverflow.posts_questions` " \
                          "WHERE tags like '%google-bigquery%' " \
                          "ORDER BY view_count DESC LIMIT 10"
                results = bigquery.query sql
                
                results.each do |row|
                  puts "#{row[:url]}: #{row[:view_count]} views"
                end

                A seguir