0

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]>
1
  • 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. Commented Jan 13, 2020 at 11:14

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.