Reputation: 138
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]>
Upvotes: 0
Views: 761
Reputation: 541
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)
Upvotes: 1