Usar chaves de API para acessar APIs

Esta página descreve como usar chaves de API para acessar APIs e serviços do Google Cloud que aceitam chaves de API.

Nem todas as Google Cloud APIs aceitam chaves de API para autorizar o uso. Confira a documentação do serviço ou da API que você quer usar para determinar se é compatível com chaves de API.

Para saber como criar e gerenciar chaves de API, incluindo a restrição delas, consulte Gerenciar chaves de API.

Para saber como usar chaves de API com a Plataforma Google Maps, consulte a documentação da Plataforma Google Maps. Para mais informações sobre a API de chaves de API, consulte a documentação da API 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 .NET desta página em um ambiente de desenvolvimento local, instale e inicialize o gcloud CLI e e configure o Application Default Credentials com suas credenciais de usuário.

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local na documentação de autenticação do Google Cloud.

C++

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

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local na documentação de autenticação do Google Cloud.

Go

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

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local na documentação de autenticação do Google Cloud.

Node.js

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

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local na documentação de autenticação do Google Cloud.

Python

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

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local na documentação de autenticação do Google Cloud.

REST

Para usar as amostras da API REST nesta página em um ambiente de desenvolvimento local, use as credenciais fornecidas para gcloud CLI.

    Install the Google Cloud CLI, then initialize it by running the following command:

    gcloud init

Para mais informações, consulte Autenticar para usar REST na documentação de autenticação do Google Cloud.

Usar uma chave de API com REST

Para incluir uma chave de API com uma chamada da API REST, use o cabeçalho HTML x-goog-api-key, conforme mostrado no exemplo a seguir:

curl -X POST \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"

Se não for possível usar o cabeçalho HTML, use o parâmetro de consulta key. No entanto, esse método inclui a chave de API no URL, expondo-a a roubos por meio de verificações de URL.

O exemplo a seguir mostra como usar o parâmetro de consulta key com uma solicitação da API Cloud Natural Language para documents.analyzeEntities. Substitua API_KEY pela string da chave de API.

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

Usar uma chave de API com bibliotecas de cliente

Este exemplo usa a API Cloud Natural Language, que aceita chaves de API, para demonstrar como fornecer uma chave de API à biblioteca.

C#

Para executar este exemplo, instale a biblioteca de cliente da Natural Language.


using Google.Cloud.Language.V1;
using System;

public class UseApiKeySample
{
    public void AnalyzeSentiment(string apiKey)
    {
        LanguageServiceClient client = new LanguageServiceClientBuilder
        {
            ApiKey = apiKey
        }.Build();

        string text = "Hello, world!";

        AnalyzeSentimentResponse response = client.AnalyzeSentiment(Document.FromPlainText(text));
        Console.WriteLine($"Text: {text}");
        Sentiment sentiment = response.DocumentSentiment;
        Console.WriteLine($"Sentiment: {sentiment.Score}, {sentiment.Magnitude}");
        Console.WriteLine("Successfully authenticated using the API key");
    }
}

C++

Para executar este exemplo, instale a biblioteca de cliente da Natural Language.

#include "google/cloud/language/v1/language_client.h"
#include "google/cloud/credentials.h"
#include "google/cloud/options.h"

void AuthenticateWithApiKey(std::vector<std::string> const& argv) {
  if (argv.size() != 2) {
    throw google::cloud::testing_util::Usage{
        "authenticate-with-api-key <project-id> <api-key>"};
  }
  namespace gc = ::google::cloud;
  auto options = gc::Options{}.set<gc::UnifiedCredentialsOption>(
      gc::MakeApiKeyCredentials(argv[1]));
  auto client = gc::language_v1::LanguageServiceClient(
      gc::language_v1::MakeLanguageServiceConnection(options));

  auto constexpr kText = "Hello, world!";

  google::cloud::language::v1::Document d;
  d.set_content(kText);
  d.set_type(google::cloud::language::v1::Document::PLAIN_TEXT);

  auto response = client.AnalyzeSentiment(d, {});
  if (!response) throw std::move(response.status());
  auto const& sentiment = response->document_sentiment();
  std::cout << "Text: " << kText << "\n";
  std::cout << "Sentiment: " << sentiment.score() << ", "
            << sentiment.magnitude() << "\n";
  std::cout << "Successfully authenticated using the API key\n";
}

Go

Para executar este exemplo, instale a biblioteca de cliente da Natural Language.

import (
	"context"
	"fmt"
	"io"

	language "cloud.google.com/go/language/apiv1"
	"cloud.google.com/go/language/apiv1/languagepb"
	"google.golang.org/api/option"
)

// authenticateWithAPIKey authenticates with an API key for Google Language
// service.
func authenticateWithAPIKey(w io.Writer, apiKey string) error {
	// apiKey := "api-key-string"

	ctx := context.Background()

	// Initialize the Language Service client and set the API key.
	client, err := language.NewClient(ctx, option.WithAPIKey(apiKey))
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	text := "Hello, world!"
	// Make a request to analyze the sentiment of the text.
	res, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
	if err != nil {
		return fmt.Errorf("AnalyzeSentiment: %w", err)
	}

	fmt.Fprintf(w, "Text: %s\n", text)
	fmt.Fprintf(w, "Sentiment score: %v\n", res.DocumentSentiment.Score)
	fmt.Fprintln(w, "Successfully authenticated using the API key.")

	return nil
}

Node.js

Para executar este exemplo, instale a biblioteca de cliente da Natural Language.


const {
  v1: {LanguageServiceClient},
} = require('@google-cloud/language');

/**
 * Authenticates with an API key for Google Language service.
 *
 * @param {string} apiKey An API Key to use
 */
async function authenticateWithAPIKey(apiKey) {
  const language = new LanguageServiceClient({apiKey});

  // Alternatively:
  // const {GoogleAuth} = require('google-auth-library');
  // const auth = new GoogleAuth({apiKey});
  // const language = new LanguageServiceClient({auth});

  const text = 'Hello, world!';

  const [response] = await language.analyzeSentiment({
    document: {
      content: text,
      type: 'PLAIN_TEXT',
    },
  });

  console.log(`Text: ${text}`);
  console.log(
    `Sentiment: ${response.documentSentiment.score}, ${response.documentSentiment.magnitude}`
  );
  console.log('Successfully authenticated using the API key');
}

authenticateWithAPIKey();

Python

Para executar este exemplo, instale a biblioteca de cliente da Natural Language.


from google.cloud import language_v1


def authenticate_with_api_key(api_key_string: str) -> None:
    """
    Authenticates with an API key for Google Language service.

    TODO(Developer): Replace this variable before running the sample.

    Args:
        api_key_string: The API key to authenticate to the service.
    """

    # Initialize the Language Service client and set the API key
    client = language_v1.LanguageServiceClient(
        client_options={"api_key": api_key_string}
    )

    text = "Hello, world!"
    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )

    # Make a request to analyze the sentiment of the text.
    sentiment = client.analyze_sentiment(
        request={"document": document}
    ).document_sentiment

    print(f"Text: {text}")
    print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
    print("Successfully authenticated using the API key")

Ao usar chaves de API nos seus aplicativos, garanta que elas sejam mantidas em segurança durante o armazenamento e a transmissão. A exposição pública das chaves de API pode levar a cobranças inesperadas na sua conta. Para mais informações, consulte Práticas recomendadas para gerenciar chaves de API.

A seguir