When I try the REST API with curl, it is working like a charm. The code that works is given below:
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
}
}
}'
But I'm not getting authenticated when I'm doing same thing in my Python code. not sure how to use the "-u" in the python code.
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)
I get Unauthorized (401) response:
<Response [401]>
asked Jan 13, 2020 at 11:05
Jithin P Gopal
1382 silver badges11 bronze badges
-
In the first request (curl) the data is sent as Authorization header, while in your python post request it's sent as a simple param.Flo– Flo2020年01月13日 11:14:54 +00:00Commented Jan 13, 2020 at 11:14
1 Answer 1
For curl, -u is to add a basic auth header.
So you would like to build request like this:
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)
answered Jan 13, 2020 at 11:13
Alan haha
5511 gold badge4 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py