ibm-cloudsentiment-analysiswatson-nlu

Sample example of Sentiment feature of Watson NLU failing with error code 400


I was trying the sample examples of various features documented at https://cloud.ibm.com/apidocs/natural-language-understanding. All the features examples are working properly except the Sentiment feature while trying with Curl.

curl -X POST \
-H "Content-Type: application/json" \
-u "apikey:{apikey}" \
-d @parameters.json \
"{url}/v1/analyze?version=2018-11-16"

parameters.json
{
  "url": "www.wsj.com/news/markets",
  "features": {
    "sentiment": {
      "targets": [
        "stocks"
      ]
    }
  }
}



Sentiment feature response:
{
  "language": "en",
  "error": "target(s) not found",
  "code": 400
}

Solution

  • Here's how it worked for me. Explaining in an elaborate way to help others.

    First of all, you have to create a file named parameters.json and paste the below code

    {
      "url": "www.wsj.com/news/markets",
      "features": {
        "sentiment": {
          "targets": [
            "stocks"
          ]
        }
      }
    }
    

    Pointing to the folder in which this JSON file is on a terminal or command prompt and replacing the {apikey} and {URL} with the NLU service values, run the below command

    curl -X POST \                                                                                                                            
    -H "Content-Type: application/json" \
    -u "apikey:{APIKEY}" \
    -d @parameters.json \
    "{URL}/v1/analyze?version=2018-11-16"
    

    The {URL} in my case is https://gateway.watsonplatform.net/natural-language-understanding/api

    Then should see the below output

    {
      "usage": {
        "text_units": 1,
        "text_characters": 1421,
        "features": 1
      },
      "sentiment": {
        "targets": [
          {
            "text": "stocks",
            "score": -0.640222,
            "mixed": "1",
            "label": "negative"
          }
        ],
        "document": {
          "score": -0.662399,
          "label": "negative"
        }
      },
      "retrieved_url": "https://www.wsj.com/news/markets",
      "language": "en"
    }