使用python请求时未经授权的HTTP请求

时间:2020-01-13 11:05:48

标签: python rest api http-status-code-401

当我尝试使用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]>

1 个答案:

答案 0 :(得分:1)

对于curl,-u将添加一个基本的auth标头。

因此,您希望构建如下请求:

import requests
from requests.auth import HTTPBasicAuth

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"
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, auth=HTTPBasicAuth('apikey', WATSONAPIKEY))
data = r.json()
print (r)