I'm trying to make an API call to Google Cloud Vision API using an API key from Golang. But I'm getting a 400: bad request, invalid_grant error
.
The apiKey/apiKeyOption part of the code below is mine.
What is the right way to make this call? Is it possible at all?
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"
}
According to what I found in the official documentation (both in GitHub and Golang documentation) of the Google Cloud client libraries for Golang, the current supported authentication methods are Google Application Default Credentials and Service Accounts, so there is no such option to authenticate using an API key.
However, as pointed out in the documentation, Google recommends using Service Accounts instead of API keys for security reasons, so I would suggest that you go with that option if you can.
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.