0

I am trying to reach my automL model prediction endpoint that I have setup, I have created a service account and added the correct role to it, now I am trying to call the endpoint in Python, but I am not sure how to call it: Here is what I have tried. The key file is downloaded from google so it's good.

from google.oauth2 import service_account
project_id = 'aaa'
endpoint_id = 'bbb'
with open('./ServiceAccountKey.json') as source:
    info = json.load(source)
credentials = service_account.Credentials.from_service_account_info(info)
scoped_credentials = credentials.with_scopes(
    ['https://www.googleapis.com/auth/cloud-platform'])
access_token = scoped_credentials.get_access_token()
endpoint = f"https://us-central1-aiplatform.googleapis.com/v1alpha1/projects/{project_id}/locations/us-central1/endpoints/{endpoint_id}:predict"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer " + access_token}
payload = {}
x = requests.post(endpoint, data = payload, header=headers)
print(x)

The error I get is this:

AttributeError: 'Credentials' object has no attribute 'get_access_token'

Permissions I have given the service account:

enter image description here

Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174
  • 4
    1) `access_token = scoped_credentials.token`. 2) You might need to call `scoped_credentials.refresh()` first. 2) Tip: Use `from_service_account_file()` instead of `from_service_account_info()`. 3) You can add the scopes in a single call instead of multiple calls. `credentials = service_account.Credentials.from_service_account_file('ServiceAccountKey.json', scopes=['https://www.googleapis.com/auth/cloud-platform'])` – John Hanley Apr 19 '21 at 17:05

1 Answers1

1

The best way is to use the AI Platform Python client library. Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path to your service account file and you are good to go.

Better to not deal with access token and refresh tokens yourself if there is a ready-made library available.

dishant makwana
  • 1,029
  • 6
  • 13
  • 1
    There may be some cases where setting GOOGLE_APPLICATION_CREDENTIALS isn't possible. I provided [the alternative solution](https://stackoverflow.com/questions/53472429/how-to-get-a-gcp-bearer-token-programmatically-with-python/67069710#67069710) in Python3. – Hil Liao May 18 '22 at 00:33