【发布时间】:2020-01-13 19:13:09
【问题描述】:
当我尝试使用 curl 的 REST API 时,它就像一个魅力。有效的代码如下:
curl -X POST -u "apikey:####My Key####" \
"https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/4b490a19-9cd0-4e9b-9f71-c7ce59f9d7df/v1/analyze?version=2019-07-12" \
--request POST \
--header "Content-Type: application/json" \
--data '{
"text": "I love apples! I do not like oranges.",
"features": {
"sentiment": {
"targets": [
"apples",
"oranges",
"broccoli"
]
},
"keywords": {
"emotion": true
}
}
}'
但是当我在我的 Python 代码中做同样的事情时,我没有获得身份验证。不知道如何在 python 代码中使用“-u”。
import requests
WATSON_NLP_URL = "https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/4b490a19-9cd0-4e9b-9f71-c7ce59f9d7df/v1/analyze?version=2019-07-12"
WATSONAPIKEY = "XXXX"
params = {"apikey":WATSONAPIKEY}
json_to_nlp = {
"text": "I love apples! I do not like oranges.",
"features": {
"sentiment": {
"targets": [
"apples",
"oranges",
"broccoli"
]
},
"keywords": {
"emotion": "true"
}
}
}
r = requests.post(url=WATSON_NLP_URL, json=json_to_nlp, params=params)
data = r.json()
print (r)
我收到未经授权的 (401) 响应:
<Response [401]>
【问题讨论】:
-
在第一个请求 (curl) 中,数据作为 Authorization 标头发送,而在您的 python 发布请求中,它作为简单参数发送。
标签: python rest api http-status-code-401