How to authenticate GCP AI Platform Predictions using HTTP requests

Viewed 478

I have deployed a model to AI Platform Predictions successfully by following this tutorial. Now, I want to make predictions with this model via HTTP requests.

As suggested by @Ismail, I followed Method: projects.predict documentation.

I'm sending a POST request to https://ml.googleapis.com/v1/projects/${PROJECT_ID}/models/${MODEL_NAME}:predict with the following body:

{
  "instances": [
    [51.0, 17.0, 6.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]
  ]
}

The numbers are the model's input.

I receive the following response:

{
    "error": {
        "code": 401,
        "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

I sent the POST request using the RestMan chrome extension. I would like to be able to get a prediction with RestMan.

My question is: how can I authenticate my HTTP POST request? Should I send some information in the request's header?

2 Answers

When you access to Google API, you need to add an access token in your header. With the CLI you can generate it like this:

gcloud auth print-access-token

Of course, the current credential needs to be authorized on the AI platform prediction service.

If you perform a curl, you can do this on linux (and cloud shell)

curl -X POST -d @bodyfile.json -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  https://ml.googleapis.com/v1/projects/${PROJECT_ID}/models/${MODEL_NAME}:predic

If you use RestMan, I'm not sure it is capable to generate an access token for you. The solution is to make your model public. It's not recommended, but for a limited period of time, and for test only, why not!

For this, grant allUsers with the role roles/ml.modelUser on your model.


EDIT 1

I didn't find how to do this on a model with the console. I did t before but there were some updates... Very strange. I achieve this with the gcloud CLI

gcloud ai-platform models add-iam-policy-binding --region=us-central1 --member=allUsers --role=roles/ml.modelUser test
Related