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 and relations in Natural Language Understanding.

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

Maven

<dependency>
  <groupId>com.ibm.watson.developer_cloud</groupId>
  <artifactId>java-sdk</artifactId>
  <version>6.11.0</version>
</dependency>

Gradle

compile 'com.ibm.watson.developer_cloud:java-sdk:6.11.0'

GitHub

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

Installation

npm install --save watson-developer-cloud

GitHub

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

Installation

pip install --upgrade "watson-developer-cloud>=2.5.1"

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

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.

  • Maximum number of categories to return

    Default: 3

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

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Categories feature request

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

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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
    }
  }
}

Example Concepts feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Concepts feature request

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

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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"
      ]
    }
  }
}

Example Emotion feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Emotion feature request

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

var 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'
      ]
    }
  }
};

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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 other entities in the content. See Entity types and subtypes.

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
    }
  }
}

Example Entities feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Entities featurerequest

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

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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
    }
  }
}

Example Keywords feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);
var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '2018-11-16',
  iam_apikey: '{apikey}',
  url: '{url}'
});

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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": {}
  }
}

Example Metadata feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Metadata feature request

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

var parameters = {
  'url': 'www.ibm.com',
  'features': {
    'metadata': {}
  }
};

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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."
}

Example Relations feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Relations feature request

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

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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"
}

Example Relations feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Relations feature request

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

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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"
      ]
    }
  }
}

Example Sentiment feature request

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

NaturalLanguageUnderstanding service = 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 = service
  .analyze(parameters)
  .execute();
System.out.println(response);

Example Sentiment feature request

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

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

natural_language_understanding.analyze(parameters, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});

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)

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"
}

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 the apikey, 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 on the Dashboard.

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}" "{url}/{method}"

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

curl -u "{username}:{password}" "{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}.

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1');

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

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

var  = require('watson-developer-cloud/natural-language-understanding/v1');

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

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

from watson_developer_cloud import NaturalLanguageUnderstandingV1

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

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

from watson_developer_cloud 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}",
})

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 on the Dashboard.

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.

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

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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1');

var 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")

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-03-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 a WatsonApiException 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 a WatsonApiException 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.

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,
  function (err, response) {
    // The error will be the first argument of the callback
    if (err.code == 404) {

      // Handle Not Found (404) error
    } else if (err.code == 413) {

      // Handle Request Too Large (413) error
    } else {
      console.log('Unexpected error: ', err.code);
      console.log('error:', err);
    }
  });

Example error handling

from watson_developer_cloud import WatsonApiException
try:
    # Invoke a Natural Language Understanding method
except WatsonApiException 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 WatsonApiException => 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)
}

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 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.

Example header parameter in a request

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

Example header parameter in a request

naturalLanguageUnderstanding.methodName({
  parameters,
  headers: {
    'Custom-Header': '{header_value}'
  }
},
  function (err, response) {
    if (err) {
      console.log('error:', err);
    } else {
      console.log(response);
    }
  }
);

Example header parameter in a request

response = naturalLanguageUnderstanding.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",
    },
  },
)

Response details

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

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, specify the headers attribute on the third parameter (response) that is passed to the callback function.

Example request to access response headers

naturalLanguageUnderstanding.methodName({
  parameters
},
  function (err, result, response) {
    if (err) {
      console.log('error:', err);
    } else {
      console.log(response.headers);
    }
  }
);

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

naturalLanguageUnderstanding.set_detailed_response(True)
response = naturalLanguageUnderstanding.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 result 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/watson-developer-cloud/go-sdk/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 ")

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.

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

var  = require('watson-developer-cloud/');

var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  iam_apikey: '{apikey}',
  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)

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/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: matches 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]

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

  • 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.

  • Maximum number of categories to return.

    Constraints: value ≤ 10

    Default: 3

  • 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

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

Example requests
Response

Analysis results for each requested 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.

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

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment.

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

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment.

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

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment.

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

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment.

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

  • Categories
  • Concepts
  • Emotion
  • Entities
  • Keywords
  • Metadata
  • Relations
  • Semantic roles
  • Sentiment.
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)
Request

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: matches 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.

parameters

  • 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

  • Analysis features and options.

  • 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

  • Analysis features and options.

  • 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

  • Analysis features and options.

  • 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.

Example requests
Response

Analysis results for each requested feature

Results of the analysis, organized by feature.

Results of the analysis, organized by feature.

Results of the analysis, organized by feature.