【问题标题】:Authenticating API Call to Google ML Engine with an API Key使用 API 密钥验证对 Google ML 引擎的 API 调用
【发布时间】:2021-04-15 22:53:35
【问题描述】:

我在 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)

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

【问题讨论】:

    标签: google-cloud-platform google-authentication google-ai-platform


    【解决方案1】:

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

    这是一个使用其python client library 发送预测请求的代码 sn-p:

    # 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
    

    【讨论】:

      猜你喜欢
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 2021-02-10
      • 2019-08-25
      相关资源
      最近更新 更多