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.
IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From June 3, 2023 onward, you will no longer be able to use the Custom Sentiment feature.
To ensure we continue providing our clients with robust and powerful text classification capabilities, IBM recently announced the general availability of a new single-label text classification capability. This new feature includes extended language support and training data customizations suited for building a custom sentiment classifier.
If you would like more information or further guidance, please contact IBM Cloud Support.
This documentation describes Java SDK major version 9. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes Node SDK major version 6. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes Python SDK major version 5. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes Ruby SDK major version 2. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes .NET Standard SDK major version 5. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes Go SDK major version 2. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes Swift SDK major version 4. For more information about how to update your code from the previous version, see the migration guide.
This documentation describes Unity SDK major version 5. For more information about how to update your code from the previous version, see the migration guide.
The IBM Watson Unity SDK has the following requirements.
- The SDK requires Unity version 2018.2 or later to support Transport Layer Security (TLS) 1.2.
- Set the project settings for both the Scripting Runtime Version and the Api Compatibility Level to
.NET 4.x Equivalent
. - For more information, see TLS 1.0 support.
- Set the project settings for both the Scripting Runtime Version and the Api Compatibility Level to
- The SDK doesn't support the WebGL projects. Change your build settings to any platform except
WebGL
.
For more information about how to install and configure the SDK and SDK Core, see https://github.com/watson-developer-cloud/unity-sdk.
The code examples on this tab use the client library that is provided for Java.
Maven
<dependency>
<groupId>com.ibm.watson</groupId>
<artifactId>ibm-watson</artifactId>
<version>10.1.0</version>
</dependency>
Gradle
compile 'com.ibm.watson:ibm-watson:10.1.0'
GitHub
The code examples on this tab use the client library that is provided for Node.js.
Installation
npm install ibm-watson@^7.1.2
GitHub
The code examples on this tab use the client library that is provided for Python.
Installation
pip install --upgrade "ibm-watson>=6.1.0"
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/v2@v3.0.0
GitHub
The code examples on this tab use the client library that is provided for Swift.
Cocoapods
pod 'IBMWatsonNaturalLanguageUnderstandingV1', '~> 5.0.0'
Carthage
github "watson-developer-cloud/swift-sdk" ~> 5.0.0
Swift Package Manager
.package(url: "https://github.com/watson-developer-cloud/swift-sdk", from: "5.0.0")
GitHub
The code examples on this tab use the client library that is provided for .NET Standard.
Package Manager
Install-Package IBM.Watson.NaturalLanguageUnderstanding.v1 -Version 6.1.0
.NET CLI
dotnet add package IBM.Watson.NaturalLanguageUnderstanding.v1 --version 6.1.0
PackageReference
<PackageReference Include="IBM.Watson.NaturalLanguageUnderstanding.v1" Version="6.1.0" />
GitHub
The code examples on this tab use the client library that is provided for Unity.
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 hierarchical taxonomy of the content. For example, a news website may return categories like /international news
or /arts and entertainment
. The top three categories are returned by default.
Categories request options
For more information, see the request body for the Analyze text method.
-
Set this option to
true
to return explanations for each categorization. This option is available only for English categories.Default:
false
-
(Beta) Enter a custom model ID to override the standard categories model for all categories analysis operations in the request. This option is available only for English categories.
-
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=2022-04-07"
Example parameters
{
"url": "www.ibm.com",
"features": {
"categories": {
"limit": 3
}
}
}
Example Categories feature request
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "www.ibm.com"
limit := int64(3)
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Categories: &naturallanguageunderstandingv1.CategoriesOptions{
Limit: &limit,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Categories feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "www.ibm.com";
CategoriesOptions categories= new CategoriesOptions.Builder()
.limit(3)
.build();
Features features = new Features.Builder()
.categories(categories)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Categories feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'www.ibm.com',
'features': {
'categories': {
'limit': 3
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Categories feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, CategoriesOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "www.ibm.com",
features: {categories: {limit:3}}
)
puts JSON.pretty_generate(response.result)
Example Categories feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let categories = CategoriesOptions(limit: 3)
let features = Features(categories: categories)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Categories feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
url: "www.ibm.com",
features: new Features()
{
Categories = new CategoriesOptions()
{
Limit = 3
}
}
);
Console.WriteLine(result.Response);
Example Categories feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Categories = new CategoriesOptions()
{
Limit = 3
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "www.ibm.com",
features: features
);
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",
"language": "en",
"categories": [
{
"score": 0.997152,
"label": "/technology & computing/computing/internet/cloud computing"
},
{
"score": 0.984064,
"label": "/technology & computing/computing/computer software and applications"
},
{
"score": 0.962747,
"label": "/technology & computing/computing/data storage and warehousing"
}
]
}
Classifications
Classifies input using custom multi-label text classifier. For example, a custom weather classifier may return classifications such as "temperature" or "condition".
Classifications request options
For more information, see the request body for the Analyze text method. Note: This feature considers only the first 2000 codepoints of text.
-
Model ID of the classifications model to be used.
Note: You can analyze tone for text by using a language-specific model ID; see Tone analytics (Classifications) for more information.
Classifications response
Example Classifications feature request
curl -X POST -H "Content-Type: application/json" -u "apikey:{apikey}" -d @parameters.json "{url}/v1/analyze?version=2022-04-07"
Example parameters
{
"url": "www.ibm.com",
"features": {
"classifications": {
"model": "your-model-id"
}
}
}
Example Classifications feature request
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "www.ibm.com"
model := "your-model-id"
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Classifications: &naturallanguageunderstandingv1.ClassificationsOptions{
Model: &model,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Classifications feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "www.ibm.com";
ClassificationsOptions classifications = new ClassificationsOptions.Builder()
.model(your-model-id)
.build();
Features features = new Features.Builder()
.classifications(classifications)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Classifications feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'www.ibm.com',
'features': {
'classifications': {
'model': 'your-model-id'
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Classifications feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, ClassificationsOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_url('{url}')
response = natural_language_understanding.analyze(
url='www.ibm.com',
features=Features(classifications=ClassificationsOptions(model='your-model-id'))).get_result()
print(json.dumps(response, indent=2))
Example Classifications feature request
require "json"
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "www.ibm.com",
features: {classifications: {model: "your-model-id"}}
)
puts JSON.pretty_generate(response.result)
Example Classifications feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let classifications = ClassificationsOptions(model: "your-model-id")
let features = Features(classifications: classifications)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Classifications feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
url: "www.ibm.com",
features: new Features()
{
Classifications = new ClassificationsOptions()
{
Model = "your-model-id"
}
}
);
Console.WriteLine(result.Response);
Example Classifications feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Classifications = new ClassificationsOptions()
{
Model = "your-model-id"
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "www.ibm.com",
features: features
);
See the ClassificationsResult
object in the Analyze text method.
Example Classifications feature response
{
"classifications": [
{
"class_name": "temperature",
"confidence": 0.562519
},
{
"class_name": "conditions",
"confidence": 0.433996
},
{
"class_name": "satisfied",
"confidence": 0.355816
}
],
"language": "en",
"usage": {
"features": 0,
"text_characters": 36,
"text_units": 1
}
}
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 more information, 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=2022-04-07"
Example parameters
{
"url": "www.ibm.com",
"features": {
"concepts": {
"limit": 3
}
}
}
Example Concepts feature request
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "www.ibm.com"
limit := int64(3)
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Concepts: &naturallanguageunderstandingv1.ConceptsOptions{
Limit: &limit,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Concepts feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "www.ibm.com";
ConceptsOptions concepts= new ConceptsOptions.Builder()
.limit(3)
.build();
Features features = new Features.Builder()
.concepts(concepts)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Concepts feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'www.ibm.com',
'features': {
'concepts': {
'limit': 3
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Concepts feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, ConceptsOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "www.ibm.com",
features: {concepts: {limit:3}}
)
puts JSON.pretty_generate(response.result)
Example Concepts feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let concepts = ConceptsOptions(limit: 3)
let features = Features(concepts: concepts)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Concepts feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
url: "www.ibm.com",
features: new Features()
{
Concepts = new ConceptsOptions()
{
Limit = 3
}
}
);
Console.WriteLine(result.Response);
Example Concepts feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Concepts = new ConceptsOptions()
{
Limit = 3
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "www.ibm.com",
features: features
);
See the ConceptsResult[]
object in the Analyze text method.
Example Concepts 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 more information, 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 that is 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=2022-04-07"
Example parameters
{
"html": "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>",
"features": {
"emotion": {
"targets": [
"apples",
"oranges"
]
}
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
html := "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>"
targets := []string{"apples", "oranges"}
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
HTML: &html,
Features: &naturallanguageunderstandingv1.Features{
Emotion: &naturallanguageunderstandingv1.EmotionOptions{
Targets: targets,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Emotion feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String html = "<html><head><title>Fruits</title></head>" +
"<body><h1>Apples and Oranges</h1>" +
"<p>I love apples! I don't like oranges.</p>" +
"</body></html>";
List<String> targets = new ArrayList<>();
targets.add("apples");
targets.add("oranges");
EmotionOptions emotion= new EmotionOptions.Builder()
.targets(targets)
.build();
Features features = new Features.Builder()
.emotion(emotion)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.html(html)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Emotion feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'html': '<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don\'t like oranges.</p></body></html>',
'features': {
'emotion': {
'targets': [
'apples',
'oranges'
]
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Emotion feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, EmotionOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
html: "<html><head><title>Fruits</title></head><body><h1>Apples and Oranges</h1><p>I love apples! I don't like oranges.</p></body></html>",
features: {emotion: {targets: ['apples','oranges']}}
)
puts JSON.pretty_generate(response.result)
Example Emotion feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let html = "<html><head><title>Fruits</title></head>" +
"<body><h1>Apples and Oranges</h1>" +
"<p>I love apples! I don't like oranges.</p>" +
"</body></html>"
let emotion = EmotionOptions(targets: ["apples", "oranges"])
let features = Features(emotion: emotion)
naturalLanguageUnderstanding.analyze(features: features, html: html) {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Emotion feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.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: new Features()
{
Emotion = new EmotionOptions()
{
Targets = new List<string> { "apples", "oranges" }
}
}
);
Console.WriteLine(result.Response);
Example Emotion feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Emotion = new EmotionOptions()
{
Targets = {"apples","oranges"}
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
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
);
See the EmotionResult
object in the Analyze text method.
Example Emotion feature response
{
"usage": {
"text_units": 1,
"text_characters": 37,
"features": 1
},
"language": "en",
"emotion": {
"targets": [
{
"text": "apples",
"emotion": {
"sadness": 0.028574,
"joy": 0.859042,
"fear": 0.02752,
"disgust": 0.017519,
"anger": 0.012855
}
},
{
"text": "oranges",
"emotion": {
"sadness": 0.514253,
"joy": 0.078317,
"fear": 0.074223,
"disgust": 0.058103,
"anger": 0.126859
}
}
],
"document": {
"emotion": {
"sadness": 0.32665,
"joy": 0.563273,
"fear": 0.033387,
"disgust": 0.022637,
"anger": 0.041796
}
}
}
}
Entities
Identifies people, cities, organizations, and other entities in the content. See Entity type systems.
Entities request options
For more information, 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 sentiment 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=2022-04-07"
Example parameters
{
"url": "www.cnn.com",
"features": {
"entities": {
"sentiment": true,
"limit": 1
}
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "www.cnn.com"
sentiment := true
limit := int64(1)
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Entities: &naturallanguageunderstandingv1.EntitiesOptions{
Sentiment: &sentiment,
Limit: &limit,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Entities feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "www.cnn.com";
EntitiesOptions entities= new EntitiesOptions.Builder()
.sentiment(true)
.limit(1)
.build();
Features features = new Features.Builder()
.entities(entities)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Entities feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'www.cnn.com',
'features': {
'entities': {
'sentiment': true,
'limit': 1
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Entities feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, EntitiesOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "www.cnn.com",
features: {entities: {sentiment: true, limit: 1}
}
)
puts JSON.pretty_generate(response.result)
Example Entities feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let entities = EntitiesOptions(limit: 1, sentiment: true)
let features = Features(entities: entities)
naturalLanguageUnderstanding.analyze(features: features, url: "www.cnn.com") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Entities feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
url: "www.cnn.com",
features: new Features()
{
Entities = new EntitiesOptions()
{
Sentiment = true,
Limit = 1
}
}
);
Console.WriteLine(result.Response);
Example Entities feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Entities = new EntitiesOptions()
{
Limit = 1,
Sentiment = true
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "www.cnn.com",
features: features
);
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. For example, analyzing a company's press release could return keywords such as "sustainability", "hybrid cloud", or "IBM".
Keywords request options
For more information, see the request body for the Analyze text method.
-
Maximum number of keywords to return.
Default:
50
-
Whether to return sentiment 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=2022-04-07"
Example parameters
{
"url": "www.ibm.com",
"features": {
"keywords": {
"sentiment": true,
"emotion": true,
"limit": 3
}
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "www.ibm.com"
sentiment := true
emotion := true
limit := int64(3)
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Keywords: &naturallanguageunderstandingv1.KeywordsOptions{
Sentiment: &sentiment,
Emotion: &emotion,
Limit: &limit,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Keywords feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "www.ibm.com";
KeywordsOptions keywords= new KeywordsOptions.Builder()
.sentiment(true)
.emotion(true)
.limit(3)
.build();
Features features = new Features.Builder()
.keywords(keywords)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'www.ibm.com',
'features': {
'keywords': {
'sentiment': true,
'emotion': true,
'limit': 3
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Keywords feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, KeywordsOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "www.ibm.com",
features: {keywords: {sentiment: true, emotion: true, limit: 3}
}
)
puts JSON.pretty_generate(response.result)
Example Keywords feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let keywords = KeywordsOptions(limit: 3, sentiment: true, emotion: true)
let features = Features(keywords: keywords)
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Keywords feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
url: "www.ibm.com",
features: new Features()
{
Keywords = new KeywordsOptions()
{
Sentiment = true,
Emotion = true,
Limit = 2
}
}
);
Console.WriteLine(result.Response);
Example Keywords feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Keywords = new KeywordsOptions()
{
Limit = 3,
Sentiment = true,
Emotion = true
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "www.ibm.com",
features: features
);
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
Metadata response
Example Metadata feature request
curl -X POST -H "Content-Type: application/json" -u "apikey:{apikey}" -d @parameters.json "{url}/v1/analyze?version=2022-04-07"
Example parameters
{
"url": "www.ibm.com",
"features": {
"metadata": {}
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "www.ibm.com"
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Metadata: make(map[string]string{}),
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Metadata feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "www.ibm.com";
Map<String, Object> metadata= new HashMap<String, Object>();
Features features = new Features.Builder()
.metadata(metadata)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Metadata feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'www.ibm.com',
'features': {
'metadata': {}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Metadata feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_url('{url}')
response = natural_language_understanding.analyze(
url='www.ibm.com',
features=Features(metadata=())).get_result()
print(json.dumps(response, indent=2))
Example Metadata feature request
require "json"
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "www.ibm.com",
features: {metadata: {}
}
)
puts JSON.pretty_generate(response.result)
Example Metadata feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let features = Features(metadata: ["": .string("")])
naturalLanguageUnderstanding.analyze(features: features, url: "www.ibm.com") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Metadata feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
Dictionary<string, object> metadata = new Dictionary<string, object>();
var result = naturalLanguageUnderstanding.Analyze(
url: "www.ibm.com",
features: new Features()
{
Metadata = metadata
}
);
Console.WriteLine(result.Response);
Example Metadata feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Dictionary<string, object> metadata = new Dictionary<string, object>();
Features features = new Features()
{
Metadata = metadata
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "www.ibm.com",
features: features
);
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 more information, 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](/docs/natural-language-understanding?topic=natural-language-understanding-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=2022-04-07"
Example parameters
{
"features": {
"relations": {}
},
"text": "Leonardo DiCaprio won Best Actor in a Leading Role for his performance."
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
text := "Leonardo DiCaprio won Best Actor in a Leading Role for his performance."
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
Text: &text,
Features: &naturallanguageunderstandingv1.Features{
Relations: &naturallanguageunderstandingv1.RelationsOptions{},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Relations feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String text = "Leonardo DiCaprio won Best Actor" +
" in a Leading Role for his performance.";
RelationsOptions relations = new RelationsOptions.Builder()
.build();
Features features = new Features.Builder()
.relations(relations)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.text(text)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Relations feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'features': {
'relations': {}
},
'text': 'Leonardo DiCaprio won Best Actor in a Leading Role for his performance.'
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Relations feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, RelationsOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
text: "Leonardo DiCaprio won Best Actor in a Leading Role for his performance.",
features: {relations: {}
}
)
puts JSON.pretty_generate(response.result)
Example Relations feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let text = "Leonardo DiCaprio won Best Actor" +
" in a Leading Role for his performance."
let features = Features(relations: RelationsOptions())
naturalLanguageUnderstanding.analyze(features: features, text: text) {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Relations feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
text: "Leonardo DiCaprio won Best Actor in a Leading Role for his performance.",
features: new Features()
{
Relations = new RelationsOptions()
}
);
Console.WriteLine(result.Response);
Example Relations feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Relations = new RelationsOptions()
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
text: "Leonardo DiCaprio won Best Actor in a Leading Role for his performance.",
features: features
);
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 more information, 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 Semantic Roles feature request
curl -X POST -H "Content-Type: application/json" -u "apikey:{apikey}" -d @parameters.json "{url}/v1/analyze?version=2022-04-07"
Example parameters
{
"features": {
"semantic_roles": {}
},
"text": "IBM has one of the largest workforces in the world"
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
text := "IBM has one of the largest workforces in the world"
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
Text: &text,
Features: &naturallanguageunderstandingv1.Features{
SemanticRoles: &naturallanguageunderstandingv1.SemanticRolesOptions{},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Semantic Roles feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String text = "IBM has one of the largest" +
" workforces in the world";
SemanticRolesOptions semanticRoles = new SemanticRolesOptions.Builder()
.build();
Features features = new Features.Builder()
.semanticRoles(semanticRoles)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.text(text)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Semantic Roles feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'features': {
'semantic_roles': {}
},
'text': 'IBM has one of the largest workforces in the world'
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Semantic Roles feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, SemanticRolesOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_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 Semantic Roles feature request
require "json"
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
text: "IBM has one of the largest workforces in the world",
features: {semantic_roles: {}
}
)
puts JSON.pretty_generate(response.result)
Example Semantic Roles feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let text = "IBM has one of the largest" +
" workforces in the world"
let semanticRoles = Features(semanticRoles: SemanticRolesOptions())
naturalLanguageUnderstanding.analyze(features: semanticRoles, text: text) {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Semantic Roles feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
text: "IBM has one of the largest workforces in the world",
features: new Features()
{
SemanticRoles = new SemanticRolesOptions()
}
);
Console.WriteLine(result.Response);
Example Semantic Roles feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
SemanticRoles = new SemanticRolesOptions()
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
text: "IBM has one of the largest workforces in the world",
features: features
);
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. As an example, the phrase "Thank you and have a nice day!" returns a positive sentiment (score .91). You can analyze sentiment for detected entities with entities.sentiment
and for keywords with keywords.sentiment
.
Sentiment request options
For more information, 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 that is 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=2022-04-07"
Example parameters
{
"url": "https://en.wikipedia.org/wiki/Emmanuel_Macron",
"features": {
"sentiment": {
"targets": [
"France"
]
}
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
url := "https://en.wikipedia.org/wiki/Emmanuel_Macron"
targets := []string{"France"}
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
URL: &url,
Features: &naturallanguageunderstandingv1.Features{
Sentiment: &naturallanguageunderstandingv1.SentimentOptions{
Targets: targets,
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Sentiment feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String url = "https://en.wikipedia.org/wiki/Emmanuel_Macron";
List<String> targets = new ArrayList<>();
targets.add("France");
SentimentOptions sentiment = new SentimentOptions.Builder()
.targets(targets)
.build();
Features features = new Features.Builder()
.sentiment(sentiment)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.url(url)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Sentiment feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'url': 'https://en.wikipedia.org/wiki/Emmanuel_Macron',
'features': {
'sentiment': {
'targets': [
'France'
]
}
}
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Sentiment feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, SentimentOptions
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_url('{url}')
response = natural_language_understanding.analyze(
url='https://en.wikipedia.org/wiki/Emmanuel_Macron',
features=Features(sentiment=SentimentOptions(targets=['France']))).get_result()
print(json.dumps(response, indent=2))
Example Sentiment feature request
require "json"
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
url: "https://en.wikipedia.org/wiki/Emmanuel_Macron",
features: {sentiment: {targets=["France"]}
}
)
puts JSON.pretty_generate(response.result)
Example Sentiment feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let sentiment = SentimentOptions(targets: ["France"])
let features = Features(sentiment: sentiment)
naturalLanguageUnderstanding.analyze(features: features, url: "https://en.wikipedia.org/wiki/Emmanuel_Macron") {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Sentiment feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
url: "https://en.wikipedia.org/wiki/Emmanuel_Macron",
features: new Features()
{
Sentiment = new SentimentOptions()
{
Targets = new List<string>() { "France" }
}
}
);
Console.WriteLine(result.Response);
Example Sentiment feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Sentiments = new SentimentOptions()
{
Targets = {"France"}
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
url: "https://en.wikipedia.org/wiki/Emmanuel_Macron",
features: features
);
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": "France",
"score": 0.279964,
"label": "positive"
}
],
"document": {
"score": 0.127034,
"label": "positive"
}
},
"retrieved_url": "https://en.wikipedia.org/wiki/Emmanuel_Macron",
"language": "en"
}
Syntax
Returns information about the tokens and sentences in the input text. At least one of syntax.tokens
or syntax.sentences
must be specified.
Syntax request options
For more information, see the request body for the Analyze text method.
-
Set this option to `true` to return information about the sentences in the input text.
-
Options for tokens
-
Set this option to `true` to return the lemma for each token.
-
Set this option to `true` to return the part of speech for each token.
syntax.tokens
-
Syntax response
Example Syntax feature request
curl -X POST -H "Content-Type: application/json" -u "apikey:{apikey}" -d @parameters.json "{url}/v1/analyze?version=2022-04-07"
Example parameters
{
"text": "With great power comes great responsibility",
"features": {
"syntax": {
"sentences": true,
"tokens": {
"lemma": true,
"part_of_speech": true
}
}
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "2022-04-07",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
text := "With great power comes great responsibility"
sentences := true
lemma := true
partOfSpeech := true
response, responseErr := naturalLanguageUnderstanding.Analyze(
&naturallanguageunderstandingv1.AnalyzeOptions{
Text: &text,
Features: &naturallanguageunderstandingv1.Features{
Syntax: &naturallanguageunderstandingv1.SyntaxOptions{
Sentences: &sentences,
Tokens: &naturallanguageunderstandingv1.SyntaxOptionsTokens{
Lemma: &lemma,
PartOfSpeech: &partOfSpeech,
},
},
},
},
)
if responseErr != nil {
panic(responseErr)
}
b, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(b))
}
Example Syntax feature request
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("2022-04-07", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
String text = "With great power comes great responsibility"
SyntaxOptions syntax = new SyntaxOptions.Builder()
.sentences(true)
.build();
Features features = new Features.Builder()
.syntax(syntax)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.text(text)
.features(features)
.build();
AnalysisResults response = naturalLanguageUnderstanding
.analyze(parameters)
.execute()
.getResult();
System.out.println(response);
Example Syntax feature request
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '2022-04-07',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
const analyzeParams = {
'features': {
'syntax': {
'sentences': true,
'tokens': {
'lemma': true,
'part_of_speech': true
}
}
},
'text': 'With great power comes great responsibility'
};
naturalLanguageUnderstanding.analyze(analyzeParams)
.then(analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
})
.catch(err => {
console.log('error:', err);
});
Example Syntax feature request
import json
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson.natural_language_understanding_v1 \
import Features, SyntaxOptions, SyntaxOptionsTokens
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='2022-04-07',
authenticator=authenticator
)
natural_language_understanding.set_service_url('{url}')
response = natural_language_understanding.analyze(
text='With great power comes great responsibility',
features=Features(
syntax=SyntaxOptions(
sentences=True,
tokens=SyntaxOptionsTokens(
lemma=True,
part_of_speech=True,
)))).get_result()
print(json.dumps(response, indent=2))
Example Syntax feature request
require "json"
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "2022-04-07",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
response = natural_language_understanding.analyze(
text: "With great power comes great responsibility",
features: {
syntax: {
sentences: true,
tokens: {
lemma: true,
part_of_speech: true,
}
}
}
)
puts JSON.pretty_generate(response.result)
Example Syntax feature request
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "2022-04-07", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
let text = "With great power comes great responsibility"
let tokens = SyntaxOptionsTokens(lemma: true, partOfSpeech: true)
let syntax = SyntaxOptions(sentences: true, tokens: tokens)
let features = Features(syntax: syntax)
naturalLanguageUnderstanding.analyze(features: features, text: text) {
response, error in
guard let analysis = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(analysis)
}
Example Syntax feature request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
var result = naturalLanguageUnderstanding.Analyze(
text: "With great power comes great responsibility",
features: new Features()
{
Syntax = new SyntaxOptions()
{
Sentences = true,
Tokens = new SyntaxOptionsTokens()
{
Lemma = true,
PartOfSpeech = true
}
}
}
);
Console.WriteLine(result.Response);
Example Syntax feature request
IamAuthenticator authenticator = new IamAuthenticator(
Apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
NaturalLanguageUnderstandingService service = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
Features features = new Features()
{
Syntax = new SyntaxOptions()
{
Sentences = true,
Tokens = new SyntaxOptionsTokens()
{
PartOfSpeech = true,
Lemma = true
}
}
};
naturalLanguageUnderstanding.Analyze(
callback: (DetailedResponse<AnalysisResults> response, IBMError error) =>
{
Log.Debug("NaturalLanguageUnderstandingServiceV1", "Analyze result: {0}", response.Response);
},
text: "With great power comes great responsibility",
features: features
);
See the SyntaxResult
object in the Analyze text method.
Example Syntax feature response
{
"usage": {
"text_units": 1,
"text_characters": 43,
"features": 1
},
"syntax": {
"tokens": [
{
"text": "With",
"part_of_speech": "ADP",
"location": [
0,
4
],
"lemma": "with"
},
{
"text": "great",
"part_of_speech": "ADJ",
"location": [
5,
10
],
"lemma": "great"
},
{
"text": "power",
"part_of_speech": "NOUN",
"location": [
11,
16
],
"lemma": "power"
},
{
"text": "comes",
"part_of_speech": "VERB",
"location": [
17,
22
],
"lemma": "come"
},
{
"text": "great",
"part_of_speech": "ADJ",
"location": [
23,
28
],
"lemma": "great"
},
{
"text": "responsibility",
"part_of_speech": "NOUN",
"location": [
29,
43
],
"lemma": "responsibility"
}
],
"sentences": [
{
"text": "With great power comes great responsibility",
"location": [
0,
43
]
}
]
},
"language": "en"
}
Summarization (Experimental)
Returns a summary of the source content. For example, analysis of a sports article may return team names and scores.
Summarization request options
For more information, see the request body for the Analyze text method.
-
Maximum number of summary sentences to return.
Default:
3
Summarization response
Example Summarization feature request
curl -X POST -H "Content-Type: application/json" -u "apikey:{apikey}" -d @parameters.json "{url}/v1/analyze?version=2022-04-07"
Example parameters
{
"url": "www.ibm.com",
"features": {
"summarization": {
"limit": 2
}
}
}
See the SummarizationResult
object in the Analyze text method.
Example Summarization feature response
{
"usage": {
"text_units": 1,
"text_characters": 2922,
"features": 0
},
"retrieved_url": "https://newsroom.ibm.com/Five-Things-IBM-Workday",
"summarization": {
"text": "Today, IBM and Workday, a leading provider of enterprise applications for human resources and finance, announced a joint solution designed to help companies begin the process of safely re-opening their workplaces. Here are five key takeaways from the announcement."
},
"language": "en"
}
IBM Cloud URLs
The base URLs come from the service instance. To find the URL, view the service credentials by clicking the name of the service in the Resource list. Use the value of the URL. Add the method to form the complete API endpoint for your request.
The following example URL represents a Natural Language Understanding instance that is hosted in Washington DC:
https://api.us-east.natural-language-understanding.watson.cloud.ibm.com/instances/6bbda3b3-d572-45e1-8c54-22d6ed9e52c2
The following URLs represent the base URLs for Natural Language Understanding. When you call the API, use the URL that corresponds to the location of your service instance.
- Dallas:
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
- Washington DC:
https://api.us-east.natural-language-understanding.watson.cloud.ibm.com
- Frankfurt:
https://api.eu-de.natural-language-understanding.watson.cloud.ibm.com
- Sydney:
https://api.au-syd.natural-language-understanding.watson.cloud.ibm.com
- Tokyo:
https://api.jp-tok.natural-language-understanding.watson.cloud.ibm.com
- London:
https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com
- Seoul:
https://api.kr-seo.natural-language-understanding.watson.cloud.ibm.com
Set the correct service URL by calling the setServiceUrl()
method of the service instance.
Set the correct service URL by specifying the serviceUrl
parameter when you create the service instance.
Set the correct service URL by calling the set_service_url()
method of the service instance.
Set the correct service URL by specifying the service_url
property of the service instance.
Set the correct service URL by calling the SetServiceURL()
method of the service instance.
Set the correct service URL by setting the serviceURL
property of the service instance.
Set the correct service URL by calling the SetServiceUrl()
method of the service instance.
Set the correct service URL by calling the SetServiceUrl()
method of the service instance.
Dallas API endpoint example for services managed on IBM Cloud
curl -X {request_method} -u "apikey:{apikey}" "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/{instance_id}"
Your service instance might not use this URL
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", authenticator);
naturalLanguageUnderstanding.setServiceUrl("https://api.us-east.natural-language-understanding.watson.cloud.ibm.com");
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '{version}',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: 'https://api.us-east.natural-language-understanding.watson.cloud.ibm.com',
});
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='{version}',
authenticator=authenticator
)
natural_language_understanding.set_service_url('https://api.us-east.natural-language-understanding.watson.cloud.ibm.com')
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "{version}",
authenticator: authenticator
)
natural_language_understanding.service_url = "https://api.us-east.natural-language-understanding.watson.cloud.ibm.com"
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("https://api.us-east.natural-language-understanding.watson.cloud.ibm.com")
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "https://api.us-east.natural-language-understanding.watson.cloud.ibm.com"
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("https://api.us-east.natural-language-understanding.watson.cloud.ibm.com");
Default URL
https://api.us-south.natural-language-understanding.watson.cloud.ibm.com
Example for the Washington DC location
var authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("https://api.us-east.natural-language-understanding.watson.cloud.ibm.com");
Disabling SSL verification
All Watson services use Secure Sockets Layer (SSL) (or Transport Layer Security (TLS)) for secure connections between the client and server. The connection is verified against the local certificate store to ensure authentication, integrity, and confidentiality.
If you use a self-signed certificate, you need to disable SSL verification to make a successful connection.
Enabling SSL verification is highly recommended. Disabling SSL jeopardizes the security of the connection and data. Disable SSL only if necessary, and take steps to enable SSL as soon as possible.
To disable SSL verification for a curl request, use the --insecure
(-k
) option with the request.
To disable SSL verification, create an HttpConfigOptions
object and set the disableSslVerification
property to true
. Then, pass the object to the service instance by using the configureClient
method.
To disable SSL verification, set the disableSslVerification
parameter to true
when you create the service instance.
To disable SSL verification, specify True
on the set_disable_ssl_verification
method for the service instance.
To disable SSL verification, set the disable_ssl_verification
parameter to true
in the configure_http_client()
method for the service instance.
To disable SSL verification, call the DisableSSLVerification
method on the service instance.
To disable SSL verification, call the disableSSLVerification()
method on the service instance. You cannot disable SSL verification on Linux.
To disable SSL verification, set the DisableSslVerification
method to true
on the service instance.
To disable SSL verification, set the DisableSslVerification
method to true
on the service instance.
Example to disable SSL verification. Replace {apikey}
and {url}
with your service credentials.
curl -k -X {request_method} -u "apikey:{apikey}" "{url}/{method}"
Example to disable SSL verification
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
HttpConfigOptions configOptions = new HttpConfigOptions.Builder()
.disableSslVerification(true)
.build();
naturalLanguageUnderstanding.configureClient(configOptions);
Example to disable SSL verification
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '{version}',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
disableSslVerification: true,
});
Example to disable SSL verification
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='{version}',
authenticator=authenticator
)
natural_language_understanding.set_service_url('{url}')
natural_language_understanding.set_disable_ssl_verification(True)
Example to disable SSL verification
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "{version}",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
natural_language_understanding.configure_http_client(disable_ssl_verification: true)
Example to disable SSL verification
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
naturalLanguageUnderstanding.DisableSSLVerification()
Example to disable SSL verification
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
naturalLanguageUnderstanding.disableSSLVerification()
Example to disable SSL verification
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
naturalLanguageUnderstanding.DisableSslVerification(true);
Example to disable SSL verification
var authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
naturalLanguageUnderstanding.DisableSslVerification = true;
Authentication
You authenticate to the API by using IBM Cloud Identity and Access Management (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. For more information, see Authenticating to Watson services.
- For testing and development, you can pass an API key directly.
- For production use, unless you use the Watson SDKs, use an IAM token.
If you pass in an API key, use apikey
for the username and the value of the API key as the password. For example, if the API key is f5sAznhrKQyvBFFaZbtF60m5tzLbqWhyALQawBg5TjRI
in the service credentials, include the credentials in your call like this:
curl -u "apikey:f5sAznhrKQyvBFFaZbtF60m5tzLbqWhyALQawBg5TjRI"
For IBM Cloud instances, the SDK provides initialization methods for each form of authentication.
- Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
- Use the access token to manage the lifecycle yourself. You must periodically refresh the token.
For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.
Replace {apikey}
and {url}
with your service credentials.
curl -X {request_method} -u "apikey:{apikey}" "{url}/v1/{method}"
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", authenticator);
naturalLanguageUnderstanding.setServiceUrl("{url}");
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
version: '{version}',
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
serviceUrl: '{url}',
});
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
authenticator = IAMAuthenticator('{apikey}')
natural_language_understanding = NaturalLanguageUnderstandingV1(
version='{version}',
authenticator=authenticator
)
natural_language_understanding.set_service_url('{url}')
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
require "ibm_watson/authenticators"
require "ibm_watson/natural_language_understanding_v1"
include IBMWatson
authenticator = Authenticators::IamAuthenticator.new(
apikey: "{apikey}"
)
natural_language_understanding = NaturalLanguageUnderstandingV1.new(
version: "{version}",
authenticator: authenticator
)
natural_language_understanding.service_url = "{url}"
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
import (
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
func main() {
authenticator := &core.IamAuthenticator{
ApiKey: "{apikey}",
}
options := &naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
Version: "{version}",
Authenticator: authenticator,
}
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
naturalLanguageUnderstanding.SetServiceURL("{url}")
}
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", authenticator: authenticator)
naturalLanguageUnderstanding.serviceURL = "{url}"
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
SDK managing the IAM token. Replace {apikey}
, {version}
, and {url}
.
var authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
Access between services
Your application might use more than one Watson service. You can grant access between services and you can grant access to more than one service for your applications.
For IBM Cloud services, the method to grant access between Watson services varies depending on the type of API key. For more information, see IAM access.
- To grant access between IBM Cloud services, create an authorization between the services. For more information, see Granting access between services.
- To grant access to your services by applications without using user credentials, create a service ID, add an API key, and assign access policies. For more information, see Creating and working with service IDs.
When you give a user ID access to multiple services, use an endpoint URL that includes the service instance ID (for example, https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/6bbda3b3-d572-45e1-8c54-22d6ed9e52c2
). You can find the instance ID in two places:
-
By clicking the service instance row in the Resource list. The instance ID is the GUID in the details pane.
-
By clicking the name of the service instance in the list and looking at the credentials URL.
If you don't see the instance ID in the URL, the credentials predate service IDs. Add new credentials from the Service credentials page and use those credentials.
Versioning
API requests require a version parameter that takes a date in the format version=YYYY-MM-DD
. When the API is updated with any breaking changes, the service introduces a new version date for the API.
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, 2022-04-07
. In some cases, differences in earlier versions are noted in the descriptions of parameters and response models.
Error handling
Natural Language Understanding 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 invalid 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 that is 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 that is returned. |
message | A message that describes the error. |
The Python SDK generates an exception for any unsuccessful method invocation. When the Python SDK receives an error response from the Natural Language Understanding service, it generates an ApiException
with the following fields.
Field | Description |
---|---|
code | The HTTP response code that is returned. |
message | A message that describes the error. |
info | A dictionary of additional information about the error. |
When the Ruby SDK receives an error response from the Natural Language Understanding service, it generates an ApiException
with the following fields.
Field | Description |
---|---|
code | The HTTP response code that is 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 that is returned. |
message | A message that describes the error. |
The Swift SDK returns a WatsonError
in the completionHandler
any unsuccessful method invocation. This error type is an enum that conforms to LocalizedError
and contains an errorDescription
property that returns an error message. Some of the WatsonError
cases contain associated values that reveal more information about the error.
Field | Description |
---|---|
errorDescription | A message that describes the error. |
When the .NET Standard SDK receives an error response from the Natural Language Understanding service, it generates a ServiceResponseException
with the following fields.
Field | Description |
---|---|
Message | A message that describes the error. |
CodeDescription | The HTTP response code that is returned. |
When the Unity SDK receives an error response from the Natural Language Understanding service, it generates an IBMError
with the following fields.
Field | Description |
---|---|
Url | The URL that generated the error. |
StatusCode | The HTTP response code returned. |
ErrorMessage | A message that describes the error. |
Response | The contents of the response from the server. |
ResponseHeaders | A dictionary of headers returned by the request. |
Example error handling
try {
// Invoke a method
} catch (NotFoundException e) {
// Handle Not Found (404) exception
} catch (RequestTooLargeException e) {
// Handle Request Too Large (413) exception
} catch (ServiceResponseException e) {
// Base class for all exceptions caused by error responses from the service
System.out.println("Service returned status code "
+ e.getStatusCode() + ": " + e.getMessage());
}
Example error handling
naturalLanguageUnderstanding.method(params)
.catch(err => {
console.log('error:', err);
});
Example error handling
from ibm_watson import ApiException
try:
# Invoke a method
except ApiException as ex:
print "Method failed with status code " + str(ex.code) + ": " + ex.message
Example error handling
require "ibm_watson"
begin
# Invoke a method
rescue IBMWatson::ApiException => ex
print "Method failed with status code #{ex.code}: #{ex.error}"
end
Example error handling
import "github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
// Instantiate a service
naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(options)
// Check for errors
if naturalLanguageUnderstandingErr != nil {
panic(naturalLanguageUnderstandingErr)
}
// Call a method
result, _, responseErr := naturalLanguageUnderstanding.MethodName(&methodOptions)
// Check for errors
if responseErr != nil {
panic(responseErr)
}
Example error handling
naturalLanguageUnderstanding.method() {
response, error in
if let error = error {
switch error {
case let .http(statusCode, message, metadata):
switch statusCode {
case .some(404):
// Handle Not Found (404) exception
print("Not found")
case .some(413):
// Handle Request Too Large (413) exception
print("Payload too large")
default:
if let statusCode = statusCode {
print("Error - code: \(statusCode), \(message ?? "")")
}
}
default:
print(error.localizedDescription)
}
return
}
guard let result = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(result)
}
Example error handling
try
{
// Invoke a method
}
catch(ServiceResponseException e)
{
Console.WriteLine("Error: " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Example error handling
// Invoke a method
naturalLanguageUnderstanding.MethodName(Callback, Parameters);
// Check for errors
private void Callback(DetailedResponse<ExampleResponse> response, IBMError error)
{
if (error == null)
{
Log.Debug("ExampleCallback", "Response received: {0}", response.Response);
}
else
{
Log.Debug("ExampleCallback", "Error received: {0}, {1}, {3}", error.StatusCode, error.ErrorMessage, error.Response);
}
}
Additional headers
Some Watson services accept special parameters in headers that are passed with the request.
You can pass request header parameters in all requests or in a single request to the service.
To pass a request header, use the --header
(-H
) option with a curl request.
To pass header parameters with every request, use the setDefaultHeaders
method of the service object. See Data collection for an example use of this method.
To pass header parameters in a single request, use the addHeader
method as a modifier on the request before you execute it.
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 it.
To pass header parameters with every request, specify the set_default_headers
method of the service object. See Data collection for an example use of this method.
To pass header parameters in a single request, include headers
as a dict
in the request.
To pass header parameters with every request, specify the add_default_headers
method of the service object. See Data collection for an example use of this method.
To pass header parameters in a single request, specify the headers
method as a chainable method in the request.
To pass header parameters with every request, specify the SetDefaultHeaders
method of the service object. See Data collection for an example use of this method.
To pass header parameters in a single request, specify the Headers
as a map
in the request.
To pass header parameters with every request, add them to the defaultHeaders
property of the service object. See Data collection for an example use of this method.
To pass header parameters in a single request, pass the headers
parameter to the request method.
To pass header parameters in a single request, use the WithHeader()
method as a modifier on the request before you execute it. See Data collection for an example use of this method.
To pass header parameters in a single request, use the WithHeader()
method as a modifier on the request before you execute it.
Example header parameter in a request
curl -X {request_method} -H "Request-Header: {header_value}" "{url}/v1/{method}"
Example header parameter in a request
ReturnType returnValue = naturalLanguageUnderstanding.methodName(parameters)
.addHeader("Custom-Header", "{header_value}")
.execute();
Example header parameter in a request
const parameters = {
{parameters}
};
naturalLanguageUnderstanding.methodName(
parameters,
headers: {
'Custom-Header': '{header_value}'
})
.then(result => {
console.log(response);
})
.catch(err => {
console.log('error:', err);
});
Example header parameter in a request
response = natural_language_understanding.methodName(
parameters,
headers = {
'Custom-Header': '{header_value}'
})
Example header parameter in a request
response = natural_language_understanding.headers(
"Custom-Header" => "{header_value}"
).methodName(parameters)
Example header parameter in a request
result, _, responseErr := naturalLanguageUnderstanding.MethodName(
&methodOptions{
Headers: map[string]string{
"Accept": "application/json",
},
},
)
Example header parameter in a request
let customHeader: [String: String] = ["Custom-Header": "{header_value}"]
naturalLanguageUnderstanding.methodName(parameters, headers: customHeader) {
response, error in
}
Example header parameter in a request
IamAuthenticator authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
naturalLanguageUnderstanding.WithHeader("Custom-Header", "header_value");
Example header parameter in a request
var authenticator = new IamAuthenticator(
apikey: "{apikey}"
);
while (!authenticator.CanAuthenticate())
yield return null;
var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");
naturalLanguageUnderstanding.WithHeader("Custom-Header", "header_value");
Response details
The Natural Language Understanding service might return information to the application in response headers.
To access all response headers that the service returns, include the --include
(-i
) option with a curl request. To see detailed response data for the request, including request headers, response headers, and extra debugging information, include the --verbose
(-v
) option with the request.
Example request to access response headers
curl -X {request_method} {authentication_method} --include "{url}/v1/{method}"
To access information in the response headers, use one of the request methods that returns details with the response: executeWithDetails()
, enqueueWithDetails()
, or rxWithDetails()
. These methods return a Response<T>
object, where T
is the expected response model. Use the getResult()
method to access the response object for the method, and use the getHeaders()
method to access information in response headers.
Example request to access response headers
Response<ReturnType> response = naturalLanguageUnderstanding.methodName(parameters)
.executeWithDetails();
// Access response from methodName
ReturnType returnValue = response.getResult();
// Access information in response headers
Headers responseHeaders = response.getHeaders();
All response data is available in the Response<T>
object that is returned by each method. To access information in the response
object, use the following properties.
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
naturalLanguageUnderstanding.methodName(parameters)
.then(response => {
console.log(response.headers);
})
.catch(err => {
console.log('error:', err);
});
The return value from all service methods is a DetailedResponse
object. To access information in the result object or response headers, use the following methods.
DetailedResponse
Method | Description |
---|---|
get_result() |
Returns the response for the service-specific method. |
get_headers() |
Returns the response header information. |
get_status_code() |
Returns the HTTP status code. |
Example request to access response headers
natural_language_understanding.set_detailed_response(True)
response = natural_language_understanding.methodName(parameters)
# Access response from methodName
print(json.dumps(response.get_result(), indent=2))
# Access information in response headers
print(response.get_headers())
# Access HTTP response status
print(response.get_status_code())
The return value from all service methods is a DetailedResponse
object. To access information in the response
object, use the following properties.
DetailedResponse
Property | Description |
---|---|
result |
Returns the response for the service-specific method. |
headers |
Returns the response header information. |
status |
Returns the HTTP status code. |
Example request to access response headers
response = natural_language_understanding.methodName(parameters)
# Access response from methodName
print response.result
# Access information in response headers
print response.headers
# Access HTTP response status
print response.status
The return value from all service methods is a DetailedResponse
object. To access information in the response
object or response headers, use the following methods.
DetailedResponse
Method | Description |
---|---|
GetResult() |
Returns the response for the service-specific method. |
GetHeaders() |
Returns the response header information. |
GetStatusCode() |
Returns the HTTP status code. |
Example request to access response headers
import (
"github.com/IBM/go-sdk-core/core"
"github.com/watson-developer-cloud/go-sdk/naturallanguageunderstandingv1"
)
result, response, responseErr := naturalLanguageUnderstanding.MethodName(
&methodOptions{})
// Access result
core.PrettyPrint(response.GetResult(), "Result ")
// Access response headers
core.PrettyPrint(response.GetHeaders(), "Headers ")
// Access status code
core.PrettyPrint(response.GetStatusCode(), "Status Code ")
All response data is available in the WatsonResponse<T>
object that is returned in each method's completionHandler
.
Example request to access response headers
naturalLanguageUnderstanding.methodName(parameters) {
response, error in
guard let result = response?.result else {
print(error?.localizedDescription ?? "unknown error")
return
}
print(result) // The data returned by the service
print(response?.statusCode)
print(response?.headers)
}