Search code examples
google-oauthgoogle-python-api

How do I make authenticated Rest call to google machine learning predict endpoint?


I want to make a simple http rest call to a google machine learning predict endpoint, but I can't find any information on how to do that. As far as I can tell from the limited documentation, you have to use either the Java or Python library (or figure out how to properly encrypt everything when using the REST auth endpoints) and get a credentials object. Then the instructions end and I have no idea how to actually use my credentials object. This is my code so far:

import urllib2
from google.oauth2 import service_account

# Constants
ENDPOINT_URL = 'ml.googleapis.com/v1/projects/{project}/models/{model}:predict?access_token='
SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
SERVICE_ACCOUNT_FILE = 'service.json'

credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
access_token=credentials.token

opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request(ENDPOINT_URL + access_token)
request.get_method = lambda: 'POST'
result = opener.open(request).read()
print(str(result))

If I print credentials.valid it returns False, so I think there is an issue with the credentials object init but I don't know what since no errors are reported, the fields are all correct inside the credentials object, and I did everything according to the instructions. Also my service.json is the same one our mobile team is successfully using to get an access token so I know the json file has the correct data.

How do I get an access token for the machine learning service that I can use to call the predict endpoint?


Solution

  • It turns out the best way to do a simple query is to use the gcloud console. I ended up following the instructions here to setup my environment: https://cloud.google.com/sdk/docs/quickstart-debian-ubuntu

    Then the instructions here to actually hit the endpoint (with some help from the person that originally setup the model): https://cloud.google.com/sdk/gcloud/reference/ml-engine/predict

    It was way easier than trying to use the python library and I highly recommend it to anyone trying to just hit the predict endpoint.