Curl Node Java Python

Natural Language Understanding

API Reference
The IBM Watson Natural Language Understanding API Reference page

Introduction

Natural Language Understanding uses natural language processing to analyze semantic features of any text. Provide plain text, HTML, or a public URL, and Natural Language Understanding returns results for the features you specify. The service cleans HTML before analysis by default, which removes most advertisements and other unwanted content.

You can create custom models with Watson Knowledge Studio that can be used to detect custom entities and relations in Natural Language Understanding.

API Endpoint

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

Important: If you have IBM® Cloud Dedicated, this might not be your endpoint. Check your endpoint URL on the Service credentials page for your instance of the Natural Language Understanding service.

GitHub

https://github.com/watson-developer-cloud/node-sdk

npm

npm install watson-developer-cloud

GitHub

https://github.com/watson-developer-cloud/java-sdk

Maven


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

Gradle

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

GitHub

https://github.com/watson-developer-cloud/python-sdk

pip


pip install --upgrade watson-developer-cloud
        

Synchronous and asynchronous requests

The Java SDK supports both synchronous (blocking) and asynchronous (non-blocking) execution of all methods. All methods are called with the Java 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.

Example synchronous request


  ServiceCall call = service.analyze(parameters);
  AnalysisResults response = call.execute();
  

Example asynchronous request


  ServiceCall call = service.analyze(parameters);
  call.enqueue(new ServiceCallback<AnalysisResults>() {
    @Override public void onResponse(AnalysisResults response) {
      . . .
    }
    @Override public void onFailure(Exception e) {
      . . .
    }
  });
  

API Explorer

To interact with this REST API, use the Natural Language Understanding API Explorer. Use the Explorer to test your calls to the API and to view live responses from the server.

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. If you pass in 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.
  • With 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.

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. If you pass in 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.
  • With 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.

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. If you pass in 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.
  • With 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.

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

IAM authentication. Replace {iam_api_key} with your service credentials.


curl -u "apikey:{iam_api_key}" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models?version=2018-03-16"
    

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

var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  iam_apikey: '{iam_api_key}'
})
    

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding("{version}",options);
    

from watson_developer_cloud import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    iam_api_key='{iam_api_key}'
)
    

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


curl -u "{username}":"{password}" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models?version=2018-03-16"
    

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

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "{version}",
  "{username}",
  "{password}"
);
    

from watson_developer_cloud import NaturalLanguageUnderstandingV1

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

Service endpoint URL

If your Natural Language Understanding service URL differs from the default, you must set it manually. For example, a Natural Language Understanding service hosted in Frankfurt may use the service URL https://gateway-fra.watsonplatform.net/natural-language-understanding/api. To find the endpoint URL for your service instance, check the service credentials page.

You can set the correct URL for your service by calling the setEndPoint() method of the service instance.

You can set the correct URL for your service using the url parameter when you create the service instance.

You can set the correct URL for your service using the url parameter when you create the service instance or by calling the set_url() method of the service instance.

Default API endpoint

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

Set the service endpoint URL


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

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

var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
    version: '{version}',
    username: '{username}',
    password: '{password}',
    url: 'https://gateway-fra.watsonplatform.net/natural-language-understanding/api'
});
          

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    username='{username}',
    password='{password}',
    url='https://gateway-fra.watsonplatform.net/natural-language-understanding/api'
)
          

or


from watson_developer_cloud import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    username='{username}',
    password='{password}'
)
natural_language_understanding.set_url('https://gateway-fra.watsonplatform.net/natural-language-understanding/api')
          

Versioning

API requests require a version parameter that takes a date in the format version=YYYY-MM-DD. Send the version parameter with every API request. When we change the API in a backwards-incompatible way, we release a new minor version. To take advantage of the changes in a new version, change the value of the version parameter to the new date. If you're not ready to update to that version, don’t change your version date.

The current version is 2018-03-16.

Analyze

POST /analyze

Analyze features of natural language content.

POST /v1/analyze
ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

Name Description
Content-Type headerstring

Valid types are application/json, text/plain, and text/html.

parameters bodyobject JSON object containing request parameters.
version querystring 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-03-16.
Parameters object
Name Description
text, html, or url string One of these is required. The "text" attribute accepts plain text. The "html" attribute accepts formatted HTML source code. The "url" attribute accepts URLs to public webpages - "url" is not supported in IBM Cloud Dedicated instances.
features stringobject

Specify the features to analyze in the text, and the options to enable for each feature. For example:

"emotions": {} enables emotion analysis with default options

"entities": {"sentiment":true} analyzes entities, and enables the sentiment analysis option for detected entities.

At least one feature is required, and you can include as many as you like. Adding features might incur additional billable API events. These are the available features:

language string ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are ar (Arabic), en (English), fr (French), de (German), it (Italian), pt (Portuguese), ru (Russian), es (Spanish), and sv (Swedish). For more information about which features are supported in each language, see this table.
xpath string An XPath query to perform on url or html input. Results of the query will be appended to the cleaned text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.
clean boolean Set to false to disable text cleaning. By default, the service cleans input to remove generally unwanted content, such as advertisements.
fallback_to_raw boolean Whether to use raw HTML content if text cleaning fails. This defaults to true.
return_analyzed_text string Set this to true to show the analyzed text in the response.
limit_text_characters integer Sets the max number of characters to be processed by the service.
Name Description
parameters Object Java AnalyzeOptions object containing request parameters
AnalyzeOptions object
Name Description
text, html, or url String One of these is required. The "text" attribute accepts plain text. The "html" attribute accepts formatted HTML source code. The "url" attribute accepts URLs to public webpages - "url" is not supported in IBM Cloud Dedicated instances.
features Object

Java Features object that specifies which features to include in the analysis, and which options to enable for each feature.

At least one feature is required, and you can include as many as you like. View each feature's section in the reference for options and language support. Adding features and options may incur additional billable API events. Available features:

language String ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are ar(Arabic), en(English), fr(French), de(German), it(Italian), pt(Portuguese), ru(Russian), es(Spanish), and sv(Swedish). For more information about which features are supported in each language, see this table.
xpath string An XPath query to perform on url or html input. Results of the query will be appended to the cleaned text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.
clean Boolean Set to false to disable text cleaning. By default, the service cleans input to remove generally unwanted content, such as advertisements.
fallbackToRaw Boolean Whether to use raw HTML content if text cleaning fails. This defaults to true.
returnAnalyzedText String Set this to true to show the analyzed text in the response.
Features object
Name Description
categories Object Java CategoriesOptions object
concepts Object Java ConceptsOptions
emotion Object Java EmotionOptions object
entities Object Java EntitiesOptions object
keywords Object Java KeywordsOptions object
metadata Object Java MetadataOptions object
relations Object Java RelationsOptions object
semanticRoles Object Java SemanticRolesOptions object
sentiment Object Java SentimentOptions object
Name Description
version string 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-03-16.
text, html, or url string One of these is required. The "text" attribute accepts plain text. The "html" attribute accepts formatted HTML source code. The "url" attribute accepts URLs to public webpages - "url" is not supported in IBM Cloud Dedicated instances.
features Features

Import the options classes from the Python SDK and use them to create valid arguments for the Features constructor. For example:

Features(emotion=EmotionOptions()) enables emotion analysis with default options.

Features(entities=EntitiesOptions (sentiment=True)) enables the entities feature and the sentiment analysis option for entities.

At least one feature is required, and you can include as many as you like. Adding features might incur additional billable API events. These are the available features:

language string ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are ar (Arabic), en (English), fr (French), de (German), it (Italian), pt (Portuguese), ru (Russian), es (Spanish), and sv (Swedish). For more information about which features are supported in each language, see this table.
xpath string An XPath query to perform on url or html input. Results of the query will be appended to the cleaned text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.
clean boolean Set to False to disable text cleaning. By default, the service cleans input to remove generally unwanted content, such as advertisements.
fallback_to_raw boolean Whether to use raw HTML content if text cleaning fails. This defaults to true.
return_analyzed_text string Set this to True to show the analyzed text in the response.

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


{
  "text": "IBM is an American multinational technology company headquartered in Armonk, New York, United States, with operations in over 170 countries.",
  "features": {
    "entities": {
      "emotion": true,
      "sentiment": true,
      "limit": 2
    },
    "keywords": {
      "emotion": true,
      "sentiment": true,
      "limit": 2
    }
  }
}
      
      

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

var parameters = {
  'text': 'IBM is an American multinational technology company headquartered in Armonk, New York, United States, with operations in over 170 countries.',
  'features': {
    'entities': {
      'emotion': true,
      'sentiment': true,
      'limit': 2
    },
    'keywords': {
      'emotion': true,
      'sentiment': true,
      'limit': 2
    }
  }
}

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

String text = "IBM is an American multinational technology " +
  "company headquartered in Armonk, New York, " +
  "United States, with operations in over 170 countries.";

EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
  .emotion(true)
  .sentiment(true)
  .limit(2)
  .build();

KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
  .emotion(true)
  .sentiment(true)
  .limit(2)
  .build();

Features features = new Features.Builder()
  .entities(entitiesOptions)
  .keywords(keywordsOptions)
  .build();

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

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

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

response = natural_language_understanding.analyze(
  text='IBM is an American multinational technology company '
       'headquartered in Armonk, New York, United States, '
       'with operations in over 170 countries.',
  features=Features(
    entities=EntitiesOptions(
      emotion=True,
      sentiment=True,
      limit=2),
    keywords=KeywordsOptions(
      emotion=True,
      sentiment=True,
      limit=2)))

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

Response

The following table describes the JSON representation of the AnalysisResults Java object.

Name Description
language string Language used for the analysis
analyzed_text string The analyzed text (set return_analyzed_text to true to see this)
retrieved_url string URL used to fetch HTML content for analysis
usage object Usage information for the request
  • text_units: Number of 10,000-character units processed
  • text_characters: Number of characters processed
  • features: Integer indicating number of features used, such as entities, sentiment, etc.
concepts object Concepts results
categories object Categories results
emotion object Emotion results
entities object Entities results
keywords object Keywords results
metadata object Metadata results
relations object Relations results
semantic_roles object Semantic Roles results
sentiment object Sentiment results

Example response


{
  "usage": {
    "text_units": 1,
    "text_characters": 140,
    "features": 2
  },
  "language": "en",
  "keywords": [
    {
      "text": "American multinational technology",
      "sentiment": {
        "score": 0.0
      },
      "relevance": 0.993518,
      "emotion": {
        "sadness": 0.085259,
        "joy": 0.026169,
        "fear": 0.02454,
        "disgust": 0.088711,
        "anger": 0.033078
      }
    },
    {
      "text": "New York",
      "sentiment": {
        "score": 0.0
      },
      "relevance": 0.613816,
      "emotion": {
        "sadness": 0.166741,
        "joy": 0.228903,
        "fear": 0.057987,
        "disgust": 0.050965,
        "anger": 0.054653
      }
    }
  ],
  "entities": [
    {
      "type": "Company",
      "text": "IBM",
      "sentiment": {
        "score": 0.0
      },
      "relevance": 0.33,
      "emotion": {
        "sadness": 0.085259,
        "joy": 0.026169,
        "fear": 0.02454,
        "disgust": 0.088711,
        "anger": 0.033078
      },
      "disambiguation": {
        "subtype": [
          "SoftwareLicense",
          "OperatingSystemDeveloper",
          "ProcessorManufacturer",
          "SoftwareDeveloper",
          "CompanyFounder",
          "ProgrammingLanguageDesigner",
          "ProgrammingLanguageDeveloper"
        ],
        "name": "IBM",
        "dbpedia_resource": "http://dbpedia.org/resource/IBM"
      },
      "count": 1
    }
  ]
}
        

GET /analyze

Analyze features of natural language content.

The SDKs use the POST method for the /analyze endpoint. See the POST /analyze method.

GET /v1/analyze

Request

Parameter Description
text, html, or url querystring One of these is required. The "text" attribute accepts plain text. The "html" attribute accepts formatted HTML source code. The "url" attribute accepts URLs to public webpages - "url" is not supported in IBM Cloud Dedicated instances.
features queryarray[string] Comma separated list of features to analyze:
  • concepts
  • categories
  • emotion
  • entities
  • keywords
  • metadata
  • relations
  • semantic_roles
  • sentiment
version querystring 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-03-16.
language querystring ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are ar(Arabic), fr(French), de(German), it(Italian), pt(Portuguese), ru(Russian), es(Spanish), and sv(Swedish). For more information about which features are supported in each language, see this table.
xpath string An XPath query to perform on url or html input. Results of the query will be appended to the cleaned text before it is analyzed. To analyze only the results of the XPath query, set the clean parameter to false.
return_analyzed_text queryboolean Set this to true to show the analyzed text in the response
clean queryboolean Set to false to disable text cleaning. By default, the service cleans input to remove most irrelevant content, such as advertisements.
fallback_to_raw queryboolean Whether to use raw HTML content if text cleaning fails. This defaults to true.
limit_text_characters integer Sets the max number of characters to be processed by the service.
concepts.limit queryinteger Maximum number of concepts to return.
emotion.document queryboolean Set this to false to hide document-level emotion results.
emotion.targets queryarray[string] Target strings, separated by commas. Emotion results are returned for each target string found in the document.
entities.limit queryinteger Maximum number of entities to return.
entities.mentions queryboolean Set this to true to return locations of entity mentions.
entities.model querystring Enter a custom model ID to override the standard entity detection model.
entities.emotion queryboolean Set this to true to return emotion information for detected entities.
entities.sentiment queryboolean Set this to true to return sentiment information for detected entities.
keywords.limit queryinteger Maximum number of keywords to return.
keywords.emotion queryboolean Set this to true to return emotion information for detected keywords.
keywords.sentiment queryboolean Set this to true to return sentiment information for detected keywords.
relations.model querystring Enter a custom model ID to override the default `en-news` relations model.
semantic_roles.limit queryinteger Maximum number of semantic_roles results to return.
semantic_roles.entities queryboolean Set this to true to return entity information for subjects and objects.
semantic_roles.keywords queryboolean Set this to true to return keyword information for subjects and objects.
sentiment.document queryboolean Set this to false to disable document-level sentiment analysis.
sentiment.targets queryarray[string] List of target strings separated by commas. Sentiment analysis is performed on each target found in the text.

Example request


curl -G -u "{username}":"{password}" -d "version=2018-03-16" -d "url=www.ibm.com" -d "features=keywords,entities" -d "entities.emotion=true" -d "entities.sentiment=true" -d "keywords.emotion=true" -d "keywords.sentiment=true" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze"

Response

Name Description
language string Language used for the analysis
analyzed_text string Full list of analyzed text (set return_analyzed_text to true to see this)
retrieved_url string URL used to fetch HTML content for analysis
usage object Usage information for the request
  • text_units: Number of 10,000-character units processed
  • text_characters: Number of characters processed
  • features: Integer indicating number of features used, such as entities, sentiment, etc.
concepts object Concepts results
categories object Categories results
emotion object Emotion results
entities object Entities results
keywords object Keywords results
metadata object Metadata results
relations object Relations results
semantic_roles object Semantic Roles results
sentiment object Sentiment results

Example response


{
  "usage": {
    "text_units": 1,
    "text_characters": 1536,
    "features": 2
  },
  "entities": [
    {
      "type": "Company",
      "relevance": 0.89792,
      "count": 12,
      "name": "IBM",
      "disambiguation": {
        "name": "IBM",
        "dbpedia_resource": "http://dbpedia.org/resource/IBM",
        "subtype": [
          "SoftwareLicense",
          "OperatingSystemDeveloper",
          "ProcessorManufacturer",
          "SoftwareDeveloper",
          "CompanyFounder",
          "ProgrammingLanguageDesigner",
          "ProgrammingLanguageDeveloper"
        ]
      },
      "emotion": {
        "sadness": 0.271362,
        "joy": 0.618694,
        "fear": 0.033186,
        "disgust": 0.056113,
        "anger": 0.099437
      }
    }
  ],
  "keywords": [
    {
      "emotion": {
        "sadness": 0.174379,
        "joy": 0.66067,
        "fear": 0.051475,
        "disgust": 0.114401,
        "anger": 0.044105
      },
      "relevance": "0.900808",
      "sentiment": {
        "score": 0.419889
      },
      "text": "free trial"
    }
  ],
  "language": "en",
  "retrieved_url": "https://www.ibm.com/us-en/"
}
        

Categories

Categorize your content into a 5-level taxonomy. The top three categories will be returned.

View the complete list of categories here.

Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available when you enable "categories" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the CategoriesOptions Java object when you enable "categories" as a feature. See POST /analyze for the generic request parameters.

These are the parameters available for the CategoriesOptions class when you enable "categories" as a feature. See POST /analyze for the generic request parameters.

No options

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"
      

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

String url = "www.ibm.com";

CategoriesOptions categories = new CategoriesOptions();

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);
      

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Categories results
Name Description
score number Categorization score ranging from 0 to 1. A 0 means it's not confident in the categorization, and a 1 means it's highly confident.
label string Category label. Forward slashes separate category hierarchy levels.

Example 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

Recognize high-level concepts that are related to your text. For example, analysis of a research paper about deep learning would likely return the concept "Artificial Intelligence", even if that term is not explicitly mentioned in the paper.

Supported languages: English, French, German, Japanese, Korean, Spanish

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "concepts" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the ConceptsOptions Java object when you enable "concepts" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the ConceptsOptions class when you enable "concepts" as a feature. See POST /analyze for the generic request parameters.

Concepts options
Name Description
limit integer The maximum number of concepts to return.

Default: 8, Maximum you can return: 50.

Concepts options
Name Description
limit Integer The maximum number of concepts to return.

Default: 8, Maximum you can return: 50

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

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);
      

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Concepts results
Name Description
text string Name of the concept
relevance number Relevance score for the concept ranging from 0 to 1. A 0 means it's not relevant, and a 1 means it's highly relevant.
dbpedia_resource string Link to the concept's associated DBpedia resource

Example 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

Detect emotion conveyed by the entire body of text, or by the context around target phrases specified in the targets parameter.

You can analyze emotion for detected entities and keywords by enabling the emotion option for those features.

Supported languages: English

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "emotion" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the EmotionOptions Java object when you enable "emotion" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the EmotionOptions class when you enable "emotion" as a feature. See POST /analyze for the generic request parameters.

Emotion options
Name Description
targets array[string] The service analyzes emotion for each target string found in the text
document boolean Set this to false to hide document-level emotion results.
Emotion options
Name Description
targets List<String> The service analyzes emotion for each target string found in the text
document Boolean Set this to false to hide document-level emotion results.

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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'])))

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Emotion results
Name Description
document object Object containing emotion analysis results for the entire document
targets array[object] Array of objects containing emotion results for the targets
emotion array[object] Emotion scores ranging from 0 to 1 for sadness, joy, fear, disgust, and anger. A 0 means the text doesn't convey the emotion, and a 1 means the text definitly carries the emotion.

Example 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

Identify people, cities, organizations, and many other types of entities in your text.

View the complete list of entity types and subtypes here.

Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish

Arabic, Chinese, and Dutch custom models are also supported.

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "entities" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the EntitiesOptions Java object when you enable "entities" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the EntitiesOptions class when you enable "entities" as a feature. See POST /analyze for the generic request parameters.

Entities options
Name Description
emotion boolean Set this to true to enable emotion analysis for detected entities.
sentiment boolean Set this to true to enable targeted sentiment analysis for detected entities.

Note: This option is not supported for Arabic, Chinese, Dutch, Japanese, or Swedish entities.

mentions boolean Set this to true to return locations for entity mentions.
model string Enter a custom model ID to override the standard entity detection model. Watson Knowledge Studio custom models do not return entity relevance scores.

You can also use the public models that detect relations to detect entities. See the Entity types unique to relations documentation for the list of model IDs.
limit integer Maximum number of entities to return. Default: 50, Maximum: 250.
Entities options
Name Description
emotion Boolean Set this to true to enable emotion analysis for detected entities
sentiment Boolean Set this to true to enable targeted sentiment analysis for detected entities

Note: This option is not supported for Arabic, Chinese, Dutch, Japanese, or Swedish entities.

mentions Boolean Set this to true to return locations for entity mentions.
model String Enter a custom model ID to override the standard entity detection model. Watson Knowledge Studio custom models do not return entity relevance scores.

You can also use the public models that detect relations to detect entities. See the Entity types unique to relations documentation for the list of model IDs.
limit Integer Maximum number of entities to return. Default: 50, Maximum: 250.

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Entities results
Name Description
type string Entity type
text string Entity text
mentions array[object] Array of entity mention objects that contain the following:
  • The mention text
  • A location array of integers that indicate the beginning and ending character offsets of the mention in the analyzed text
(Set the entity mentions option to true to see these results)
sentiment object Sentiment analysis results for the entity (set the entity sentiment option to true to see these results)
emotion object Emotion analysis results for the entity (set the entity emotion option to true to see these results)
relevance string Relevance score ranging from 0 to 1. A 0 means it's not relevant, and a 1 means it's highly relevant.
disambiguation object Disambiguation information for the entity. Contains entity subType information, a common entity name, and a dbpedia_resource link if applicable.
count integer Number of times the entity is mentioned in the text

Example 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

Identify the important keywords in your content.

Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "keywords" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the KeywordsOptions Java object when you enable "keywords" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the KeywordsOptions class when you enable "keywords" as a feature. See POST /analyze for the generic request parameters.

Keywords options
Name Description
emotion boolean Set this to true to enable emotion analysis for detected keywords.
sentiment boolean Set this to true to enable targeted sentiment analysis for detected keywords.

Note: This option is available only for English, German, and Korean keywords.

limit integer Maximum number of keywords to return. Default: 50, Maximum: 250.
Keywords options
Name Description
emotion Boolean Set this to true to enable emotion analysis for detected keywords.
sentiment Boolean Set this to true to enable targeted sentiment analysis for detected keywords.

Note: This option is available only for English, German, and Korean keywords.

limit Integer Maximum number of keywords to return. Default: 50, Maximum: 250.

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Keywords results
Name Description
text string Keyword text
relevance number Keyword relevance score. A 0 means it's not relevant, and a 1 means it's highly relevant.
sentiment object Sentiment score for the concept ranging from -1 to 1. Negative scores indicate negative sentiment, and positive scores indicate positive sentiment.
emotion object Emotion analysis results, containing scores for sadness, joy, fear, disgust, and anger.

Example 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

Get document metadata, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. (HTML or webpage input only)

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "metadata" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the MetadataOptions Java object when you enable "metadata" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the MetadataOptions class when you enable "metadata" as a feature. See POST /analyze for the generic request parameters.

No options

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Metadata results
Name Description
authors array[object] Array of objects containing author names
feeds array[object] Array of objects that each contain one link to an RSS or ATOM feed
image string URL of a prominent image on the webpage.
publication_date string Date time information in YYYY-MM-DDThh:mm:ss.sTZD format
title string Page title

Example 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

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

View the complete list of relation types here.

Supported languages: Arabic, English, German, Japanese, Korean, Spanish

Chinese, Dutch, French, Italian, and Portuguese custom models are also supported.

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "relations" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the RelationsOptions Java object when you enable "relations" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the RelationsOptions class when you enable "relations" as a feature. See POST /analyze for the generic request parameters.

Relations options
Name Description
model string Specify the ID of a deployed Watson Knowledge Studio custom model to override the default model
Relations options
Name Description
model String Specify the ID of a deployed Watson Knowledge Studio custom model to override the default model

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}");

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Relations results
Name Description
type string Type of the relation
sentence string Selection of text that contains the relation
score string Relation confidence score ranging from 0 to 1. A 0 means it's not confident, and a 1 means it's highly confident.
arguments array[object] The arguments of the relation. Each argument object contains:
  • The argument text
  • Location array indicating beginning and ending character offsets of the argument in the analyzed text
  • Entities array containing objects with entity information for the argument

Example 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

Parse sentences into subject, action, and object form.

Supported languages: English, German, Japanese, Korean, Spanish

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "semantic_roles" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the SemanticRolesOptions Java object when you enable "semanticRoles" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the SemanticRolesOptions class when you enable "semantic_roles" as a feature. See POST /analyze for the generic request parameters.

Semantic Roles options
Name Description
entities boolean Set this to true to return entity information for subjects and objects
keywords boolean Set this to true to return keyword information for subjects and objects
limit integer Maximum number of semantic role results to return. Default: 50
Semantic Roles options
Name Description
entities Boolean Set this to true to return entity information for subjects and objects
keywords Boolean Set this to true to return keyword information for subjects and objects
limit Integer Maximum number of semantic role results to return. Default: 50

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}");

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version=2018-03-16)

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

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

Response

For generic analysis response attributes, see the POST /analyze response section.

Semantic Roles results
Name Description
sentence string Sentence containing the semantic role information
subject object The subject of the parsed sentence. Contains entity and keyword information if applicable.
action object The action that is taken by the subject. Contains the text of the action, a common normalized name for the action, and the verb tense.
object object The analyzed object. Contains entity and keyword information if applicable.

Example 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

Analyze the general sentiment of your content or analyze the sentiment toward specific target phrases found in the text.

You can analyze sentiment for entities and keywords by enabling the sentiment option for those features.

Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish

ServiceCall<AnalysisResults> analyze(AnalyzeOptions parameters)

Request

These are the options available if you enable "sentiment" as a feature in your request. See POST /analyze for the generic request parameters.

These are the options available for the SentimentOptions Java object when you enable "sentiment" as a feature. See POST /analyze for the generic request parameters.

These are the options available for the SentimentOptions class when you enable "sentiment" as a feature. See POST /analyze for the generic request parameters.

Sentiment options
Name Description
targets array[string] The service analyzes sentiment for each target string found in the text. Returns up to 20 targets.
document boolean Set this to false to hide document-level sentiment results.
Sentiment options
Name Description
targets List<String> The service analyzes sentiment for each target string found in the text
document Boolean Set this to false to hide document-level sentiment results.

Example request


curl -X POST -H "Content-Type: application/json" -u "{username}":"{password}" -d @parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16"

parameters.json


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

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}");

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);

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

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

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


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

Response

For generic analysis response attributes, see the POST /analyze response section.

Sentiment results
Name Description
document object Document-level sentiment analysis results
targets array[object] Array of target analysis results. Each object contains the text of the target, sentiment score, and a label.
score number Sentiment score ranging from -1 (negative sentiment) to 1 (positive sentiment).
label string Indicates whether the sentiment is positive, neutral, or negative

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

Manage models

The following methods manage your deployed custom model from Watson Knowledge Studio.

List models

List available custom models.

GET /v1/models
ServiceCall<ListModelsResults> listModels()

Request

Name Description
version querystring 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-03-16.

No arguments.

Example request


curl -G -u "{username}":"{password}" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models?version=2018-03-16"
      

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}");

ListModelsResults models = service
  .listModels()
  .execute();
System.out.println(models);
      

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

response = natural_language_understanding.list_models()

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

Response

Name Description
models array[object] Array of objects containing details about your available models

Example response


{
  "models": [
    {
      "status": "available",
      "model_id": "MODEL_ID",
      "language": "en",
      "description": "My custom model deployed from Watson Knowledge Studio"
    }
  ]
}
    

Delete model

Delete a custom model.

DELETE /v1/models/{model_id}
ServiceCall<Void> deleteModel(String modelId)

Request

Name Description
model_id pathstring ID of the model to delete.
version querystring 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-03-16.
Name Description
modelId String ID of the model to delete.
Name Description
model_id String ID of the model to delete.

Example request


curl -X DELETE -u "{username}":"{password}" "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models/{model_id}?version=2018-03-16"
      

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  'username': '{username}',
  'password': '{password}',
  'version': '2018-03-16'
});

var parameters = {
  'model_id': '{model_id}'
};

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}");

DeleteModelOptions options = new DeleteModelOptions.Builder().modelId("model_id").build();
service.deleteModel(options).execute();
      

import json
from watson_developer_cloud import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16')

response = natural_language_understanding.delete_model(model_id='my_model_id')

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

Response

Name Description
deleted pathstring model_id of the successfully deleted model

Example response


{
  "deleted": "{model_id}"
}
      

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 from accessing your data for general service improvements, set the X-Watson-Learning-Opt-Out header parameter to true for all requests. (Any value other than false or 0 disables request logging for that call.) You must set the header on each request that you do not want IBM to access for general service improvements. set the X-Watson-Learning-Opt-Out header parameter to true when you create the service instance. (Any value other than false or 0 disables request logging for that call.) You must set the header when you create the service for any any call that you do not want IBM to access for general service improvements. set the x-watson-learning-opt-out header parameter to true when you create the service instance. (Any value other than false or 0 disables request logging for that call.) You must set the header when you create the service for any any call that you do not want IBM to access for general service improvements. For more information, see Controlling request logging for Watson services.


curl -u "{username}":"{password}"
--header "X-Watson-Learning-Opt-Out: true"
"https://gateway.watsonplatform.net/natural-language-understanding/api/v1/{method}"
      

var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1');
var natural_language_understanding = new NaturalLanguageUnderstandingV1({
  username: '{username}',
  password: '{password}',
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});
      

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

NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
  "2018-03-16",
  "{username}",
  "{password}"
);
service.setDefaultHeaders(headers);

natural_language_understanding = NaturalLanguageUnderstandingV1(
  username='username',
  password='password',
  version='2018-03-16',
  x_watson_learning_opt_out=True)

Error handling

The Natural Language Understanding service uses standard HTTP response codes to display whether a method completed successfully. A 200 response always indicates success. A 400 type response is usually an error with the call, and a 500 type response usually indicates an internal system error.

Java Exceptions

Common Java exceptions are listed under the "Direct known subclasses" section of the ServiceResponseException page in the Javadoc.

Name Description
Exception string The name of the exception that was raised.
status integer The HTTP status code.
error string A description of the error.

Error format

Name Description
code Error code
error Error description

Example error


{
  "code": 500,
  "error": "Internal server error"
}
        

Example error


SEVERE: POST https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16, status: 400, error: cannot locate keyphrase
Exception in thread "main" com.ibm.watson.developer_cloud.service.exception.BadRequestException: cannot locate keyphrase
        

Example error


watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: cannot locate keyphrase, Code: 400