使用 API 密钥验证对 Google ML 引擎的 API 调用

问题描述

我在 Google AI Platform 中有一个已保存的模型,当我在 AI Platform UI 中测试预测时,该模型可以工作。

但是,当我尝试通过 REST 访问 API 时,我不断收到状态为 401 的响应。我想知道如何成功做到这一点。

我的 api URL 如下所示:

'https://ml.googleapis.com/v1/projects/ml-project-name/models/my-model-names/versions/v2:predict

我希望能够在驻留在任何平台上的外部应用程序中访问此端点以使用它生成预测。

Google Cloud 建议使用服务帐号授权,但是,它的所有说明都需要设置环境变量,以便应用可以自动对您进行身份验证。我更愿意在请求中直接提供它们,以使事情更便携,并与工作中其他地方的工作方式保持一致。

所以我尝试获取 API 密钥。

根据此页面https://cloud.google.com/docs/authentication/api-keys 您可以通过以下方式验证请求:

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

但是,当我运行以下代码时,我的请求状态为 401

import requests

api_key = my_sample_api_key
url     = f'https://ml.googleapis.com/v1/projects/project-name/models/model-name/versions/v2:predict?key={api_key}'

json    = {"instances": [ {"input_1": ["Please predict this text"]}]}

res = request.post(url,json=json)

任何帮助将不胜感激,谢谢。

解决方法

Auto ML 不支持在发送请求时使用 API 密钥。我建议在您的请求中使用身份验证令牌或使用可用的客户端库来发送预测。

以下是使用其 python client library 发送预测请求的代码片段:

# Create the AI Platform service object.
# To authenticate set the environment variable
# GOOGLE_APPLICATION_CREDENTIALS=<path_to_service_account_file>
service = googleapiclient.discovery.build('ml','v1')

def predict_json(project,model,instances,version=None):
    """Send json data to a deployed model for prediction.

    Args:
        project (str): project where the AI Platform Model is deployed.
        model (str): model name.
        instances ([Mapping[str: Any]]): Keys should be the names of Tensors
            your deployed model expects as inputs. Values should be datatypes
            convertible to Tensors,or (potentially nested) lists of datatypes
            convertible to tensors.
        version: str,version of the model to target.
    Returns:
        Mapping[str: any]: dictionary of prediction results defined by the
            model.
    """
    name = 'projects/{}/models/{}'.format(project,model)

    if version is not None:
        name += '/versions/{}'.format(version)

    response = service.projects().predict(
        name=name,body={'instances': instances}
    ).execute()

    if 'error' in response:
        raise RuntimeError(response['error'])

    return response['predictions']

以下是使用带有身份验证令牌的 curl 发送 POST request 的示例:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://ml.googleapis.com/v1/projects/your-project/models/you-model-name/versions/your-version-name:predict