Introduction

Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you request. The service cleans HTML content before analysis by default, so the results can ignore most advertisements and other unwanted content.

You can create custom models with Watson Knowledge Studio to detect custom entities, relations, and categories in Natural Language Understanding.

Java SDK version 7.0.0 only requires additional configuration to set the target. For details, see https://github.com/watson-developer-cloud/java-sdk#installation.

Beginning with version 4.0.0, the Node SDK returns a Promise for all methods when a callback is not specified.

The package location moved to ibm-watson. It remains available at watson-developer-cloud but is not updated there. Use ibm-watson to stay up to date.

The code examples on this tab use the client library that is provided for Java.

Maven

<dependency>
  <groupId>com.ibm.watson</groupId>
  <artifactId>ibm-watson</artifactId>
  <version>7.0.0</version>
</dependency>

Gradle

compile 'com.ibm.watson:ibm-watson:7.0.0'

GitHub

The code examples on this tab use the client library that is provided for Node.js.

Installation

npm install ibm-watson

GitHub

The code examples on this tab use the client library that is provided for Python.

Installation

pip install --upgrade "ibm-watson>=3.0.3"

GitHub

The code examples on this tab use the client library that is provided for Ruby.

Installation

gem install ibm_watson

GitHub

The code examples on this tab use the client library that is provided for Go.

go get -u github.com/watson-developer-cloud/go-sdk/...

GitHub

The code examples on this tab use the client library that is provided for Swift.

Cocoapods

pod 'IBMWatsonNaturalLanguageUnderstandingV1', '~> 2.0.2'

Carthage

github "watson-developer-cloud/swift-sdk" ~> 2.0.2

Swift Package Manager

.package(url: "https://github.com/watson-developer-cloud/swift-sdk", from: "2.0.2")

GitHub

Text analytics features

Natural Language Understanding includes a set of text analytics features that you can use to extract meaning from unstructured data.

These examples can help you get started. For the request options and response body for all features, see the Analyze text method.

Categories

Returns a five-level taxonomy of the content. The top three categories are returned.

Categories request options

For details, see the request body for the Analyze text method.

  • Set this to true to return explanations for each categorization. This is available only for English categories.

    Default: false

  • Maximum number of categories to return

    Default: 3

  • Enter a custom model ID to override the standard categories model.

Categories response

Example Categories feature request

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

Example parameters

{
  "url": "www.ibm.com",
  "features": {
    "categories": {
      "limit": 3
    }
  }
}

Example Categories feature request

package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
   panic(naturalLanguageUnderstandingErr)
  }

  url := "www.ibm.com"
  limit := int64(3)

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      URL: &url,
      Features: &naturallanguageunderstandingv1.Features{
        Categories: &naturallanguageunderstandingv1.CategoriesOptions{
          Limit: &limit,
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Categories feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String url = "www.ibm.com";

CategoriesOptions categories= new CategoriesOptions.Builder()
  .limit(3)
  .build();

Features features = new Features.Builder()
  .categories(categories)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .url(url)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Categories feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'url': 'www.ibm.com',
  'features': {
    'categories': {
      'limit': 3
    }
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Categories feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, CategoriesOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    url='www.ibm.com',
    features=Features(categories=CategoriesOptions(limit=3))).get_result()

print(json.dumps(response, indent=2))

Example Categories feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  url: "www.ibm.com",
  features: {categories: {limit:3}}
)

puts JSON.pretty_generate(response.result)

Example Categories feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let categories = CategoriesOptions(limit: 3)
let features = Features(categories: categories)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the CategoriesResult[] object in the Analyze text method.

Example Categories feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 1536,
    "features": 1
  },
  "retrieved_url": "https://www.ibm.com/us-en/",
  "categories": [
    {
      "score": 0.594296,
      "label": "/technology and computing/software"
    },
    {
      "score": 0.448495,
      "label": "/science/mathematics/statistics"
    },
    {
      "score": 0.426429,
      "label": "/business and industrial"
    }
  ],
  "language": "en"
}

Concepts

Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned.

Concepts request options

For details, see the request body for the Analyze text method.

  • Maximum number of concepts to return

    Default: 50

Concepts response

Example Concepts feature request

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

Example parameters

{
  "url": "www.ibm.com",
  "features": {
    "concepts": {
      "limit": 3
    }
  }
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
   panic(naturalLanguageUnderstandingErr)
  }

  url := "www.ibm.com"
  limit := int64(3)

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      URL: &url,
      Features: &naturallanguageunderstandingv1.Features{
        Concepts: &naturallanguageunderstandingv1.ConceptsOptions{
          Limit: &limit,
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Concepts feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");


String url = "www.ibm.com";

ConceptsOptions concepts= new ConceptsOptions.Builder()
  .limit(3)
  .build();

Features features = new Features.Builder()
  .concepts(concepts)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .url(url)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Concepts feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'url': 'www.ibm.com',
  'features': {
    'concepts': {
      'limit': 3
    }
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Concepts feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, ConceptsOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    url='www.ibm.com',
    features=Features(concepts=ConceptsOptions(limit=3))).get_result()

print(json.dumps(response, indent=2))

Example Concepts feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  url: "www.ibm.com",
  features: {concepts: {limit:3}}
)

puts JSON.pretty_generate(response.result)

Example Concepts feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let concepts = ConceptsOptions(limit: 3)
let features = Features(concepts: concepts)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the ConceptsResult[] object in the Analyze text method.

Example Categories feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 1536,
    "features": 1
  },
  "retrieved_url": "http://www.ibm.com/us-en/",
  "concepts": [
    {
      "text": "Social network service",
      "relevance": 0.92186,
      "dbpedia_resource": "http://dbpedia.org/resource/Social_network_service"
    },
    {
      "text": "Thomas J. Watson",
      "relevance": 0.871908,
      "dbpedia_resource": "http://dbpedia.org/resource/Thomas_J._Watson"
    },
    {
      "text": "Lotus Software",
      "relevance": 0.839578,
      "dbpedia_resource": "http://dbpedia.org/resource/Lotus_Software"
    }
  ],
  "language": "en"
}

Emotion

Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with entities.emotion and for keywords with keywords.emotion.

Emotion request options

For details, see the request body for the Analyze text method.

  • Whether to hide document-level emotion results.

    Default: true

  • Target strings, separated by commas. Emotion results are returned for each target string found in the document.

Emotion response

Example Emotion feature request

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

Example parameters

{
  "html": "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>",
  "features": {
    "emotion": {
      "targets": [
        "apples",
        "oranges"
      ]
    }
  }
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
   panic(naturalLanguageUnderstandingErr)
  }

  html := "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>"
  targets := []string{"apples", "oranges"}

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      HTML: &html,
      Features: &naturallanguageunderstandingv1.Features{
        Emotion: &naturallanguageunderstandingv1.EmotionOptions{
          Targets: targets,
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Emotion feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String html = "<html><head><title>Fruits</title></head>" +
  "<body><h1>Apples and Oranges</h1>" +
  "<p>I love apples! I don't like oranges.</p>" +
  "</body></html>";

List<String> targets = new ArrayList<>();
targets.add("apples");
targets.add("oranges");

EmotionOptions emotion= new EmotionOptions.Builder()
  .targets(targets)
  .build();

Features features = new Features.Builder()
  .emotion(emotion)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .html(html)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Emotion feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'html': '<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don\'t like oranges.</p></body></html>',
  'features': {
    'emotion': {
      'targets': [
        'apples',
        'oranges'
      ]
    }
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Emotion feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, EmotionOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    html="<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>",
    features=Features(emotion=EmotionOptions(targets=['apples','oranges']))).get_result()

print(json.dumps(response, indent=2))

Example Emotion feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  html: "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>",
  features: {emotion: {targets: ['apples','oranges']}}
)

puts JSON.pretty_generate(response.result)

Example Emotion feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let html = "<html><head><title>Fruits</title></head>" +
  "<body><h1>Apples and Oranges</h1>" +
  "<p>I love apples! I don't like oranges.</p>" +
  "</body></html>"
let emotion = EmotionOptions(targets: ["apples", "oranges"])
let features = Features(emotion: emotion)
naturalLanguageUnderstanding.analyze(features: features, html: html) {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the EmotionResult object in the Analyze text method.

Example Emotion feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 37,
    "features": 1
  },
  "language": "en",
  "emotion": {
    "targets": [
      {
        "text": "apples",
        "emotion": {
          "sadness": 0.028574,
          "joy": 0.859042,
          "fear": 0.02752,
          "disgust": 0.017519,
          "anger": 0.012855
        }
      },
      {
        "text": "oranges",
        "emotion": {
          "sadness": 0.514253,
          "joy": 0.078317,
          "fear": 0.074223,
          "disgust": 0.058103,
          "anger": 0.126859
        }
      }
    ],
    "document": {
      "emotion": {
        "sadness": 0.32665,
        "joy": 0.563273,
        "fear": 0.033387,
        "disgust": 0.022637,
        "anger": 0.041796
      }
    }
  }
}

Entities

Identifies people, cities, organizations, and other entities in the content. See Entity type systems.

Entities request options

For details, see the request body for the Analyze text method.

  • Maximum number of entities to return.

    Default: 50

  • Whether to return locations of entity mentions.

    Default: false

  • A custom model ID. For more information about how to override the standard entity detection model, see Customizing.

  • Whether to return emotion information for detected entities.

    Default: false

  • Whether to return emotion information for detected entities.

    Default: false

Entities response

Example Entities feature request

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

Example parameters

{
  "url": "www.cnn.com",
  "features": {
    "entities": {
      "sentiment": true,
      "limit": 1
    }
  }
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  url := "www.cnn.com"
  sentiment := true
  limit := int64(1)

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      URL: &url,
      Features: &naturallanguageunderstandingv1.Features{
        Entities: &naturallanguageunderstandingv1.EntitiesOptions{
          Sentiment: &sentiment,
          Limit: &limit,
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Entities feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String url = "www.cnn.com";

EntitiesOptions entities= new EntitiesOptions.Builder()
  .sentiment(true)
  .limit(1)
  .build();

Features features = new Features.Builder()
  .entities(entities)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .url(url)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Entities feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'url': 'www.cnn.com',
  'features': {
    'entities': {
      'sentiment': true,
      'limit': 1
    }
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Entities feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    url='www.cnn.com',
    features=Features(entities=EntitiesOptions(sentiment=True,limit=1))).get_result()

print(json.dumps(response, indent=2))

Example Entities feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  url: "www.cnn.com",
  features: {entities: {sentiment: true, limit: 1}
  }
)

puts JSON.pretty_generate(response.result)

Example Entities feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let entities = EntitiesOptions(limit: 1, sentiment: true)
let features = Features(entities: entities)
naturalLanguageUnderstanding.analyze(features: features, url: "www.cnn.com") {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the EntitiesResult[] object in the Analyze text method.

Example Entities feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 2708,
    "features": 1
  },
  "retrieved_url": "http://www.cnn.com/",
  "language": "en",
  "entities": [
    {
      "type": "Company",
      "text": "CNN",
      "sentiment": {
        "score": 0.0,
        "label": "neutral"
      },
      "relevance": 0.784947,
      "disambiguation": {
        "subtype": [
          "Broadcast",
          "AwardWinner",
          "RadioNetwork",
          "TVNetwork"
        ],
        "name": "CNN",
        "dbpedia_resource": "http://dbpedia.org/resource/CNN"
      },
      "count": 9
    }
  ]
}

Keywords

Returns important keywords in the content.

Keywords request options

For details, see the request body for the Analyze text method.

  • Maximum number of keywords to return.

    Default: 50

  • Whether to return emotion information for detected keywords.

    Default: false

  • Whether to return emotion information for detected keywords.

    Default: false

Keywords response

Example Keywords feature request

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

Example parameters

{
  "url": "www.ibm.com",
  "features": {
    "keywords": {
      "sentiment": true,
      "emotion": true,
      "limit": 3
    }
  }
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  url := "www.ibm.com"
  sentiment := true
  emotion := true
  limit := int64(3)

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      URL: &url,
      Features: &naturallanguageunderstandingv1.Features{
        Keywords: &naturallanguageunderstandingv1.KeywordsOptions{
          Sentiment: &sentiment,
          Emotion: &emotion,
          Limit: &limit,
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Keywords feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String url = "www.ibm.com";

KeywordsOptions keywords= new KeywordsOptions.Builder()
  .sentiment(true)
  .emotion(true)
  .limit(3)
  .build();

Features features = new Features.Builder()
  .keywords(keywords)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .url(url)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'url': 'www.ibm.com',
  'features': {
    'keywords': {
      'sentiment': true,
      'emotion': true,
      'limit': 3
    }
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Keywords feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, KeywordsOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    url='www.ibm.com',
    features=Features(keywords=KeywordsOptions(sentiment=True,emotion=True,limit=2))).get_result()

print(json.dumps(response, indent=2))

Example Keywords feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  url: "www.ibm.com",
  features: {keywords: {sentiment: true, emotion: true, limit: 3}
  }
)

puts JSON.pretty_generate(response.result)

Example Keywords feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let keywords = KeywordsOptions(limit: 3, sentiment: true, emotion: true)
let features = Features(keywords: keywords)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the KeywordsResult[] object in the Analyze text method.

Example Keywords feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 1536,
    "features": 1
  },
  "keywords": [
    {
      "text": "curated online courses",
      "sentiment": {
        "score": 0.792454
      },
      "relevance": 0.864624,
      "emotions": {
        "sadness": 0.188625,
        "joy": 0.522781,
        "fear": 0.12012,
        "disgust": 0.103212,
        "anger": 0.106669
      }
    },
    {
      "text": "free virtual server",
      "sentiment": {
        "score": 0.664726
      },
      "relevance": 0.864593,
      "emotions": {
        "sadness": 0.265225,
        "joy": 0.532354,
        "fear": 0.07773,
        "disgust": 0.090112,
        "anger": 0.102242
      }
    }
  ],
  "language": "en",
  "retrieved_url": "https://www.ibm.com/us-en/"
}

Metadata

Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only.

Metadata request options

No request parameters

This feature does not accept any request options.

Metadata response

Example Metadata feature request

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

Example parameters

{
  "url": "www.ibm.com",
  "features": {
    "metadata": {}
  }
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  url := "www.ibm.com"

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      URL: &url,
      Features: &naturallanguageunderstandingv1.Features{
        Metadata: &naturallanguageunderstandingv1.MetadataOptions{},
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Metadata feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String url = "www.ibm.com";

MetadataOptions metadata= new MetadataOptions();

Features features = new Features.Builder()
  .metadata(metadata)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .url(url)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Metadata feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'url': 'www.ibm.com',
  'features': {
    'metadata': {}
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Metadata feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, MetadataOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    url='www.ibm.com',
    features=Features(metadata=MetadataOptions())).get_result()

print(json.dumps(response, indent=2))

Example Metadata feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  url: "www.ibm.com",
  features: {metadata: {}
  }
)

puts JSON.pretty_generate(response.result)

Example Metadata feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let features = Features(metadata: MetadataOptions())
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the MetadataResult object in the Analyze text method.

Example Metadata feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 1536,
    "features": 1
  },
  "retrieved_url": "https://www.ibm.com/us-en/",
  "metadata": {
    "title": "IBM - United States",
    "publication_date": "2015-10-01T00:00:00",
    "image": "",
    "feeds": [],
    "authors": []
  },
  "language": "en"
}

Relations

Recognizes when two entities are related and identifies the type of relation. For example, an awardedTo relation might connect the entities "Nobel Prize" and "Albert Einstein".

Relations request options

For details, see the request body for the Analyze text method.

  • A custom model ID. For more information about how to override the default relations model, see Customizing.

    Default: en-news

Relations response

Example Relations feature request

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

Example parameters

{
  "features": {
    "relations": {}
  },
  "text": "Leonardo DiCaprio won Best Actor in a Leading Role for his performance."
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  text := "Leonardo DiCaprio won Best Actor in a Leading Role for his performance."

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      Text: &text,
      Features: &naturallanguageunderstandingv1.Features{
        Relations: &naturallanguageunderstandingv1.RelationsOptions{},
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Relations feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String text = "Leonardo DiCaprio won Best Actor" +
  " in a Leading Role for his performance.";

RelationsOptions relations = new RelationsOptions.Builder()
  .build();

Features features = new Features.Builder()
  .relations(relations)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .text(text)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Relations feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'features': {
    'relations': {}
  },
  'text': 'Leonardo DiCaprio won Best Actor in a Leading Role for his performance.'
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Relations feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, RelationsOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    text='Leonardo DiCaprio won Best Actor in a Leading Role for his performance.',
    features=Features(relations=RelationsOptions())).get_result()

print(json.dumps(response, indent=2))

Example Relations feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  text: "Leonardo DiCaprio won Best Actor in a Leading Role for his performance.",
  features: {relations: {}
  }
)

puts JSON.pretty_generate(response.result)

Example Relations feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let text = "Leonardo DiCaprio won Best Actor" +
           " in a Leading Role for his performance."
let features = Features(relations: RelationsOptions())
naturalLanguageUnderstanding.analyze(features: features, text: text) {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the RelationsResult[] object in the Analyze text method.

Example Relations feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 79,
    "features": 1
  },
  "relations": [
    {
      "type": "awardedTo",
      "sentence": "Leonardo DiCaprio won Best Actor in a Leading Role for his performance.",
      "score": 0.680715,
      "arguments": [
        {
          "text": "Best Actor",
          "location": [
            22,
            32
          ],
          "entities": [
            {
              "type": "EntertainmentAward",
              "text": "Best Actor"
            }
          ]
        },
        {
          "text": "Leonardo DiCaprio",
          "location": [
            0,
            17
          ],
          "entities": [
            {
              "type": "Person",
              "text": "Leonardo DiCaprio"
            }
          ]
        }
      ]
    }
  ],
  "language": "en"
}

Semantic Roles

Parses sentences into subject, action, and object form.

Semantic Roles request options

For details, see the request body for the Analyze text method.

  • Maximum number of semantic_roles results to return.

    Default: 50

  • Whether to return keyword information for subjects and objects.

    Default: false

  • Whether to return entity information for subjects and objects.

    Default: false

Semantic roles response

Example Relations feature request

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

Example parameters

{
  "features": {
    "semantic_roles": {}
  },
  "text": "IBM has one of the largest workforces in the world"
}
package main

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL: "{url}",
      Version: "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  text := "IBM has one of the largest workforces in the world"

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      Text: &text,
      Features: &naturallanguageunderstandingv1.Features{
        SemanticRoles: &naturallanguageunderstandingv1.SemanticRolesOptions{},
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Relations feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String text = "IBM has one of the largest" +
  " workforces in the world";

SemanticRolesOptions semanticRoles = new SemanticRolesOptions.Builder()
  .build();

Features features = new Features.Builder()
  .semanticRoles(semanticRoles)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .text(text)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Relations feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'features': {
    'semantic_roles': {}
  },
  'text': 'IBM has one of the largest workforces in the world'
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Relations feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, SemanticRolesOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    text='IBM has one of the largest workforces in the world',
    features=Features(semantic_roles=SemanticRolesOptions())).get_result()

print(json.dumps(response, indent=2))

Example Relations feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  text: "IBM has one of the largest workforces in the world",
  features: {semantic_roles: {}
  }
)

puts JSON.pretty_generate(response.result)

Example Relations feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let text = "IBM has one of the largest" +
            " workforces in the world"
let semanticRoles = Features(semanticRoles: SemanticRolesOptions())
naturalLanguageUnderstanding.analyze(features: semanticRoles, text: text) {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the SemanticRolesResult[] object in the Analyze text method.

Example Semantic Roles feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 50,
    "features": 1
  },
  "semantic_roles": [
    {
      "subject": {
        "text": "IBM"
      },
      "sentence": "IBM has one of the largest workforces in the world",
      "object": {
        "text": "one of the largest workforces in the world"
      },
      "action": {
        "verb": {
          "text": "have",
          "tense": "present"
        },
        "text": "has",
        "normalized": "have"
      }
    }
  ],
  "language": "en"
}

Sentiment

Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with entities.sentiment and for keywords with keywords.sentiment .

Sentiment request options

For details, see the request body for the Analyze text method.

  • Whether to return document-level sentiment analysis.

    Default: true

  • Target strings, separated by commas. Sentiment results are returned for each target string found in the document.

Sentiment response

Example Sentiment feature request

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

Example parameters

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

import (
  "encoding/json"
  "fmt"
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL:       "{url}",
      Version:   "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  url := "www.wsj.com/news/markets"
  targets := []string{"stocks"}

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      URL: &url,
      Features: &naturallanguageunderstandingv1.Features{
        Sentiment: &naturallanguageunderstandingv1.SentimentOptions{
          Targets: targets,
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Sentiment feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String url = "www.wsj.com/news/markets";

List<String> targets = new ArrayList<>();
targets.add("stocks");

SentimentOptions sentiment = new SentimentOptions.Builder()
  .targets(targets)
  .build();

Features features = new Features.Builder()
  .sentiment(sentiment)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .url(url)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Sentiment feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'url': 'www.wsj.com/news/markets',
  'features': {
    'sentiment': {
      'targets': [
        'stocks'
      ]
    }
  }
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Sentiment feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, SentimentOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    url='www.wsj.com/news/markets',
    features=Features(sentiment=SentimentOptions(targets=['stocks']))).get_result()

print(json.dumps(response, indent=2))

Example Sentiment feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  url: "www.wsj.com/news/markets",
  features: {sentiment: {targets=["stocks"]}
  }
)

puts JSON.pretty_generate(response.result)

Example Sentiment feature request

let sentiment = SentimentOptions(targets: ["stocks"])
let features = Features(sentiment: sentiment)
naturalLanguageUnderstanding.analyze(features: features, url: "www.wsj.com/news/markets") {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the SentimentResult object in the Analyze text method.

Example Sentiment feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 1188,
    "features": 1
  },
  "sentiment": {
    "targets": [
      {
        "text": "stocks",
        "score": 0.279964,
        "label": "positive"
      }
    ],
    "document": {
      "score": 0.127034,
      "label": "positive"
    }
  },
  "retrieved_url": "https://www.wsj.com/news/markets",
  "language": "en"
}

Syntax (Experimental)

Returns information about the tokens and sentences in the input text. At least one of syntax.tokens or syntax.sentences must be specified.

Syntax request options

For details, see the request body for the Analyze text method.

  • Set this to true to return information about the sentences in the input text.

  • Options for tokens

Syntax response

Example Syntax feature request

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

Example parameters

{
  "text": "With great power comes great responsibility",
  "features": {
    "syntax": {
      "sentences": true,
      "tokens": {
        "lemma": true,
        "part_of_speech": true
      }
    }
  }
}
package main

import (
  "encoding/json"
  "fmt"

  "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)

func main() {
  naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.
    NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
      URL:       "{url}",
      Version:   "2018-11-16",
      IAMApiKey: "{apikey}",
    })
  if naturalLanguageUnderstandingErr != nil {
    panic(naturalLanguageUnderstandingErr)
  }

  text := "With great power comes great responsibility"
  sentences := true
  lemma := true
  partOfSpeech := true

  response, responseErr := naturalLanguageUnderstanding.Analyze(
    &naturallanguageunderstandingv1.AnalyzeOptions{
      Text: &text,
      Features: &naturallanguageunderstandingv1.Features{
        Syntax: &naturallanguageunderstandingv1.SyntaxOptions{
          Sentences: &sentences,
          Tokens: &naturallanguageunderstandingv1.SyntaxOptionsTokens{
            Lemma:        &lemma,
            PartOfSpeech: &partOfSpeech,
          },
        },
      },
    },
  )
  if responseErr != nil {
    panic(responseErr)
  }
  result := naturalLanguageUnderstanding.GetAnalyzeResult(response)
  b, _ := json.MarshalIndent(result, "", "   ")
  fmt.Println(string(b))
}

Example Syntax feature request

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2018-11-16", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

String text = "With great power comes great responsibility"

SyntaxOptions syntax = new SyntaxOptions.Builder()
  .sentences(true)
  .build();

Features features = new Features.Builder()
  .syntax(syntax)
  .build();

AnalyzeOptions parameters = new AnalyzeOptions.Builder()
  .text(text)
  .features(features)
  .build();

AnalysisResults response = naturalLanguageUnderstanding
  .analyze(parameters)
  .execute()
  .getResult();
System.out.println(response);

Example Syntax feature request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1.js');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

const analyzeParams = {
  'features': {
    'syntax': {
      'sentences': true,
      'tokens': {
        'lemma': true,
        'part_of_speech': true
      }
    }
  },
  'text': 'With great power comes great responsibility'
};

naturalLanguageUnderstanding.analyze(analyzeParams)
  .then(analysisResults => {
    console.log(JSON.stringify(analysisResults, null, 2));
  })
  .catch(err => {
    console.log('error:', err);
  });

Example Syntax feature request

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1
from watson_developer_cloud.natural_language_understanding_v1 import Features, SemanticRolesOptions

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='{apikey}',
    url='{url}'
)

response = natural_language_understanding.analyze(
    text='With great power comes great responsibility',
    features=Features(
      syntax=SyntaxOptions(
        sentences=True,
        tokens=SyntaxOptionsTokens(
          lemma=True,
          part_of_speech=True,
        )))).get_result()

print(json.dumps(response, indent=2))

Example Syntax feature request

require "json"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "2018-11-16",
  iam_apikey: "{apikey}",
  url: "{url}"
)

response = natural_language_understanding.analyze(
  text: "With great power comes great responsibility",
  features: {
    syntax: {
      sentences: true,
      tokens: {
        lemma: true,
        part_of_speech: true,
      }
    }
  }
)

puts JSON.pretty_generate(response.result)

Example Syntax feature request

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2018-11-16", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "{url}"

let text = "With great power comes great responsibility"
let tokens = SyntaxOptionsTokens(lemma: true, partOfSpeech: true)
let syntax = SyntaxOptions(sentences: true, tokens: tokens)
let features = Features(syntax: syntax)
naturalLanguageUnderstanding.analyze(features: features, text: text) {
  response, error in

  guard let analysis = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(analysis)
}

See the SyntaxResult object in the Analyze text method.

Example Syntax feature response

{
  "usage": {
    "text_units": 1,
    "text_characters": 43,
    "features": 0
  },
  "syntax": {
    "tokens": [
      {
        "text": "With",
        "part_of_speech": "ADP",
        "location": [
          0,
          4
        ],
        "lemma": "with"
      },
      {
        "text": "great",
        "part_of_speech": "ADJ",
        "location": [
          5,
          10
        ],
        "lemma": "great"
      },
      {
        "text": "power",
        "part_of_speech": "NOUN",
        "location": [
          11,
          16
        ],
        "lemma": "power"
      },
      {
        "text": "comes",
        "part_of_speech": "VERB",
        "location": [
          17,
          22
        ],
        "lemma": "come"
      },
      {
        "text": "great",
        "part_of_speech": "ADJ",
        "location": [
          23,
          28
        ],
        "lemma": "great"
      },
      {
        "text": "responsibility",
        "part_of_speech": "NOUN",
        "location": [
          29,
          43
        ],
        "lemma": "responsibility"
      }
    ],
    "sentences": [
      {
        "text": "With great power comes great responsibility",
        "location": [
          0,
          43
        ]
      }
    ]
  },
  "language": "en"
}

Authentication

IBM Cloud is migrating to token-based Identity and Access Management (IAM) authentication.

  • With some service instances, you authenticate to the API by using IAM. You can pass either a bearer token in an Authorization header or an API key. Tokens support authenticated requests without embedding service credentials in every call. API keys use basic authentication. Learn more about IAM.

    If you pass in an API key, use apikey for the username and the value of the API key as the password.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

  • In other instances, you authenticate by providing the username and password for the service instance. For more information, see Service credentials for Watson services.

To find out which authentication to use, view the service credentials by clicking the service instance in the Resource list.

The "username" and "password" in the service credentials are different from your IBM Cloud account IBMid and password.

IAM authentication. Replace {apikey} and {url} with your service credentials.

curl -u "apikey:{apikey}" -X {request_method} "{url}/{method}"

Basic authentication. Replace {username}, {password}, and {url} with your service credentials.

curl -u "{username}:{password}" -X {request_method} "{url}/{method}"

SDK managing the IAM token. Replace {apikey}, {version} and {url}.

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

Basic authentication. Replace {username}, {password}, `, and{url}`. Use either of the two constructors.

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
    "{version}",
    "{username}",
    "{password}");
naturalLanguageUnderstanding.setEndPoint("{url}");

or

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}");
naturalLanguageUnderstanding.setUsernameAndPassword("{username}","{password}");
naturalLanguageUnderstanding.setEndPoint("{url}");

SDK managing the IAM token. Replace {apikey}, {version} and {url}.

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  iam_apikey: '{apikey}',
  url: '{url}'
});

Basic authentication. Replace {username}, {password}, {version}, and {url}.

const  = require('ibm-watson/natural-language-understanding/v1');

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  username: '{username}',
  password: '{password}',
  url: '{url}'
});

SDK managing the IAM token. Replace {apikey}, {version} and {url}.

from ibm_watson import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    iam_apikey='{apikey}',
    url='{url}'
)

Basic authentication. Replace {username}, {password}, `, and{url}`.

from ibm_watson import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    username='{username}',
    password='{password}',
    url='{url}'
)

SDK managing the IAM token. Replace {apikey}, {version} and {url}.

require "ibm_watson"

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "{version}",
  iam_apikey: "{apikey}",
  url:"{url}"
)

Basic authentication. Replace {username}, {password}, `, and{url}`.

require "ibm_watson"

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "{version}",
  username: "{username}",
  password: "{password}",
  url:"{url}"
)

SDK managing the IAM token. Replace {apikey}, {version} and {url}.

import "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version: "{version}",
  IAMApiKey: "{apikey}",
  URL: "{url}",
})

Basic authentication. Replace {username}, {password}, `, and{url}`.

import "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version: "{version}",
  Username: "{username}",
  Password: "{password}",
  URL: "{url}",
})

SDK managing the IAM token. Replace {apikey}, {version} and {url}.

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", apiKey: "{apikey}")

naturalLanguageUnderstanding.serviceURL = "{url}"

Basic authentication. Replace {username}, {password}, `, and{url}`.

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", username: "{username}", password: "{password}")

naturalLanguageUnderstanding.serviceURL = "{url}"

Service endpoint

The service endpoint is based on the location of the service instance. For example, when Natural Language Understanding is hosted in Frankfurt, the base URL is https://gateway-fra.watsonplatform.net/natural-language-understanding/api. The URL might also be different when you use IBM Cloud Dedicated.

To find out which URL to use, view the service credentials by clicking the service instance in the Resource list.

Use that URL in your requests to Natural Language Understanding.

Set the correct service URL by calling the setEndPoint() method of the service instance.

Set the correct service URL by calling the url parameter when you create the service instance.

Set the correct service URL by calling the url parameter when you create the service instance or by calling the set_url() method of the service instance.

Set the correct service URL by calling the url parameter when you create the service instance or by calling the url= method of the service instance.

Set the correct service URL by the URL parameter when you create the service instance or by calling the SetURL= method of the service instance.

Set the correct service URL by setting the serviceURL property of the service instance.

Service endpoints by location:

  • Dallas: https://gateway.watsonplatform.net/natural-language-understanding/api
  • Washington DC: https://gateway-wdc.watsonplatform.net/natural-language-understanding/api
  • Frankfurt: https://gateway-fra.watsonplatform.net/natural-language-understanding/api
  • Sydney: https://gateway-syd.watsonplatform.net/natural-language-understanding/api
  • Tokyo: https://gateway-tok.watsonplatform.net/natural-language-understanding/api
  • London: https://gateway-lon.watsonplatform.net/natural-language-understanding/api

All locations might not support Natural Language Understanding. For details, see Service availability.

Dallas API endpoint example

curl -u "apikey:{apikey}" -X {request_method} "https://gateway.watsonplatform.net/natural-language-understanding/api"

Your service instance might not use this URL

Default URL

https://gateway.watsonplatform.net/natural-language-understanding/api

Example for the Washington DC location

NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}");
naturalLanguageUnderstanding.setEndPoint("https://gateway-wdc.watsonplatform.net/natural-language-understanding/api");

Default URL

https://gateway.watsonplatform.net/natural-language-understanding/api

Example for the Washington DC location

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  iam_apikey: '{apikey}',
  url: 'https://gateway-wdc.watsonplatform.net/natural-language-understanding/api'
});

Default URL

https://gateway.watsonplatform.net/natural-language-understanding/api

Examples for the Washington DC location in the constructor and after instantiation

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    iam_apikey='{apikey}',
    url='https://gateway-wdc.watsonplatform.net/natural-language-understanding/api'
)

or

natural_language_understanding.set_url('https://gateway-wdc.watsonplatform.net/natural-language-understanding/api')

Default URL

https://gateway.watsonplatform.net/natural-language-understanding/api

Examples for the Washington DC location in the constructor and after instantiation

natural_language_understanding = IBMWatson::.new(
  version: "{version}",
  api_key: "{apikey}",
  url: "https://gateway-wdc.watsonplatform.net/natural-language-understanding/api"
)

or

natural_language_understanding.url = "https://gateway-wdc.watsonplatform.net/natural-language-understanding/api"

Default URL

https://gateway.watsonplatform.net/natural-language-understanding/api

Examples for the Washington DC location in the constructor and after instantiation

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version: "{version}",
  IAMApiKey: "{apikey}",
  URL: "https://gateway-wdc.watsonplatform.net/natural-language-understanding/api",
})

or

naturalLanguageUnderstanding.SetURL("https://gateway-wdc.watsonplatform.net/natural-language-understanding/api")

Default URL

https://gateway.watsonplatform.net/natural-language-understanding/api

Example for the Washington DC location

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", apiKey: "{apikey}")
naturalLanguageUnderstanding.serviceURL = "https://gateway-wdc.watsonplatform.net/natural-language-understanding/api"

Disabling SSL verification

All Watson services use Secure Sockets Layer (SSL) (or Transport Layer Security (TLS)) for secure connections between the client and server. The connection is verified against the local certificate store to ensure authentication, integrity, and confidentiality.

If you use a self-signed certificate, you need to disable SSL verification to make a successful connection.

Enabling SSL verification is highly recommended. Disabling SSL jeopardizes the security of the connection and data. Disable SSL only if absolutely necessary, and take steps to enable SSL as soon as possible.

To disable SSL verification for a curl request, use the --insecure (-k) option with the request.

To disable SSL verification, create an HttpConfigOptions object and set the disableSslVerification property to true. Then pass the object to the service instance by using the configureClient method.

To disable SSL verification, set the disable_ssl_verification parameter to true when you create the service instance.

To disable SSL verification, call the disable_SSL_verification method on the service instance.

To disable SSL verification, call the configure_http_client method on the service instance and set the disable_ssl parameter to true.

To disable SSL verification, call the DisableSSLVerification method on the service instance.

You cannot disable SSL verification with the Swift SDK.

Example that disables SSL verification

IAM authentication. Replace {apikey} and {url} with your service credentials.

curl -k -u "apikey:{apikey}" -X {request_method} "{url}/{method}"

Example that disables SSL verification

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", options);
naturalLanguageUnderstanding.setEndPoint("{url}");

HttpConfigOptions configOptions = new HttpConfigOptions.Builder()
  .disableSslVerification(true)
  .build();
naturalLanguageUnderstanding.configureClient(configOptions);

Example that disables SSL verification

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  iam_apikey: '{apikey}',
  url: '{url}',
  disable_ssl_verification: true,
});

Example that disables SSL verification

from ibm_watson import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    iam_apikey='{apikey}',
    url='{url}'
)
natural_language_understanding.disable_SSL_verification()

Example that disables SSL verification

require "ibm_watson"

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "{version}",
  iam_apikey: "{apikey}",
  url:"{url}"
)
natural_language_understanding.configure_http_client(disable_ssl: true)

Example that disables SSL verification

import "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version: "{version}",
  IAMApiKey: "{apikey}",
  URL: "{url}",
})
naturalLanguageUnderstanding.DisableSSLVerification()

Versioning

API requests require a version parameter that takes a date in the format version=YYYY-MM-DD. When we change the API in a backwards-incompatible way, we release a new version date.

Send the version parameter with every API request. The service uses the API version for the date you specify, or the most recent version before that date. Don't default to the current date. Instead, specify a date that matches a version that is compatible with your app, and don't change it until your app is ready for a later version.

Specify the version to use on API requests with the version parameter when you create the service instance. The service uses the API version for the date you specify, or the most recent version before that date. Don't default to the current date. Instead, specify a date that matches a version that is compatible with your app, and don't change it until your app is ready for a later version.

This documentation describes the current version of Natural Language Understanding, 2018-11-16. In some cases, differences in earlier versions are noted in the descriptions of parameters and response models.

Error handling

The Natural Language Understanding service uses standard HTTP response codes to indicate whether a method completed successfully. HTTP response codes in the 2xx range indicate success. A response in the 4xx range is some sort of failure, and a response in the 5xx range usually indicates an internal system error that cannot be resolved by the user. Response codes are listed with the method.

ErrorResponse

Name Description
code
integer
The HTTP response code.
error
string
General description of an error.

The Java SDK generates an exception for any unsuccessful method invocation. All methods that accept an argument can also throw an IllegalArgumentException.

Exception Description
IllegalArgumentException An illegal argument was passed to the method.

When the Java SDK receives an error response from the Natural Language Understanding service, it generates an exception from the com.ibm.watson.developer_cloud.service.exception package. All service exceptions contain the following fields.

Field Description
statusCode The HTTP response code returned.
message A message that describes the error.

When the Node SDK receives an error response from the Natural Language Understanding service, it creates an Error object with information that describes the error that occurred. This error object is passed as the first parameter to the callback function for the method. The contents of the error object are as shown in the following table.

Error

Field Description
code The HTTP response code returned.
message A message that describes the error.

The Python SDK generates an exception for any unsuccessful method invocation. When the Python SDK receives an error response from the Natural Language Understanding service, it generates an ApiException that contains the following fields.

Field Description
code The HTTP response code returned.
message A message that describes the error.
info A dictionary of additional information about the error.

When the Ruby SDK receives an error response from the Natural Language Understanding service, it generates an ApiException that contains the following fields.

Field Description
code The HTTP response code returned.
message A message that describes the error.
info A dictionary of additional information about the error.

The Go SDK generates an error for any unsuccessful service instantiation and method invocation. You can check for the error immediately. The contents of the error object are as shown in the following table.

Error

Field Description
code The HTTP response code returned.
message A message that describes the error.

The Swift SDK returns a WatsonError in the completionHandler any unsuccessful method invocation. This error type is an enum that conforms to LocalizedError and contains an errorDescription property that returns an error message. Some of the WatsonError cases contain associated values that reveal more information about the error.

Field Description
errorDescription A message that describes the error.

Example error handling

try {
  // Invoke a Natural Language Understanding method
} catch (NotFoundException e) {
  // Handle Not Found (404) exception
} catch (RequestTooLargeException e) {
  // Handle Request Too Large (413) exception
} catch (ServiceResponseException e) {
  // Base class for all exceptions caused by error responses from the service
  System.out.println("Service returned status code "
    + e.getStatusCode() + ": " + e.getMessage());
}

Example error handling

naturalLanguageUnderstanding.method(params)
  .catch(err => {
    console.log('error:', err);
  });

Example error handling

from ibm_watson import ApiException
try:
    # Invoke a Natural Language Understanding method
except ApiException as ex:
    print "Method failed with status code " + str(ex.code) + ": " + ex.message

Example error handling

require "ibm_watson"
begin
  # Invoke a Natural Language Understanding method
rescue IBMWatson::ApiException => ex
  print "Method failed with status code #{ex.code}: #{ex.error}"
end

Example error handling

import "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"

// Instantiate a service
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturalLanguageUnderstandingv1.NaturalLanguageUnderstandingV1Options{})

// Check for error
if naturalLanguageUnderstandingErr != nil {
  panic(naturalLanguageUnderstandingErr)
}

// Call a method
response, responseErr := naturalLanguageUnderstanding.methodName(&methodOptions)

// Check for error
if responseErr != nil {
  panic(responseErr)
}

Example error handling

naturalLanguageUnderstanding.method() {
  response, error in

  if let error = error {
    switch error {
    case let .http(statusCode, message, metadata):
      switch statusCode {
      case .some(404):
        // Handle Not Found (404) exception
        print("Not found")
      case .some(413):
        // Handle Request Too Large (413) exception
        print("Payload too large")
      default:
        if let statusCode = statusCode {
          print("Error - code: \(statusCode), \(message ?? "")")
        }
      }
    default:
      print(error.localizedDescription)
    }
    return
  }

  guard let result = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }

  print(result)
}

Data handling

Additional headers

Some Watson services accept special parameters in headers that are passed with the request.

You can pass request header parameters in all requests or in a single request to the service.

To pass a request header, use the --header (-H) option with a curl request.

To pass header parameters with every request, use the setDefaultHeaders method of the service object. See Data collection for an example use of this method.

To pass header parameters in a single request, use the addHeader method as a modifier on the request before you execute the request.

To pass header parameters with every request, specify the headers parameter when you create the service object. See Data collection for an example use of this method.

To pass header parameters in a single request, use the headers method as a modifier on the request before you execute the request.

To pass header parameters with every request, specify the set_default_headers method of the service object. See Data collection for an example use of this method.

To pass header parameters in a single request, include headers as a dict in the request.

To pass header parameters with every request, specify the add_default_headers method of the service object. See Data collection for an example use of this method.

To pass header parameters in a single request, specify the headers method as a chainable method in the request.

To pass header parameters with every request, specify the SetDefaultHeaders method of the service object. See Data collection for an example use of this method.

To pass header parameters in a single request, specify the Headers as a map in the request.

To pass header parameters with every request, add them to the defaultHeaders property of the service object. See Data collection for an example use of this method.

To pass header parameters in a single request, pass the headers parameter to the request method.

Example header parameter in a request

curl -u "apikey:{apikey}" -X {request_method} --header "Request-Header: {header_value}" "{url}/{method}"

Example header parameter in a request

ReturnType returnValue = naturalLanguageUnderstanding.methodName(parameters)
  .addHeader("Custom-Header", "{header_value}")
  .execute();

Example header parameter in a request

const parameters = {
  {parameters}
};

naturalLanguageUnderstanding.methodName(
  parameters,
  headers: {
    'Custom-Header': '{header_value}'
  })
   .then(result => {
    console.log(response);
  })
  .catch(err => {
    console.log('error:', err);
  });

Example header parameter in a request

response = natural_language_understanding.methodName(
    parameters,
    headers = {
        'Custom-Header': '{header_value}'
    })

Example header parameter in a request

response = natural_language_understanding.headers(
  "Custom-Header" => "{header_value}"
).methodName(parameters)

Example header parameter in a request

response, _ := naturallanguageunderstandingv1.methodName(
  &methodOptions{
    Headers: map[string]string{
      "Accept": "application/json",
    },
  },
)

Example header parameter in a request

let customHeader: [String: String] = ["Custom-Header": "{header_value}"]
naturalLanguageUnderstanding.methodName(parameters, headers: customHeader) {
  response, error in
}

Response details

The Natural Language Understanding service might return information to the application in response headers.

To access all response headers that the service returns, include the --include (-i) option with a curl request. To see detailed response data for the request, including request headers, response headers, and additional debugging information, include the --verbose (-v) option with the request.

Example request to access response headers

curl -u "apikey:{apikey}" -X {request_method} --include "{url}/{method}"

To access information in the response headers, use one of the request methods that returns details with the response: executeWithDetails(), enqueueWithDetails(), or rxWithDetails(). These methods return a Response<T> object, where T is the expected response model. Use the getResult() method to access the response object for the method, and use the getHeaders() method to access information in response headers.

Example request to access response headers

Response<ReturnType> response = naturalLanguageUnderstanding.methodName(parameters)
  .executeWithDetails();
// Access response from methodName
ReturnType returnValue = response.getResult();
// Access information in response headers
Headers responseHeaders = response.getHeaders();

To access information in the response headers, add the return_response parameter set to true and specify the headers attribute on the response object that is returned by the method.

Example request to access response headers

const parameters = {
  {parameters}
};

parameters.return_response = true;

naturalLanguageUnderstanding.methodName(parameters)
  .then(response => {
    console.log(response.headers);
  })
  .catch(err => {
    console.log('error:', err);
  });

The return value from all service methods is a DetailedResponse object. To access information in the result object or response headers, use the following methods.

DetailedResponse

Method Description
get_result() Returns the response for the service-specific method.
get_headers() Returns the response header information.
get_status_code() Returns the HTTP status code.

Example request to access response headers

natural_language_understanding.set_detailed_response(True)
response = natural_language_understanding.methodName(parameters)
# Access response from methodName
print(json.dumps(response.get_result(), indent=2))
# Access information in response headers
print(response.get_headers())
# Access HTTP response status
print(response.get_status_code())

The return value from all service methods is a DetailedResponse object. To access information in the response object, use the following properties.

DetailedResponse

Property Description
result Returns the response for the service-specific method.
headers Returns the response header information.
status Returns the HTTP status code.

Example request to access response headers

response = natural_language_understanding.methodName(parameters)
# Access response from methodName
print response.result
# Access information in response headers
print response.headers
# Access HTTP response status
print response.status

The return value from all service methods is a DetailedResponse object. To access information in the response object or response headers, use the following methods.

DetailedResponse

Method Description
GetResult() Returns the response for the service-specific method.
GetHeaders() Returns the response header information.
GetStatusCode() Returns the HTTP status code.

Example request to access response headers

import "github.com/IBM/go-sdk-core/core"
response, _ := naturallanguageunderstandingv1.methodName(&methodOptions{})

// Access result
core.PrettyPrint(response.GetResult(), "Result ")

// Access response headers
core.PrettyPrint(response.GetHeaders(), "Headers ")

// Access status code
core.PrettyPrint(response.GetStatusCode(), "Status Code ")

All response data is available in the WatsonResponse<T> object returned in each method's completionHandler.

Example request to access response headers

naturalLanguageUnderstanding.methodName(parameters) {
  response, error in

  guard let result = response?.result else {
    print(error?.localizedDescription ?? "unknown error")
    return
  }
  print(result) // The data returned by the service
  print(response?.statusCode)
  print(response?.headers)
}

Data collection

By default, all Watson services log requests and their results. Logging is done only to improve the services for future users. The logged data is not shared or made public.

To prevent IBM usage of your data for an API request, set the X-Watson-Learning-Opt-Out header parameter to true.

You must set the header on each request that you do not want IBM to access for general service improvements.

You can set the header by using the setDefaultHeaders method of the service object.

You can set the header by using the headers parameter when you create the service object.

You can set the header by using the set_default_headers method of the service object.

You can set the header by using the add_default_headers method of the service object.

You can set the header by using the SetDefaultHeaders method of the service object.

You can set the header by adding it to the defaultHeaders property of the service object.

Example request

curl -u "apikey:{apikey}" -H "X-Watson-Learning-Opt-Out: true" "{url}/{method}"

Example request

Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Watson-Learning-Opt-Out", "true");

naturalLanguageUnderstanding.setDefaultHeaders(headers);

Example request

const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  iam_apikey: '{apikey}',
  url: '{url}',
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});

Example request

natural_language_understanding.set_default_headers({'x-watson-learning-opt-out': "true"})

Example request

natural_language_understanding.add_default_headers(headers: {"x-watson-learning-opt-out" => "true"})

Example request

import "net/http"

headers := http.Header{}
headers.Add("x-watson-learning-opt-out", "true")
naturallanguageunderstandingv1.Service.SetDefaultHeaders(headers)

Example request

naturalLanguageUnderstanding.defaultHeaders["X-Watson-Learning-Opt-Out"] = "true"

Synchronous and asynchronous requests

The Java SDK supports both synchronous (blocking) and asynchronous (non-blocking) execution of service methods. All service methods implement the ServiceCall interface.

  • To call a method synchronously, use the execute method of the ServiceCall interface. You can call the execute method directly from an instance of the service.
  • To call a method asynchronously, use the enqueue method of the ServiceCall interface to receive a callback when the response arrives. The ServiceCallback interface of the method's argument provides onResponse and onFailure methods that you override to handle the callback.

The Ruby SDK supports both synchronous (blocking) and asynchronous (non-blocking) execution of service methods. All service methods implement the Concurrent::Async module. When you use the synchronous or asynchronous methods, an IVar object is returned. You access the DetailedResponse object by calling ivar_object.value.

For more information about the Ivar object, see the IVar class docs.

  • To call a method synchronously, either call the method directly or use the .await chainable method of the Concurrent::Async module.

    Calling a method directly (without .await) returns a DetailedResponse object.

  • To call a method asynchronously, use the .async chainable method of the Concurrent::Async module.

You can call the .await and .async methods directly from an instance of the service.

Example synchronous request

ReturnType returnValue = naturalLanguageUnderstanding.method(parameters).execute();

Example asynchronous request

naturalLanguageUnderstanding.method(parameters).enqueue(new ServiceCallback<ReturnType>() {
  @Override public void onResponse(ReturnType response) {
    . . .
  }
  @Override public void onFailure(Exception e) {
    . . .
  }
});

Example synchronous request

response = natural_language_understanding.method_name(parameters)

or

response = natural_language_understanding.await.method_name(parameters)

Example asynchronous request

response = natural_language_understanding.async.method_name(parameters)

Methods

Analyze text (GET)

Analyzes raw text, HTML, or a public webpage.

GET /v1/analyze
Request

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-11-16.

    Constraints: Value must match regular expression ^\d{4}-\d{2}-\d{2}$

  • Comma separated list of analysis features

    Allowable values: [categories,concepts,emotion,entities,keywords,metadata,relations,semantic_roles,sentiment,syntax]

  • URL-encoded text to analyze. One of the text, html, or url parameters is required.

  • URL-encoded HTML to analyze. One of the text, html, or url parameters is required.

  • Public webpage to analyze. One of the text, html, or url parameters is required. url is not supported in IBM Cloud Dedicated instances.

  • Set this to true to show the analyzed text in the response

    Default: false

  • Set this to false to disable text cleaning when analyzing webpages. To learn more about webpage cleaning, see the Analyzing webpages documentation.

    Default: true

  • An XPath query to perform on html or url input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.

  • Whether to use raw HTML content if text cleaning fails

    Default: true

  • ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See Language support for more information.

  • Set this to true to return explanations for each categorization. This feature is available only for English language text.

    Default: false

  • Maximum number of categories to return.

    Constraints: value ≤ 10

    Default: 3

  • Enter a custom model ID to override the standard categories model

  • Maximum number of concepts to return.

    Constraints: value ≤ 50

    Default: 8

  • Set this to false to hide document-level emotion results

    Default: true

  • Target strings, separated by commas. Emotion results will be returned for each target string found in the document

  • Maximum number of entities to return.

    Constraints: value ≤ 250

    Default: 50

  • Set this to true to return locations of entity mentions

    Default: false

  • Enter a custom model ID to override the standard entity detection model

  • Set this to true to return emotion information for detected entities

    Default: false

  • Set this to true to return sentiment information for detected entities

    Default: false

  • Maximum number of keywords to return.

    Constraints: value ≤ 250

    Default: 50

  • Set this to true to return emotion information for detected keywords

    Default: false

  • Set this to true to return sentiment information for detected keywords

    Default: false

  • Enter a custom model ID to override the default en-news relations model

    Default: en-news

  • Maximum number of semantic_roles results to return

    Default: 50

  • Set this to true to return entity information for subjects and objects

    Default: false

  • Set this to true to return keyword information for subjects and objects

    Default: false

  • Set this to false to disable document level sentiment analysis

    Default: true

  • Sentiment information will return for each target string that is found in the text

  • Set this to true to return information about the tokens in the input text.

    Default: false

  • Set this to true to return the lemma for each token.

    Default: false

  • Set this to true to return the part of speech for each token.

    Default: false

  • Set this to true to return information about the sentences in the input text.

    Default: false

  • Sets the maximum number of characters that are processed by the service.

Response

Results of the analysis, organized by feature

Status Code

  • Analysis results

  • Invalid request

Example responses

Analyze text

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).

Analyzes text, HTML, or a public webpage for the following features:

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment
  • Syntax (Experimental).
POST /v1/analyze
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) Analyze(analyzeOptions *AnalyzeOptions) (*core.DetailedResponse, error)
ServiceCall<AnalysisResults> analyze(AnalyzeOptions analyzeOptions)
analyze(params, callback())
analyze(self, features, text=None, html=None, url=None, clean=None, xpath=None, fallback_to_raw=None, return_analyzed_text=None, language=None, limit_text_characters=None, **kwargs)
analyze(features:, text: nil, html: nil, url: nil, clean: nil, xpath: nil, fallback_to_raw: nil, return_analyzed_text: nil, language: nil, limit_text_characters: nil)
func analyze(
    features: Features,
    text: String? = nil,
    html: String? = nil,
    url: String? = nil,
    clean: Bool? = nil,
    xpath: String? = nil,
    fallbackToRaw: Bool? = nil,
    returnAnalyzedText: Bool? = nil,
    language: String? = nil,
    limitTextCharacters: Int? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<AnalysisResults>?, WatsonError?) -> Void)
Request

Instantiate the AnalyzeOptions struct and set the fields to provide parameter values for the Analyze method.

Use the AnalyzeOptions.Builder to create a AnalyzeOptions object that contains the parameter values for the analyze method.

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-11-16.

    Constraints: Value must match regular expression ^\d{4}-\d{2}-\d{2}$

An object containing request parameters. The features object and one of the text, html, or url attributes are required.

The analyze options.

The analyze options.

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze. One of the text, html, or url parameters is required.

  • The HTML file to analyze. One of the text, html, or url parameters is required.

  • The webpage to analyze. One of the text, html, or url parameters is required.

  • Set this to false to disable webpage cleaning. To learn more about webpage cleaning, see the Analyzing webpages documentation.

    Default: true

  • An XPath query to perform on html or url input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.

  • Whether to use raw HTML content if text cleaning fails.

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

  • ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See Language support for more information.

  • Sets the maximum number of characters that are processed by the service.

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze. One of the text, html, or url parameters is required.

  • The HTML file to analyze. One of the text, html, or url parameters is required.

  • The webpage to analyze. One of the text, html, or url parameters is required.

  • Set this to false to disable webpage cleaning. To learn more about webpage cleaning, see the Analyzing webpages documentation.

    Default: true

  • An XPath query to perform on html or url input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.

  • Whether to use raw HTML content if text cleaning fails.

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

  • ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See Language support for more information.

  • Sets the maximum number of characters that are processed by the service.

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze. One of the text, html, or url parameters is required.

  • The HTML file to analyze. One of the text, html, or url parameters is required.

  • The webpage to analyze. One of the text, html, or url parameters is required.

  • Set this to false to disable webpage cleaning. To learn more about webpage cleaning, see the Analyzing webpages documentation.

    Default: true

  • An XPath query to perform on html or url input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.

  • Whether to use raw HTML content if text cleaning fails.

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

  • ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See Language support for more information.

  • Sets the maximum number of characters that are processed by the service.

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze. One of the text, html, or url parameters is required.

  • The HTML file to analyze. One of the text, html, or url parameters is required.

  • The webpage to analyze. One of the text, html, or url parameters is required.

  • Set this to false to disable webpage cleaning. To learn more about webpage cleaning, see the Analyzing webpages documentation.

    Default: true

  • An XPath query to perform on html or url input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.

  • Whether to use raw HTML content if text cleaning fails.

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

  • ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See Language support for more information.

  • Sets the maximum number of characters that are processed by the service.

Response

Results of the analysis, organized by feature