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

Authenticating API Call to Google ML Engine with an API Key

我在 Google AI Platform 中保存了一个模型,当我在 AI Platform UI 中测试预测时可以使用该模型 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