LoginSignup
2
2

More than 3 years have passed since last update.

【Watson Machine Learning メモ】新認証方式 apikeyによるwebサービス呼出し

Last updated at Posted at 2019-08-01

はじめに

Watson Machine LearningにデプロイしたWebサービスを呼び出す際に、1段階目としてtokenを取得します。従来はWatson Machine LearningのCredentcial情報のうち、userid/passwordのセットを使って、Basic認証を使って取得していたのですが、この方法が使えなくなった模様。
新しいWatson ML API呼出し方法のメモ(Pythonケース)を記載します。

参考リンク
https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/ml-authentication.html

サンプルコード

新しい方式でのtoken取得のサンプルコードを以下に記載します。
payloadデータの渡し方以降は従来通りなので省略します。

import urllib3, requests, json

# 新しい方式は認証にapikeyを利用し、userid/passwordは不要となります。
wml_credentials = {
  "instance_id": "xxxx",
  "apikey": "xxxx",
  "url": "https://us-south.ml.cloud.ibm.com"
}

# トークン取得
apikey = wml_credentials["apikey"]

# Get an IAM token from IBM Cloud
url     = "https://iam.bluemix.net/oidc/token"
headers = { "Content-Type" : "application/x-www-form-urlencoded" }
data    = "apikey=" + apikey + "&grant_type=urn:ibm:params:oauth:grant-type:apikey"
IBM_cloud_IAM_uid = "bx"
IBM_cloud_IAM_pwd = "bx"
response  = requests.post( url, headers=headers, data=data, 
        auth=( IBM_cloud_IAM_uid, IBM_cloud_IAM_pwd ) )
iam_token = response.json()["access_token"]
print('iam_token = ', iam_token)

# API呼出し用ヘッダ
# API呼出し用のヘッダには新しく`ML-Instance-ID`を追加する必要があります。
ml_instance_id = wml_credentials["instance_id"]
header = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + iam_token, 
      'ML-Instance-ID': ml_instance_id}

# これ以降の呼出し方法は従来通りなので、省略します。
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2