Rohit Prabu
Rohit Prabu

Reputation: 284

Could not establish an API connection in Google Cloud Platform

For retrieving monitoring metrics from my project, I used below Python code:

from google.cloud import monitoring_v3
from google.oauth2 import service_account
from googleapiclient import discovery

credentials = service_account.Credentials.from_service_account_file(
   r'D:\GCP\credentials\blahblah-04e8fd0245b8.json')

service = discovery.build('compute', 'v1', credentials=credentials)

client = monitoring_v3.MetricServiceClient()

project_name = f"projects/{blahblah-300807}"

resource_descriptors = client.list_monitored_resource_descriptors(
    name=project_name)

for descriptor in resource_descriptors:
    print(descriptor.type)

I did everything well. I gave the file path for credentials information correctly, but I received this error message:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: \
Could not automatically determine credentials. \
Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create \
credentials and re-run the application. \
For more information, please see \
https://cloud.google.com/docs/authentication/getting-started

I even checked that link and tried the alternative method, but still, it didn't work. How can I rectify this? Am I making a mistake?

Upvotes: 1

Views: 1389

Answers (1)

guillaume blaquiere
guillaume blaquiere

Reputation: 76073

You don't use the credential when you create the client

client = monitoring_v3.MetricServiceClient()

You can change it like this

client = monitoring_v3.MetricServiceClient(credentials=credentials)

Personally, I prefer to not explicitly provide the credential in the code, and I prefer to use the environment variable GOOGLE_APPLICATION_CREDENTIALS for this.

Create an environment variable in your OS with the name GOOGLE_APPLICATION_CREDENTIALS and the value that point to the service account key file D:\GCP\credentials\blahblah-04e8fd0245b8.json.

But, if it's on your own computer, you can even don't use service account key file (which is not really secure, I explain why in this article), you can use your own credential. For this, simply create an application default credential (ADC) like this gcloud auth application-default login

Upvotes: 2

Related Questions