使用 API 密钥访问 API

本页面介绍了如何使用 API 密钥访问 Google Cloud API 和接受 API 密钥的服务。

并非所有 Google Cloud API 都接受 API 密钥来授权使用。查看您要使用的服务或 API 的文档,以确定它是否接手 API 密钥。

如需了解如何创建和管理 API 密钥(包括限制 API 密钥),请参阅管理 API 密钥

如需了解如何将 API 密钥与 Google Maps Platform 搭配使用,请参阅 Google Maps Platform 文档。如需详细了解 API Keys API,请参阅 API Keys API 文档

将 API 密钥与 REST 搭配使用

您可以将 API 密钥作为查询参数传递给 REST API 调用,格式如下。将 API_KEY 替换为您的 API 密钥的密钥字符串。

例如,为针对 documents.analyzeEntities 发出的 Cloud Natural Language API 请求传递 API 密钥:

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

或者,您可以使用 x-goog-api-key 标头传入密钥。此标头必须与 gRPC 请求搭配使用。

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"

将 API 密钥与客户端库搭配使用

客户端库对 API 密钥的支持是特定于语言的。

此示例使用支持使用 API 密钥进行身份验证的 Cloud Natural Language API 来演示如何向库提供 API 密钥。

C#

如需运行此示例,您必须安装 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++

如需运行此示例,您必须安装 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

如需运行此示例,您必须安装 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
}

Java

如需运行此示例,您必须安装 Natural Language 客户端库

import com.google.cloud.language.v2.AnalyzeSentimentResponse;
import com.google.cloud.language.v2.Document;
import com.google.cloud.language.v2.LanguageServiceClient;
import com.google.cloud.language.v2.LanguageServiceSettings;
import java.io.IOException;

  static String authenticateUsingApiKey(String apiKey) throws IOException {
    LanguageServiceSettings settings =
        LanguageServiceSettings.newBuilder().setApiKey(apiKey).build();
    try (LanguageServiceClient client = LanguageServiceClient.create(settings)) {
      Document document =
          Document.newBuilder()
              .setContent("Hello World!")
              .setType(Document.Type.PLAIN_TEXT)
              .build();

      AnalyzeSentimentResponse actualResponse = client.analyzeSentiment(document);

      return actualResponse.getDocumentSentiment().toString();
    }
  }

Node.js

如需运行此示例,您必须安装 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 auth = new GoogleAuth({apiKey});
  // const {GoogleAuth} = require('google-auth-library');
  // 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();

PHP

如需运行此示例,您必须安装 Natural Language 客户端库

namespace Google\Cloud\Samples\Auth;

use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Vision\V1\Client\ProductSearchClient;
use Google\Cloud\Vision\V1\ListProductsRequest;
use Google\Cloud\Vision\V1\Product;

/**
 * Authenticate to a cloud API using an API key explicitly.
 * Note: This only works for APIs with support for API keys.
 *
 * @param string $projectId     The Google Cloud project ID.
 * @param string $location      The location name.
 * @param string $apiKey        The API key.
 */
function auth_cloud_apikey(string $projectId, string $location, string $apiKey): void
{
    $formattedParent = ProductSearchClient::locationName($projectId, $location);

    // Create a client.
    $productSearchClient = new ProductSearchClient([
        'apiKey' => $apiKey,
    ]);

    // Prepare the request message.
    $request = (new ListProductsRequest())
        ->setParent($formattedParent);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $productSearchClient->listProducts($request);

        /** @var Product $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

Python

如需运行此示例,您必须安装 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")

当您在应用中使用 API 密钥时,请确保其在存储和传输期间均安全无虞。公开泄露 API 密钥可能会导致您的账号产生意外费用。如需了解详情,请参阅管理 API 密钥的最佳实践

后续步骤