如何使用 Google 云客户端库进行基于 API 键的 REST 调用

How to make an API-key based REST call with Google Cloud client library

我正在尝试使用来自 Golang 的 API 密钥对 Google Cloud Vision API 进行 API 调用。但是我收到 400: bad request, invalid_grant error

下面的 apiKey/apiKeyOption 部分代码是我的。

拨打这个电话的正确方式是什么?有可能吗?

import (
    // ...
    "google.golang.org/api/option"
    vision "cloud.google.com/go/vision/apiv1"
    "golang.org/x/net/context"
)

func getImageLabels(filename string) []string {

    ctx := context.Background()

    apiKey := "..." // I have a valid api key generated in the console.
    apiKeyOption := option.WithAPIKey(apiKey)

    client, err := vision.NewImageAnnotatorClient(ctx, apiKeyOption)

    // ...
    labels, err := client.DetectLabels(ctx, image, nil, 10)

}

...

Failed to detect labels: rpc error: code = Internal desc = transport: oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error" : "invalid_grant"
}

根据我在 Google Golang 云客户端库的官方文档(均在 GitHub and Golang documentation 中)中找到的内容,当前支持的身份验证方法是 Google 应用程序默认凭据 服务帐户,因此没有使用API 密钥进行身份验证的选项。

但是,正如 in the documentation 所指出的,出于安全原因,Google 建议使用服务帐户而不是 API 密钥,因此我建议您尽可能使用该选项.

API keys can be used when calling Google APIs that don't require authentication, and when using Google Cloud Endpoints. For security reasons, we recommend using service accounts instead.

@dsesto 是对的,使用服务帐户进行身份验证总是更好。但是,如果您想使用 API 键,它应该可以工作。

我已经在该库上打开了一个 github issue 来解释错误。

使用 curl 的相同请求正常工作(无凭据):

curl https://vision.googleapis.com/v1/images:annotate?key=<API_KEY>  -H'content-type:application/json' -d'{
 "requests": [
  {
   "image": {
    "source": {
     "imageUri": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/1200px-Google_2015_logo.svg.png"
    }
   },
   "features": [
    {
     "type": "LABEL_DETECTION"
    }
   ]
  }
 ]
}'