IBM Cloud API Docs

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

This feature does not accept any request options.

Metadata response

Example Metadata feature request

curl -X POST -H "Content-Type: application/json" -u "apikey:{apikey}" -d @parameters.json "{url}/v1/analyze?version=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

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

Endpoint URLs

Identify the base URL for your service instance.

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

Data handling

Additional headers

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

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

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

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

To pass header parameters in a single request, use the addHeader method as a modifier on the request before you execute 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)
}

The response contains fields for response headers, response JSON, and the status code.

DetailedResponse

Property Description
Result Returns the result for the service-specific method.
Response Returns the raw JSON response for the service-specific method.
Headers Returns the response header information.
StatusCode Returns the HTTP status code.

Example request to access response headers

var results = naturalLanguageUnderstanding.MethodName(parameters);

var result = results.Result;            //  The result object
var responseHeaders = results.Headers;  //  The response headers
var responseJson = results.Response;    //  The raw response JSON
var statusCode = results.StatusCode;    //  The response status code

The response contains fields for response headers, response JSON, and the status code.

DetailedResponse

Property Description
Result Returns the result for the service-specific method.
Response Returns the raw JSON response for the service-specific method.
Headers Returns the response header information.
StatusCode Returns the HTTP status code.

Example request to access response headers

private void Example()
{
    naturalLanguageUnderstanding.MethodName(Callback, Parameters);
}

private void Callback(DetailedResponse<ResponseType> response, IBMError error)
{
    var result = response.Result;                 //  The result object
    var responseHeaders = response.Headers;       //  The response headers
    var responseJson = reresponsesults.Response;  //  The raw response JSON
    var statusCode = response.StatusCode;         //  The response status code
}

Data collection

By default, Natural Language Understanding service instances that are not part of Premium plans collect data about API requests and their results. This data is collected only to improve the services for future users. The collected data is not shared or made public. Data is not collected for services that are part of Premium plans.

To prevent IBM usage of your data for an API request, set the X-Watson-Learning-Opt-Out header parameter to true. You can also disable request logging at the account level. For more information, see Controlling request logging for Watson services.

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

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

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

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

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

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

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

You can set the header by using the WithHeader() method of the service object.

Example request

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

Example request

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

naturalLanguageUnderstanding.setDefaultHeaders(headers);

Example request

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}',
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});

Example request

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

Example request

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

Example request

import "net/http"

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

Example request

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

Example request

IamAuthenticator authenticator = new IamAuthenticator(
    apikey: "{apikey}"
    );

NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");

naturalLanguageUnderstanding.WithHeader("X-Watson-Learning-Opt-Out", "true");

Example request

var authenticator = new IamAuthenticator(
    apikey: "{apikey}"
);

while (!authenticator.CanAuthenticate())
    yield return null;

var naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("{version}", authenticator);
naturalLanguageUnderstanding.SetServiceUrl("{url}");

naturalLanguageUnderstanding.WithHeader("X-Watson-Learning-Opt-Out", "true");

Synchronous and asynchronous requests

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

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

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

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

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

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

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

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

Example synchronous request

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

Example asynchronous request

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

Example synchronous request

response = natural_language_understanding.method_name(parameters)

or

response = natural_language_understanding.await.method_name(parameters)

Example asynchronous request

response = natural_language_understanding.async.method_name(parameters)

Methods

Analyze text (GET)

Change notice

Analyzes raw text, HTML, or a public webpage.

If a language for the input text is not specified with the language parameter, the service automatically detects the language.

GET /v1/analyze

Request

Query Parameters

  • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

  • Comma separated list of analysis features

    Allowable values: [categories,classifications,concepts,emotion,entities,keywords,metadata,relations,semantic_roles,sentiment,summarization (experimental),syntax]

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

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

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

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

    Default: false

  • Set this to false to disable text cleaning when analyzing webpages. For more information about webpage cleaning, see Analyzing webpages.

    Default: true

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

  • Whether to use raw HTML content if text cleaning fails

    Default: true

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

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

    Default: false

  • Maximum number of categories to return.

    Possible values: value ≤ 10

    Default: 3

  • (Beta) Enter a custom model ID to override the standard categories model. This feature is available only for English language text.

  • Model ID of the classifications model to be used

  • Maximum number of concepts to return.

    Possible values: value ≤ 50

    Default: 8

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

    Default: true

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

  • Maximum number of entities to return.

    Possible values: value ≤ 250

    Default: 50

  • Set this to true to return locations of entity mentions

    Default: false

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

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

    Default: false

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

    Default: false

  • Maximum number of keywords to return.

    Possible values: value ≤ 250

    Default: 50

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

    Default: false

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

    Default: false

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

    Default: en-news

  • Maximum number of semantic_roles results to return

    Default: 50

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

    Default: false

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

    Default: false

  • Set this to false to disable document level sentiment analysis

    Default: true

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

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

    Default: false

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

    Default: false

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

    Default: false

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

    Default: false

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

  • curl -u "apikey:{apikey}"   "{url}/v1/analyze}?version=2022-04-07&url=www.ibm.com&features=keywords,entities&entities.emotion=true&entities.sentiment=true&keywords.emotion=true&keywords.sentiment=true"

Response

Results of the analysis, organized by feature

Status Code

  • Analysis results

  • Invalid request

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

Analyze text

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

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

If a language for the input text is not specified with the language parameter, the service automatically detects the language.

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

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

If a language for the input text is not specified with the language parameter, the service automatically detects the language.

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

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

If a language for the input text is not specified with the language parameter, the service automatically detects the language.

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

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

If a language for the input text is not specified with the language parameter, the service automatically detects the language.

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

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

If a language for the input text is not specified with the language parameter, the service automatically detects the language.

POST /v1/analyze
ServiceCall<AnalysisResults> analyze(AnalyzeOptions analyzeOptions)
analyze(params)
analyze(self,
        features: 'Features',
        *,
        text: str = None,
        html: str = None,
        url: str = None,
        clean: bool = None,
        xpath: str = None,
        fallback_to_raw: bool = None,
        return_analyzed_text: bool = None,
        language: str = None,
        limit_text_characters: int = None,
        **kwargs
    ) -> DetailedResponse
Analyze(Features features, string text = null, string html = null, string url = null, bool? clean = null, string xpath = null, bool? fallbackToRaw = null, bool? returnAnalyzedText = null, string language = null, long? limitTextCharacters = null)

Request

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

Query Parameters

  • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

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

The analyze options.

parameters

  • Analysis features and options.

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

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

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

  • Set this to false to disable webpage cleaning. For more information about webpage cleaning, see Analyzing webpages.

    Default: true

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

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

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

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

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

parameters

  • Analysis features and options.

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

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

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

  • Set this to false to disable webpage cleaning. For more information about webpage cleaning, see Analyzing webpages.

    Default: true

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

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

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

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

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

parameters

  • Analysis features and options.

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

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

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

  • Set this to false to disable webpage cleaning. For more information about webpage cleaning, see Analyzing webpages.

    Default: true

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

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

    Default: true

  • Whether or not to return the analyzed text.

    Default: false

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

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

  • curl -X POST -u "apikey:{apikey}" -H "Content-Type: application/json" -d @parameters.json "{url}/v1/analyze?version=2022-04-07"
  • {
      "text": "IBM is an American multinational technology company headquartered in Armonk, New York, United States, with operations in over 170 countries.",
      "features": {
        "entities": {
          "emotion": true,
          "sentiment": true,
          "limit": 2
        },
        "keywords": {
          "emotion": true,
          "sentiment": true,
          "limit": 2
        }
      }
    }
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
    naturalLanguageUnderstanding.SetServiceUrl("{url}");
    
    var features = new Features()
    {
        Keywords = new KeywordsOptions()
        {
            Limit = 2,
            Sentiment = true,
            Emotion = true
        },
        Entities = new EntitiesOptions()
        {
            Sentiment = true,
            Limit = 2
        }
    };
    
    var result = naturalLanguageUnderstanding.Analyze(
        features: features,
        text: "IBM is an American multinational technology company headquartered in Armonk, New York, United States, with operations in over 170 countries."
        );
    
    Console.WriteLine(result.Response);
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
      "2022-04-07", authenticator);
    naturalLanguageUnderstanding.setServiceUrl("{url}");
    
    String text = "IBM is an American multinational technology " +
      "company headquartered in Armonk, New York, " +
      "United States, with operations in over 170 countries.";
    
    EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
      .emotion(true)
      .sentiment(true)
      .limit(2)
      .build();
    
    KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
      .emotion(true)
      .sentiment(true)
      .limit(2)
      .build();
    
    Features features = new Features.Builder()
      .entities(entitiesOptions)
      .keywords(keywordsOptions)
      .build();
    
    AnalyzeOptions parameters = new AnalyzeOptions.Builder()
      .text(text)
      .features(features)
      .build();
    
    AnalysisResults response = 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': {
        'entities': {
          'emotion': true,
          'sentiment': true,
          'limit': 2,
        },
        'keywords': {
          'emotion': true,
          'sentiment': true,
          'limit': 2,
        },
      },
    };
    
    naturalLanguageUnderstanding.analyze(analyzeParams)
      .then(analysisResults => {
        console.log(JSON.stringify(analysisResults, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • 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, 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(
        text='IBM is an American multinational technology company '
        'headquartered in Armonk, New York, United States, '
        'with operations in over 170 countries.',
        features=Features(
            entities=EntitiesOptions(emotion=True, sentiment=True, limit=2),
            keywords=KeywordsOptions(emotion=True, sentiment=True,
                                     limit=2))).get_result()
    
    print(json.dumps(response, indent=2))

Response

Results of the analysis, organized by feature

Results of the analysis, organized by feature.

Results of the analysis, organized by feature.

Results of the analysis, organized by feature.

Results of the analysis, organized by feature.

Status Code

  • Analysis results

  • Invalid request

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

List models

Lists Watson Knowledge Studio custom entities and relations models that are deployed to your Natural Language Understanding service.

Lists Watson Knowledge Studio custom entities and relations models that are deployed to your Natural Language Understanding service.

Lists Watson Knowledge Studio custom entities and relations models that are deployed to your Natural Language Understanding service.

Lists Watson Knowledge Studio custom entities and relations models that are deployed to your Natural Language Understanding service.

Lists Watson Knowledge Studio custom entities and relations models that are deployed to your Natural Language Understanding service.

GET /v1/models
ServiceCall<ListModelsResults> listModels(ListModelsOptions listModelsOptions)
listModels(params)
list_models(self,
        **kwargs
    ) -> DetailedResponse
ListModels()

Request

Use the ListModelsOptions.Builder to create a ListModelsOptions object that contains the parameter values for the listModels method.

Query Parameters

  • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

parameters

    parameters

      parameters

        • curl -u "apikey:{apikey}" "{url}/v1/models?version=2022-04-07"
        • IamAuthenticator authenticator = new IamAuthenticator(
              apikey: "{apikey}"
              );
          
          NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
          naturalLanguageUnderstanding.SetServiceUrl("{url}");
          
          var result = naturalLanguageUnderstanding.ListModels();
          
          Console.WriteLine(result.Response);
        • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
          NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
            "2022-04-07", authenticator);
          naturalLanguageUnderstanding.setServiceUrl("{url}");
          
          ListModelsResults models = naturalLanguageUnderstanding
            .listModels()
            .execute()
            .getResult();
          System.out.println(models);
        • 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}',
          });
          
          naturalLanguageUnderstanding.listModels()
            .then(listModelsResults => {
              console.log(JSON.stringify(listModelsResults, null, 2));
            })
            .catch(err => {
              console.log('error:', err);
            });
        • import json
          from ibm_watson import NaturalLanguageUnderstandingV1
          from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
          
          authenticator = IAMAuthenticator('{apikey}')
          natural_language_understanding = NaturalLanguageUnderstandingV1(
              version='2022-04-07',
              authenticator=authenticator)
          
          natural_language_understanding.set_service_url('{url}')
          
          response = natural_language_understanding.list_models().get_result()
          
          print(json.dumps(response, indent=2))

        Response

        Custom models that are available for entities and relations

        Custom models that are available for entities and relations.

        Custom models that are available for entities and relations.

        Custom models that are available for entities and relations.

        Custom models that are available for entities and relations.

        Status Code

        • List models results

        • Invalid request

        Example responses
        • {
            "models": [
              {
                "workspace_id": "504503a0-62c1-12e9-8346-d190294d088d",
                "version_description": "Initial version",
                "model_version": "1.0.1",
                "version": "1.0.1",
                "status": "available",
                "notices": [],
                "name": "MyAdvancedRulesModel",
                "model_id": "2987ca3f-205f-4786-a168-2d8026ddcc9b",
                "language": "en",
                "description": "My custom advanced rules model",
                "created": "2019-04-24T14:50:22Z"
              }
            ]
          }
        • {
            "models": [
              {
                "workspace_id": "504503a0-62c1-12e9-8346-d190294d088d",
                "version_description": "Initial version",
                "model_version": "1.0.1",
                "version": "1.0.1",
                "status": "available",
                "notices": [],
                "name": "MyAdvancedRulesModel",
                "model_id": "2987ca3f-205f-4786-a168-2d8026ddcc9b",
                "language": "en",
                "description": "My custom advanced rules model",
                "created": "2019-04-24T14:50:22Z"
              }
            ]
          }

        Delete model

        Deletes a custom model

        Deletes a custom model.

        Deletes a custom model.

        Deletes a custom model.

        Deletes a custom model.

        DELETE /v1/models/{model_id}
        ServiceCall<DeleteModelResults> deleteModel(DeleteModelOptions deleteModelOptions)
        deleteModel(params)
        delete_model(self,
                model_id: str,
                **kwargs
            ) -> DetailedResponse
        DeleteModel(string modelId)

        Request

        Use the DeleteModelOptions.Builder to create a DeleteModelOptions object that contains the parameter values for the deleteModel method.

        Path Parameters

        • Model ID of the model to delete

        Query Parameters

        • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

        The deleteModel options.

        parameters

        • Model ID of the model to delete.

        parameters

        • Model ID of the model to delete.

        parameters

        • Model ID of the model to delete.

        • curl -X DELETE -u "apikey:{apikey}" "{url}/v1/models/{model_id}?version=2022-04-07"
        • IamAuthenticator authenticator = new IamAuthenticator(
              apikey: "{apikey}"
              );
          
          NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
          naturalLanguageUnderstanding.SetServiceUrl("{url}");
          
          var result = naturalLanguageUnderstanding.DeleteModel(
              modelId: "model_id"
              );
          
          Console.WriteLine(result.Response);
        • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
          NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
            "2022-04-07", authenticator);
          naturalLanguageUnderstanding.setServiceUrl("{url}");
          
          DeleteModelOptions options = new DeleteModelOptions.Builder().modelId("model_id").build();
          naturalLanguageUnderstanding.deleteModel(options).execute();
        • 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 deleteModelParams = {
            'modelId': '{model-id}',
          };
          
          naturalLanguageUnderstanding.deleteModel(deleteModelParams)
            .then(deleteModelResults => {
              console.log(JSON.stringify(deleteModelResults, null, 2));
            })
            .catch(err => {
              console.log('error:', err);
            });
        • import json
          from ibm_watson import NaturalLanguageUnderstandingV1
          from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
          
          authenticator = IAMAuthenticator('{apikey}')
          natural_language_understanding = NaturalLanguageUnderstandingV1(
              version='2022-04-07',
              authenticator=authenticator)
          
          natural_language_understanding.set_service_url('{url}')
          
          response = natural_language_understanding.delete_model(
              model_id='model_id').get_result()
          
          print(json.dumps(response, indent=2))

        Response

        Delete model results.

        Delete model results.

        Delete model results.

        Delete model results.

        Status Code

        • Delete model results

        • Invalid request

        Example responses
        • {
            "deleted": "2987ca3f-205f-4786-a168-2d8026ddcc9b"
          }
        • {
            "deleted": "2987ca3f-205f-4786-a168-2d8026ddcc9b"
          }

        Create categories model

        (Beta) Creates a custom categories model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

        (Beta) Creates a custom categories model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

        (Beta) Creates a custom categories model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

        (Beta) Creates a custom categories model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

        (Beta) Creates a custom categories model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

        POST /v1/models/categories
        ServiceCall<CategoriesModel> createCategoriesModel(CreateCategoriesModelOptions createCategoriesModelOptions)
        createCategoriesModel(params)
        create_categories_model(self,
                language: str,
                training_data: BinaryIO,
                *,
                training_data_content_type: str = None,
                name: str = None,
                description: str = None,
                model_version: str = None,
                workspace_id: str = None,
                version_description: str = None,
                **kwargs
            ) -> DetailedResponse
        CreateCategoriesModel(string language, System.IO.MemoryStream trainingData, string trainingDataContentType = null, string name = null, string description = null, string modelVersion = null, string workspaceId = null, string versionDescription = null)

        Request

        Use the CreateCategoriesModelOptions.Builder to create a CreateCategoriesModelOptions object that contains the parameter values for the createCategoriesModel method.

        Query Parameters

        • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

        Form Parameters

        • The 2-letter language code of this model

        • Training data in JSON format. For more information, see Categories training data requirements.

        • An optional name for the model

        • An optional map of metadata key-value pairs to store with this model

          Examples:
          View
        • An optional description of the model

        • An optional version string

        • Deprecated — use model_version

        • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding

        • The description of the version

        The createCategoriesModel options.

        parameters

        • The 2-letter language code of this model.

        • Training data in JSON format. For more information, see Categories training data requirements.

        • The content type of trainingData.

          Allowable values: [json,application/json]

        • An optional name for the model.

        • An optional description of the model.

        • An optional version string.

        • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

        • The description of the version.

        parameters

        • The 2-letter language code of this model.

        • Training data in JSON format. For more information, see Categories training data requirements.

        • The content type of training_data.

          Allowable values: [json,application/json]

        • An optional name for the model.

        • An optional description of the model.

        • An optional version string.

        • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

        • The description of the version.

        parameters

        • The 2-letter language code of this model.

        • Training data in JSON format. For more information, see Categories training data requirements.

        • The content type of trainingData.

          Allowable values: [json,application/json]

        • An optional name for the model.

        • An optional description of the model.

        • An optional version string.

        • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

        • The description of the version.

        • curl -X POST -u "apikey:{apikey}" -H "Content-Type: multipart/form-data" -F "training_data=@categories_data.json;type=application/json" -F "language=en" -F "name=MyCategoriesModel" -F "model_version=1.0.1" "{url}/v1/models/categories?version=2022-04-07"
        • IamAuthenticator authenticator = new IamAuthenticator(
              apikey: "{apikey}"
              );
          
          NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
          naturalLanguageUnderstanding.SetServiceUrl("{url}");
          
          var result = naturalLanguageUnderstanding.CreateCategoriesModel(
              language: "en",
              trainingData: new MemoryStream(File.ReadAllBytes("trainingData.json")),
              trainingDataContentType: NaturalLanguageUnderstandingService.CreateCategoriesModelEnums.TrainingDataContentTypeValue.APPLICATION_JSON,
              name: "MyCategoriesModel",
              modelVersion: "1.0.1"
              );
          
          Console.WriteLine(result.Response);
        • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
          NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
            "2022-04-07", authenticator);
          naturalLanguageUnderstanding.setServiceUrl("{url}");
          
          try {
            CreateCategoriesModelOptions createCategoriesModelOptions = new CreateCategoriesModelOptions.Builder()
              .language("en")
              .trainingData(new FileInputStream("trainingData.json"))
              .trainingDataContentType("application/json")
              .name("testString")
              .description("testString")
              .modelVersion("testString")
              .versionDescription("testString")
              .build();
          
            CategoriesModel response = naturalLanguageUnderstanding.createCategoriesModel(createCategoriesModelOptions).execute().getResult();
          
            System.out.println(response);
          } catch (FileNotFoundException e) {
            e.printStackTrace();
          }
        • const fs = require('fs');
          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 createCategoriesModelParams = {
            language: 'en',
            trainingData: fs.createReadStream('./categories_data.json'),
            name: 'MyCategoriesModel',
            modelVersion: '1.0.1'
          };
          
          naturalLanguageUnderstanding.createCategoriesModel(createCategoriesModelParams)
            .then(createCategoriesModelResults => {
              console.log(JSON.stringify(createCategoriesModelResults, null, 2));
            })
            .catch(err => {
              console.log('error:', err);
            });
        • from os.path import join, dirname
          from ibm_watson import NaturalLanguageUnderstandingV1
          from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
          
          authenticator = IAMAuthenticator('{apikey}')
          natural_language_understanding = NaturalLanguageUnderstandingV1(
              version='2022-04-07',
              authenticator=authenticator
          )
          
          natural_language_understanding.set_service_url('{url}')
          
          with open(join(dirname(__file__), './.', 'categories_data.json'),
                         'rb') as file:
              model=natural_language_understanding.create_categories_model(
                  language='en',
                  training_data=file
                  name='MyCategoriesModel',
                  model_version='1.0.1',
              ).get_result()
              print(json.dumps(model, indent=2))

        Response

        Categories model

        Categories model.

        Categories model.

        Categories model.

        Categories model.

        Status Code

        • Model created successfully

        • Invalid request

        • Access forbidden

        Example responses
        • {
            "name": "MyCategoriesModel",
            "language": "en",
            "model_version": "1.0.1",
            "status": "training",
            "notices": [],
            "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
            "features": [
              "categories"
            ],
            "created": "2020-04-10T19:32:42Z",
            "last_trained": "2020-04-10T19:32:42Z",
            "last_deployed": "2020-04-10T19:32:42Z"
          }
        • {
            "name": "MyCategoriesModel",
            "language": "en",
            "model_version": "1.0.1",
            "status": "training",
            "notices": [],
            "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
            "features": [
              "categories"
            ],
            "created": "2020-04-10T19:32:42Z",
            "last_trained": "2020-04-10T19:32:42Z",
            "last_deployed": "2020-04-10T19:32:42Z"
          }

        List categories models

        (Beta) Returns all custom categories models associated with this service instance.

        (Beta) Returns all custom categories models associated with this service instance.

        (Beta) Returns all custom categories models associated with this service instance.

        (Beta) Returns all custom categories models associated with this service instance.

        (Beta) Returns all custom categories models associated with this service instance.

        GET /v1/models/categories
        ServiceCall<CategoriesModelList> listCategoriesModels(ListCategoriesModelsOptions listCategoriesModelsOptions)
        listCategoriesModels(params)
        list_categories_models(self,
                **kwargs
            ) -> DetailedResponse
        ListCategoriesModels()

        Request

        Use the ListCategoriesModelsOptions.Builder to create a ListCategoriesModelsOptions object that contains the parameter values for the listCategoriesModels method.

        Query Parameters

        • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

        parameters

          parameters

            parameters

              • curl -u "apikey:{apikey}" "{url}/v1/models/categories?version=2022-04-07"
              • IamAuthenticator authenticator = new IamAuthenticator(
                    apikey: "{apikey}"
                    );
                
                NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                naturalLanguageUnderstanding.SetServiceUrl("{url}");
                
                var result = naturalLanguageUnderstanding.ListCategoriesModels();
                
                Console.WriteLine(result.Response);
              • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                  "2022-04-07", authenticator);
                naturalLanguageUnderstanding.setServiceUrl("{url}");
                
                CategoriesModelList response = naturalLanguageUnderstanding.listCategoriesModels().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}',
                });
                
                naturalLanguageUnderstanding.listCategoriesModels()
                  .then(listCategoriesModelsResults => {
                    console.log(JSON.stringify(listCategoriesModelsResults, null, 2));
                  })
                  .catch(err => {
                    console.log('error:', err);
                  });
              • import json
                from ibm_watson import NaturalLanguageUnderstandingV1
                from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                
                authenticator = IAMAuthenticator('{apikey}')
                natural_language_understanding = NaturalLanguageUnderstandingV1(
                    version='2022-04-07',
                    authenticator=authenticator)
                
                natural_language_understanding.set_service_url('{url}')
                
                models = natural_language_understanding.list_categories_models().get_result()
                
                print(json.dumps(models, indent=2))

              Response

              List of categories models.

              List of categories models.

              List of categories models.

              List of categories models.

              List of categories models.

              Status Code

              • Models retrieved

              • Invalid request

              • Access forbidden

              Example responses
              • {
                  "models": [
                    {
                      "name": "MyCategoriesModel",
                      "language": "en",
                      "model_version": "1.0.1",
                      "status": "available",
                      "notices": [],
                      "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                      "features": [
                        "categories"
                      ],
                      "created": "2020-04-10T19:32:42Z",
                      "last_trained": "2020-04-10T19:32:42Z",
                      "last_deployed": "2020-04-10T19:32:42Z"
                    }
                  ]
                }
              • {
                  "models": [
                    {
                      "name": "MyCategoriesModel",
                      "language": "en",
                      "model_version": "1.0.1",
                      "status": "available",
                      "notices": [],
                      "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                      "features": [
                        "categories"
                      ],
                      "created": "2020-04-10T19:32:42Z",
                      "last_trained": "2020-04-10T19:32:42Z",
                      "last_deployed": "2020-04-10T19:32:42Z"
                    }
                  ]
                }

              Get categories model details

              (Beta) Returns the status of the categories model with the given model ID.

              (Beta) Returns the status of the categories model with the given model ID.

              (Beta) Returns the status of the categories model with the given model ID.

              (Beta) Returns the status of the categories model with the given model ID.

              (Beta) Returns the status of the categories model with the given model ID.

              GET /v1/models/categories/{model_id}
              ServiceCall<CategoriesModel> getCategoriesModel(GetCategoriesModelOptions getCategoriesModelOptions)
              getCategoriesModel(params)
              get_categories_model(self,
                      model_id: str,
                      **kwargs
                  ) -> DetailedResponse
              GetCategoriesModel(string modelId)

              Request

              Use the GetCategoriesModelOptions.Builder to create a GetCategoriesModelOptions object that contains the parameter values for the getCategoriesModel method.

              Path Parameters

              • ID of the model

              Query Parameters

              • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

              The getCategoriesModel options.

              parameters

              • ID of the model.

              parameters

              • ID of the model.

              parameters

              • ID of the model.

              • curl -u "apikey:{apikey}" "{url}/v1/models/categories/{model_id}?version=2022-04-07"
              • IamAuthenticator authenticator = new IamAuthenticator(
                    apikey: "{apikey}"
                    );
                
                NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                naturalLanguageUnderstanding.SetServiceUrl("{url}");
                
                var result = naturalLanguageUnderstanding.GetCategoriesModel(
                    modelId: "{modelId}"
                    );
                
                Console.WriteLine(result.Response);
              • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                  "2022-04-07", authenticator);
                naturalLanguageUnderstanding.setServiceUrl("{url}");
                
                GetCategoriesModelOptions getCategoriesModelOptions = new GetCategoriesModelOptions.Builder()
                  .modelId("{modelId}")
                  .build();
                
                CategoriesModel response = naturalLanguageUnderstanding.getCategoriesModel(getCategoriesModelOptions).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 getCategoriesModelParams = {
                  modelId: '{model_id}',
                };
                
                naturalLanguageUnderstanding.getCategoriesModel(getCategoriesModelParams)
                  .then(getCategoriesModelResults => {
                    console.log(JSON.stringify(getCategoriesModelResults, null, 2));
                  })
                  .catch(err => {
                    console.log('error:', err);
                  });
              • import json
                from ibm_watson import NaturalLanguageUnderstandingV1
                from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                
                authenticator = IAMAuthenticator('{apikey}')
                natural_language_understanding = NaturalLanguageUnderstandingV1(
                    version='2022-04-07',
                    authenticator=authenticator)
                
                natural_language_understanding.set_service_url('{url}')
                
                model = natural_language_understanding.get_categories_model(
                  model_id='{model_id}',
                ).get_result()
                
                
                print(json.dumps(model, indent=2))

              Response

              Categories model

              Categories model.

              Categories model.

              Categories model.

              Categories model.

              Status Code

              • Model retrieved

              • Invalid request

              • Access forbidden

              Example responses
              • {
                  "name": "MyCategoriesModel",
                  "language": "en",
                  "model_version": "1.0.1",
                  "status": "available",
                  "notices": [],
                  "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                  "features": [
                    "categories"
                  ],
                  "created": "2020-04-10T19:32:42Z",
                  "last_trained": "2020-04-10T19:32:42Z",
                  "last_deployed": "2020-04-10T19:32:42Z"
                }
              • {
                  "name": "MyCategoriesModel",
                  "language": "en",
                  "model_version": "1.0.1",
                  "status": "available",
                  "notices": [],
                  "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                  "features": [
                    "categories"
                  ],
                  "created": "2020-04-10T19:32:42Z",
                  "last_trained": "2020-04-10T19:32:42Z",
                  "last_deployed": "2020-04-10T19:32:42Z"
                }

              Update categories model

              (Beta) Overwrites the training data associated with this custom categories model and retrains the model. The new model replaces the current deployment.

              (Beta) Overwrites the training data associated with this custom categories model and retrains the model. The new model replaces the current deployment.

              (Beta) Overwrites the training data associated with this custom categories model and retrains the model. The new model replaces the current deployment.

              (Beta) Overwrites the training data associated with this custom categories model and retrains the model. The new model replaces the current deployment.

              (Beta) Overwrites the training data associated with this custom categories model and retrains the model. The new model replaces the current deployment.

              PUT /v1/models/categories/{model_id}
              ServiceCall<CategoriesModel> updateCategoriesModel(UpdateCategoriesModelOptions updateCategoriesModelOptions)
              updateCategoriesModel(params)
              update_categories_model(self,
                      model_id: str,
                      language: str,
                      training_data: BinaryIO,
                      *,
                      training_data_content_type: str = None,
                      name: str = None,
                      description: str = None,
                      model_version: str = None,
                      workspace_id: str = None,
                      version_description: str = None,
                      **kwargs
                  ) -> DetailedResponse
              UpdateCategoriesModel(string modelId, string language, System.IO.MemoryStream trainingData, string trainingDataContentType = null, string name = null, string description = null, string modelVersion = null, string workspaceId = null, string versionDescription = null)

              Request

              Use the UpdateCategoriesModelOptions.Builder to create a UpdateCategoriesModelOptions object that contains the parameter values for the updateCategoriesModel method.

              Path Parameters

              • ID of the model

              Query Parameters

              • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

              Form Parameters

              • The 2-letter language code of this model

              • Training data in JSON format. For more information, see Categories training data requirements.

              • An optional name for the model

              • An optional map of metadata key-value pairs to store with this model

                Examples:
                View
              • An optional description of the model

              • An optional version string

              • Deprecated — use model_version

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding

              • The description of the version

              The updateCategoriesModel options.

              parameters

              • ID of the model.

              • The 2-letter language code of this model.

              • Training data in JSON format. For more information, see Categories training data requirements.

              • The content type of trainingData.

                Allowable values: [json,application/json]

              • An optional name for the model.

              • An optional description of the model.

              • An optional version string.

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

              • The description of the version.

              parameters

              • ID of the model.

              • The 2-letter language code of this model.

              • Training data in JSON format. For more information, see Categories training data requirements.

              • The content type of training_data.

                Allowable values: [json,application/json]

              • An optional name for the model.

              • An optional description of the model.

              • An optional version string.

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

              • The description of the version.

              parameters

              • ID of the model.

              • The 2-letter language code of this model.

              • Training data in JSON format. For more information, see Categories training data requirements.

              • The content type of trainingData.

                Allowable values: [json,application/json]

              • An optional name for the model.

              • An optional description of the model.

              • An optional version string.

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

              • The description of the version.

              • curl -X PUT -u "apikey:{apikey}" -H "Content-Type: multipart/form-data" -F "training_data=@categories_model.json;type=application/json" -F "language=en" -F "name=MyCategoriesModel" -F "description=My updated categories model" -F "model_version=1.0.1" -F "version_description=Updated version" "{url}/v1/models/categories/{model_id}?version=2022-04-07"
              • IamAuthenticator authenticator = new IamAuthenticator(
                    apikey: "{apikey}"
                    );
                
                NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                naturalLanguageUnderstanding.SetServiceUrl("{url}");
                
                var result = naturalLanguageUnderstanding.UpdateCategoriesModel(
                    modelId: "{modelId}",
                    trainingData: new MemoryStream(File.ReadAllBytes("trainingData.json")),
                    language: "en",
                    name: "MyCategoriesModel",
                    description: "My updated categories model",
                    modelVersion: "1.0.1",
                    versionDescription: "Updated version"
                    );
                
                Console.WriteLine(result.Response);
              • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                  "2022-04-07", authenticator);
                naturalLanguageUnderstanding.setServiceUrl("{url}");
                
                try {
                  UpdateCategoriesModelOptions updateCategoriesModelOptions = new UpdateCategoriesModelOptions.Builder()
                    .language("en")
                    .trainingData(new FileInputStream("trainingData.json"))
                    .trainingDataContentType("application/json")
                    .name("newName")
                    .description("newDescription")
                    .modelVersion("testString")
                    .versionDescription("testString")
                    .modelId("{modelId}")
                    .build();
                
                  CategoriesModel response = naturalLanguageUnderstanding.updateCategoriesModel(updateCategoriesModelOptions).execute().getResult();
                
                  System.out.println(response);
                } catch (FileNotFoundException e) {
                  e.printStackTrace();
                }
              • const fs = require('fs');
                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 updateCategoriesModelParams = {
                  language: 'en',
                  trainingData: fs.createReadStream('./categories_model.json'),
                  name: 'MyCategoriesModel',
                  description: 'My updated categories model',
                  modelVersion: '1.0.1',
                  versionDescription: 'Updated version',
                  modelId: '{model_id}'
                };
                
                naturalLanguageUnderstanding.updateCategoriesModel(updateCategoriesModelParams)
                  .then(updateCategoriesModelResults => {
                    console.log(JSON.stringify(updateCategoriesModelResults, null, 2));
                  })
                  .catch(err => {
                    console.log('error:', err);
                  });
              • from os.path import join, dirname
                from ibm_watson import NaturalLanguageUnderstandingV1
                from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                
                authenticator = IAMAuthenticator('{apikey}')
                natural_language_understanding = NaturalLanguageUnderstandingV1(
                    version='2022-04-07',
                    authenticator=authenticator
                )
                
                natural_language_understanding.set_service_url('{url}')
                
                with open(join(dirname(__file__), './.', 'categories_model.json'),
                               'rb') as file:
                    model=natural_language_understanding.update_categories_model(
                        language='en',
                        training_data=file
                        name='MyCategoriesModel',
                        description='My updated categories model',
                        model_version='1.0.1',
                        version_description='Updated version',
                        model_id='{model_id}'
                    ).get_result()
                    print(json.dumps(model, indent=2))

              Response

              Categories model

              Categories model.

              Categories model.

              Categories model.

              Categories model.

              Status Code

              • Model overwrite successful

              • Invalid request

              • Access forbidden

              Example responses
              • {
                  "models": [
                    {
                      "name": "MyCategoriesModel",
                      "language": "en",
                      "model_version": "1.0.1",
                      "status": "deploying",
                      "notices": [],
                      "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                      "features": [
                        "categories"
                      ],
                      "created": "2020-04-10T20:21:46Z",
                      "last_trained": "2020-04-10T20:21:46Z",
                      "last_deployed": "2020-04-10T20:21:46Z"
                    }
                  ]
                }
              • {
                  "models": [
                    {
                      "name": "MyCategoriesModel",
                      "language": "en",
                      "model_version": "1.0.1",
                      "status": "deploying",
                      "notices": [],
                      "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                      "features": [
                        "categories"
                      ],
                      "created": "2020-04-10T20:21:46Z",
                      "last_trained": "2020-04-10T20:21:46Z",
                      "last_deployed": "2020-04-10T20:21:46Z"
                    }
                  ]
                }

              Delete categories model

              (Beta) Un-deploys the custom categories model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

              (Beta) Un-deploys the custom categories model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

              (Beta) Un-deploys the custom categories model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

              (Beta) Un-deploys the custom categories model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

              (Beta) Un-deploys the custom categories model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

              DELETE /v1/models/categories/{model_id}
              ServiceCall<DeleteModelResults> deleteCategoriesModel(DeleteCategoriesModelOptions deleteCategoriesModelOptions)
              deleteCategoriesModel(params)
              delete_categories_model(self,
                      model_id: str,
                      **kwargs
                  ) -> DetailedResponse
              DeleteCategoriesModel(string modelId)

              Request

              Use the DeleteCategoriesModelOptions.Builder to create a DeleteCategoriesModelOptions object that contains the parameter values for the deleteCategoriesModel method.

              Path Parameters

              • ID of the model

              Query Parameters

              • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

              The deleteCategoriesModel options.

              parameters

              • ID of the model.

              parameters

              • ID of the model.

              parameters

              • ID of the model.

              • curl -X DELETE -u "apikey:{apikey}" "{url}/v1/models/categories/{model_id}?version=2022-04-07"
              • IamAuthenticator authenticator = new IamAuthenticator(
                    apikey: "{apikey}"
                    );
                
                NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                naturalLanguageUnderstanding.SetServiceUrl("{url}");
                
                var result = naturalLanguageUnderstanding.DeleteCategoriesModel(
                    modelId: "{modelId}"
                    );
                
                Console.WriteLine(result.Response);
              • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                  "2022-04-07", authenticator);
                naturalLanguageUnderstanding.setServiceUrl("{url}");
                
                DeleteCategoriesModelOptions deleteCategoriesModelOptions = new DeleteCategoriesModelOptions.Builder()
                  .modelId("{modelId}")
                  .build();
                
                DeleteModelResults response = naturalLanguageUnderstanding.deleteCategoriesModel(deleteCategoriesModelOptions).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 deleteCategoriesModelParams = {
                  modelId: '{model_id}',
                };
                
                naturalLanguageUnderstanding.deleteCategoriesModel(deleteCategoriesModelParams)
                  .then(deleteCategoriesModelResults => {
                    console.log(JSON.stringify(deleteCategoriesModelResults, null, 2));
                  })
                  .catch(err => {
                    console.log('error:', err);
                  });
              • import json
                from ibm_watson import NaturalLanguageUnderstandingV1
                from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                
                authenticator = IAMAuthenticator('{apikey}')
                natural_language_understanding = NaturalLanguageUnderstandingV1(
                    version='2022-04-07',
                    authenticator=authenticator)
                
                natural_language_understanding.set_service_url('{url}')
                
                model = natural_language_understanding.delete_categories_model(
                  model_id='{model_id}',
                ).get_result()
                
                
                print(json.dumps(model, indent=2))

              Response

              Delete model results.

              Delete model results.

              Delete model results.

              Delete model results.

              Status Code

              • Delete model results

              • Invalid request

              • Access forbidden

              Example responses
              • {
                  "deleted": "2987ca3f-205f-4786-a168-2d8026ddcc9b"
                }
              • {
                  "deleted": "2987ca3f-205f-4786-a168-2d8026ddcc9b"
                }

              Create classifications model

              Creates a custom classifications model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

              Creates a custom classifications model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

              Creates a custom classifications model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

              Creates a custom classifications model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

              Creates a custom classifications model by uploading training data and associated metadata. The model begins the training and deploying process and is ready to use when the status is available.

              POST /v1/models/classifications
              ServiceCall<ClassificationsModel> createClassificationsModel(CreateClassificationsModelOptions createClassificationsModelOptions)
              createClassificationsModel(params)
              create_classifications_model(self,
                      language: str,
                      training_data: BinaryIO,
                      *,
                      training_data_content_type: str = None,
                      name: str = None,
                      description: str = None,
                      model_version: str = None,
                      workspace_id: str = None,
                      version_description: str = None,
                      training_parameters: 'ClassificationsTrainingParameters' = None,
                      **kwargs
                  ) -> DetailedResponse
              CreateClassificationsModel(string language, System.IO.MemoryStream trainingData, string trainingDataContentType = null, string name = null, string description = null, string modelVersion = null, string workspaceId = null, string versionDescription = null, ClassificationsTrainingParameters trainingParameters = null)

              Request

              Use the CreateClassificationsModelOptions.Builder to create a CreateClassificationsModelOptions object that contains the parameter values for the createClassificationsModel method.

              Query Parameters

              • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

              Form Parameters

              • The 2-letter language code of this model

              • Training data in JSON format. For more information, see Classifications training data requirements.

              • An optional name for the model

              • An optional map of metadata key-value pairs to store with this model

                Examples:
                View
              • An optional description of the model

              • An optional version string

              • Deprecated — use model_version

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding

              • The description of the version

              • Optional classifications training parameters along with model train requests

              The createClassificationsModel options.

              parameters

              • The 2-letter language code of this model.

              • Training data in JSON format. For more information, see Classifications training data requirements.

              • The content type of trainingData.

                Allowable values: [json,application/json]

              • An optional name for the model.

              • An optional description of the model.

              • An optional version string.

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

              • The description of the version.

              • Optional classifications training parameters along with model train requests.

              parameters

              • The 2-letter language code of this model.

              • Training data in JSON format. For more information, see Classifications training data requirements.

              • The content type of training_data.

                Allowable values: [json,application/json]

              • An optional name for the model.

              • An optional description of the model.

              • An optional version string.

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

              • The description of the version.

              • Optional classifications training parameters along with model train requests.

              parameters

              • The 2-letter language code of this model.

              • Training data in JSON format. For more information, see Classifications training data requirements.

              • The content type of trainingData.

                Allowable values: [json,application/json]

              • An optional name for the model.

              • An optional description of the model.

              • An optional version string.

              • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

              • The description of the version.

              • Optional classifications training parameters along with model train requests.

              • curl -X POST -u "apikey:{apikey}" -H "Content-Type: multipart/form-data" -F "training_data=@classifications_data.json;type=application/json" -F "language=en" -F "name=MyClassificationsModel" -F "model_version=1.0.1" "{url}/v1/models/classifications?version=2022-04-07"
              • IamAuthenticator authenticator = new IamAuthenticator(
                    apikey: "{apikey}"
                    );
                
                NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                naturalLanguageUnderstanding.SetServiceUrl("{url}");
                
                var result = naturalLanguageUnderstanding.CreateClassificationsModel(
                    trainingData: new MemoryStream(File.ReadAllBytes("trainingData.json")),
                    trainingDataContentType: NaturalLanguageUnderstandingService.CreateClassificationsModelEnums.TrainingDataContentTypeValue.APPLICATION_JSON,
                    language: "en",
                    name: "MyClassificationsModel",
                    modelVersion: "1.0.1"
                    );
                
                Console.WriteLine(result.Response);
              • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                  "2022-04-07", authenticator);
                naturalLanguageUnderstanding.setServiceUrl("{url}");
                
                try {
                  CreateClassificationsModelOptions createClassificationsModelOptions = new CreateClassificationsModelOptions.Builder()
                    .language("en")
                    .trainingData(new FileInputStream("trainingData.json"))
                    .trainingDataContentType("application/json")
                    .name("testString")
                    .description("testString")
                    .modelVersion("testString")
                    .versionDescription("testString")
                    .build();
                
                  ClassificationsModel response = naturalLanguageUnderstanding.createClassificationsModel(createClassificationsModelOptions).execute().getResult();
                
                  System.out.println(response);
                } catch (FileNotFoundException e) {
                  e.printStackTrace();
                }
              • const fs = require('fs');
                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 createClassificationsModelParams = {
                  language: 'en',
                  trainingData: fs.createReadStream('./classifications_data.json'),
                  name: 'MyClassificationsModel',
                  modelVersion: '1.0.1',
                };
                
                naturalLanguageUnderstanding.createClassificationsModel(createClassificationsModelParams)
                  .then(createClassificationsModelResults => {
                    console.log(JSON.stringify(createClassificationsModelResults, null, 2));
                  })
                  .catch(err => {
                    console.log('error:', err);
                  });
              • from os.path import join, dirname
                from ibm_watson import NaturalLanguageUnderstandingV1
                from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                
                authenticator = IAMAuthenticator('{apikey}')
                natural_language_understanding = NaturalLanguageUnderstandingV1(
                    version='2022-04-07',
                    authenticator=authenticator
                )
                
                natural_language_understanding.set_service_url('{url}')
                
                with open(join(dirname(__file__), './.', 'classifications_data.json'),
                               'rb') as file:
                    model=natural_language_understanding.create_classifications_model(
                        language='en',
                        training_data=file
                        name='MyClassificationsModel',
                        model_version='1.0.1',
                    ).get_result()
                    print(json.dumps(model, indent=2))

              Response

              Classifications model

              Classifications model.

              Classifications model.

              Classifications model.

              Classifications model.

              Status Code

              • Model created successfully

              • Invalid request

              • Access forbidden

              Example responses
              • {
                  "name": "MyClassificationsModel",
                  "language": "en",
                  "model_version": "1.0.1",
                  "status": "training",
                  "notices": [],
                  "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                  "features": [
                    "classifications"
                  ],
                  "created": "2020-04-10T19:32:42Z",
                  "last_trained": "2020-04-10T19:32:42Z",
                  "last_deployed": "2020-04-10T19:32:42Z"
                }
              • {
                  "name": "MyClassificationsModel",
                  "language": "en",
                  "model_version": "1.0.1",
                  "status": "training",
                  "notices": [],
                  "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                  "features": [
                    "classifications"
                  ],
                  "created": "2020-04-10T19:32:42Z",
                  "last_trained": "2020-04-10T19:32:42Z",
                  "last_deployed": "2020-04-10T19:32:42Z"
                }

              List classifications models

              Returns all custom classifications models associated with this service instance.

              Returns all custom classifications models associated with this service instance.

              Returns all custom classifications models associated with this service instance.

              Returns all custom classifications models associated with this service instance.

              Returns all custom classifications models associated with this service instance.

              GET /v1/models/classifications
              ServiceCall<ClassificationsModelList> listClassificationsModels(ListClassificationsModelsOptions listClassificationsModelsOptions)
              listClassificationsModels(params)
              list_classifications_models(self,
                      **kwargs
                  ) -> DetailedResponse
              ListClassificationsModels()

              Request

              Use the ListClassificationsModelsOptions.Builder to create a ListClassificationsModelsOptions object that contains the parameter values for the listClassificationsModels method.

              Query Parameters

              • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

              parameters

                parameters

                  parameters

                    • curl -u "apikey:{apikey}" "{url}/v1/models/classifications?version=2022-04-07"
                    • IamAuthenticator authenticator = new IamAuthenticator(
                          apikey: "{apikey}"
                          );
                      
                      NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                      naturalLanguageUnderstanding.SetServiceUrl("{url}");
                      
                      var result = naturalLanguageUnderstanding.ListClassificationsModels();
                      
                      Console.WriteLine(result.Response);
                    • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                      NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                        "2022-04-07", authenticator);
                      naturalLanguageUnderstanding.setServiceUrl("{url}");
                      
                      ListClassificationsModelsResponse response = naturalLanguageUnderstanding.listClassificationsModels().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}',
                      });
                      
                      naturalLanguageUnderstanding.listClassificationsModels()
                        .then(listClassificationsModelsResults => {
                          console.log(JSON.stringify(listClassificationsModelsResults, null, 2));
                        })
                        .catch(err => {
                          console.log('error:', err);
                        });
                    • import json
                      from ibm_watson import NaturalLanguageUnderstandingV1
                      from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                      
                      authenticator = IAMAuthenticator('{apikey}')
                      natural_language_understanding = NaturalLanguageUnderstandingV1(
                          version='2022-04-07',
                          authenticator=authenticator)
                      
                      natural_language_understanding.set_service_url('{url}')
                      
                      models = natural_language_understanding.list_classifications_models().get_result()
                      
                      print(json.dumps(models, indent=2))

                    Response

                    List of classifications models.

                    List of classifications models.

                    List of classifications models.

                    List of classifications models.

                    List of classifications models.

                    Status Code

                    • Models retrieved

                    • Invalid request

                    • Access forbidden

                    Example responses
                    • {
                        "models": [
                          {
                            "name": "MyClassificationsModel",
                            "language": "en",
                            "model_version": "1.0.1",
                            "status": "available",
                            "notices": [],
                            "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                            "features": [
                              "classifications"
                            ],
                            "created": "2020-04-10T19:32:42Z",
                            "last_trained": "2020-04-10T19:32:42Z",
                            "last_deployed": "2020-04-10T19:32:42Z"
                          }
                        ]
                      }
                    • {
                        "models": [
                          {
                            "name": "MyClassificationsModel",
                            "language": "en",
                            "model_version": "1.0.1",
                            "status": "available",
                            "notices": [],
                            "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                            "features": [
                              "classifications"
                            ],
                            "created": "2020-04-10T19:32:42Z",
                            "last_trained": "2020-04-10T19:32:42Z",
                            "last_deployed": "2020-04-10T19:32:42Z"
                          }
                        ]
                      }

                    Get classifications model details

                    Returns the status of the classifications model with the given model ID.

                    Returns the status of the classifications model with the given model ID.

                    Returns the status of the classifications model with the given model ID.

                    Returns the status of the classifications model with the given model ID.

                    Returns the status of the classifications model with the given model ID.

                    GET /v1/models/classifications/{model_id}
                    ServiceCall<ClassificationsModel> getClassificationsModel(GetClassificationsModelOptions getClassificationsModelOptions)
                    getClassificationsModel(params)
                    get_classifications_model(self,
                            model_id: str,
                            **kwargs
                        ) -> DetailedResponse
                    GetClassificationsModel(string modelId)

                    Request

                    Use the GetClassificationsModelOptions.Builder to create a GetClassificationsModelOptions object that contains the parameter values for the getClassificationsModel method.

                    Path Parameters

                    • ID of the model

                    Query Parameters

                    • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

                    The getClassificationsModel options.

                    parameters

                    • ID of the model.

                    parameters

                    • ID of the model.

                    parameters

                    • ID of the model.

                    • curl -u "apikey:{apikey}" "{url}/v1/models/classifications/{model_id}?version=2022-04-07"
                    • IamAuthenticator authenticator = new IamAuthenticator(
                          apikey: "{apikey}"
                          );
                      
                      NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                      naturalLanguageUnderstanding.SetServiceUrl("{url}");
                      
                      var result = naturalLanguageUnderstanding.GetClassificationsModel(
                          modelId: "{modelId}"
                          );
                      
                      Console.WriteLine(result.Response);
                    • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                      NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                        "2022-04-07", authenticator);
                      naturalLanguageUnderstanding.setServiceUrl("{url}");
                      
                      GetClassificationsModelOptions getClassificationsModelOptions = new GetClassificationsModelOptions.Builder()
                        .modelId("{modelId}")
                        .build();
                      
                      ClassificationsModel response = naturalLanguageUnderstanding.getClassificationsModel(getClassificationsModelOptions).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 getClassificationsModelParams = {
                        modelId: '{model_id}',
                      };
                      
                      naturalLanguageUnderstanding.getClassificationsModel(getClassificationsModelParams)
                        .then(getClassificationsModelResults => {
                          console.log(JSON.stringify(getClassificationsModelResults, null, 2));
                        })
                        .catch(err => {
                          console.log('error:', err);
                        });
                    • import json
                      from ibm_watson import NaturalLanguageUnderstandingV1
                      from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                      
                      authenticator = IAMAuthenticator('{apikey}')
                      natural_language_understanding = NaturalLanguageUnderstandingV1(
                          version='2022-04-07',
                          authenticator=authenticator)
                      
                      natural_language_understanding.set_service_url('{url}')
                      
                      model = natural_language_understanding.get_classifications_model(
                        model_id='{model_id}',
                      ).get_result()
                      
                      
                      print(json.dumps(model, indent=2))

                    Response

                    Classifications model

                    Classifications model.

                    Classifications model.

                    Classifications model.

                    Classifications model.

                    Status Code

                    • Model retrieved

                    • Invalid request

                    • Access forbidden

                    Example responses
                    • {
                        "name": "MyClassificationsModel",
                        "language": "en",
                        "model_version": "1.0.1",
                        "status": "available",
                        "notices": [],
                        "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                        "features": [
                          "classifications"
                        ],
                        "created": "2020-04-10T19:32:42Z",
                        "last_trained": "2020-04-10T19:32:42Z",
                        "last_deployed": "2020-04-10T19:32:42Z"
                      }
                    • {
                        "name": "MyClassificationsModel",
                        "language": "en",
                        "model_version": "1.0.1",
                        "status": "available",
                        "notices": [],
                        "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                        "features": [
                          "classifications"
                        ],
                        "created": "2020-04-10T19:32:42Z",
                        "last_trained": "2020-04-10T19:32:42Z",
                        "last_deployed": "2020-04-10T19:32:42Z"
                      }

                    Update classifications model

                    Overwrites the training data associated with this custom classifications model and retrains the model. The new model replaces the current deployment.

                    Overwrites the training data associated with this custom classifications model and retrains the model. The new model replaces the current deployment.

                    Overwrites the training data associated with this custom classifications model and retrains the model. The new model replaces the current deployment.

                    Overwrites the training data associated with this custom classifications model and retrains the model. The new model replaces the current deployment.

                    Overwrites the training data associated with this custom classifications model and retrains the model. The new model replaces the current deployment.

                    PUT /v1/models/classifications/{model_id}
                    ServiceCall<ClassificationsModel> updateClassificationsModel(UpdateClassificationsModelOptions updateClassificationsModelOptions)
                    updateClassificationsModel(params)
                    update_classifications_model(self,
                            model_id: str,
                            language: str,
                            training_data: BinaryIO,
                            *,
                            training_data_content_type: str = None,
                            name: str = None,
                            description: str = None,
                            model_version: str = None,
                            workspace_id: str = None,
                            version_description: str = None,
                            training_parameters: 'ClassificationsTrainingParameters' = None,
                            **kwargs
                        ) -> DetailedResponse
                    UpdateClassificationsModel(string modelId, string language, System.IO.MemoryStream trainingData, string trainingDataContentType = null, string name = null, string description = null, string modelVersion = null, string workspaceId = null, string versionDescription = null, ClassificationsTrainingParameters trainingParameters = null)

                    Request

                    Use the UpdateClassificationsModelOptions.Builder to create a UpdateClassificationsModelOptions object that contains the parameter values for the updateClassificationsModel method.

                    Path Parameters

                    • ID of the model

                    Query Parameters

                    • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

                    Form Parameters

                    • The 2-letter language code of this model

                    • Training data in JSON format. For more information, see Classifications training data requirements.

                    • An optional name for the model

                    • An optional map of metadata key-value pairs to store with this model

                      Examples:
                      View
                    • An optional description of the model

                    • An optional version string

                    • Deprecated — use model_version

                    • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding

                    • The description of the version

                    • Optional classifications training parameters along with model train requests

                    The updateClassificationsModel options.

                    parameters

                    • ID of the model.

                    • The 2-letter language code of this model.

                    • Training data in JSON format. For more information, see Classifications training data requirements.

                    • The content type of trainingData.

                      Allowable values: [json,application/json]

                    • An optional name for the model.

                    • An optional description of the model.

                    • An optional version string.

                    • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

                    • The description of the version.

                    • Optional classifications training parameters along with model train requests.

                    parameters

                    • ID of the model.

                    • The 2-letter language code of this model.

                    • Training data in JSON format. For more information, see Classifications training data requirements.

                    • The content type of training_data.

                      Allowable values: [json,application/json]

                    • An optional name for the model.

                    • An optional description of the model.

                    • An optional version string.

                    • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

                    • The description of the version.

                    • Optional classifications training parameters along with model train requests.

                    parameters

                    • ID of the model.

                    • The 2-letter language code of this model.

                    • Training data in JSON format. For more information, see Classifications training data requirements.

                    • The content type of trainingData.

                      Allowable values: [json,application/json]

                    • An optional name for the model.

                    • An optional description of the model.

                    • An optional version string.

                    • ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding.

                    • The description of the version.

                    • Optional classifications training parameters along with model train requests.

                    • curl -X PUT -u "apikey:{apikey}" -H "Content-Type: multipart/form-data" -F "training_data=@classifications_model.json;type=application/json" -F "language=en" -F "name=MyClassificationsModel" -F "description=My updated classifications model" -F "model_version=1.0.1" -F "version_description=Updated version" "{url}/v1/models/classifications/{model_id}?version=2022-04-07"
                    • IamAuthenticator authenticator = new IamAuthenticator(
                          apikey: "{apikey}"
                          );
                      
                      NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                      naturalLanguageUnderstanding.SetServiceUrl("{url}");
                      
                      var result = naturalLanguageUnderstanding.UpdateClassificationsModel(
                          modelId: "{modelId}",
                          trainingData: new MemoryStream(File.ReadAllBytes("trainingData.json")),
                          language: "en",
                          name: "MyClassificationsModel",
                          description: "My updated classifications model",
                          modelVersion: "1.0.1",
                          versionDescription: "Updated version"
                          );
                      
                      Console.WriteLine(result.Response);
                    • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                      NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                        "2022-04-07", authenticator);
                      naturalLanguageUnderstanding.setServiceUrl("{url}");
                      
                      try {
                        UpdateClassificationsModelOptions updateClassificationsModelOptions = new UpdateClassificationsModelOptions.Builder()
                          .language("en")
                          .trainingData(new FileInputStream("trainingData.json"))
                          .trainingDataContentType("application/json")
                          .name("newName")
                          .description("newDescription")
                          .modelVersion("testString")
                          .versionDescription("testString")
                          .modelId("{modelId}")
                          .build();
                        
                        ClassificationsModel response = naturalLanguageUnderstanding.updateClassificationsModel(updateClassificationsModelOptions).execute().getResult();
                        
                        System.out.println(response);
                      } catch (FileNotFoundException e) {
                        e.printStackTrace();
                      }
                    • const fs = require('fs');
                      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 updateClassificationsModelParams = {
                        language: 'en',
                        trainingData: fs.createReadStream('./classifications_model.json'),
                        name: 'MyClassificationsModel',
                        description: 'My updated classifications model',
                        modelVersion: '1.0.1',
                        versionDescription: 'Updated version',
                        modelId: '{model_id}'
                      };
                      
                      naturalLanguageUnderstanding.updateClassificationsModel(updateClassificationsModelParams)
                        .then(updateClassificationsModelResults => {
                          console.log(JSON.stringify(updateClassificationsModelResults, null, 2));
                        })
                        .catch(err => {
                          console.log('error:', err);
                        });
                    • from os.path import join, dirname
                      from ibm_watson import NaturalLanguageUnderstandingV1
                      from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                      
                      authenticator = IAMAuthenticator('{apikey}')
                      natural_language_understanding = NaturalLanguageUnderstandingV1(
                          version='2022-04-07',
                          authenticator=authenticator
                      )
                      
                      natural_language_understanding.set_service_url('{url}')
                      
                      with open(join(dirname(__file__), './.', 'classifications_model.json'),
                                     'rb') as file:
                          model=natural_language_understanding.update_classifications_model(
                              language='en',
                              training_data=file
                              name='MyClassificationsModel',
                              description='My updated classifications model',
                              model_version='1.0.1',
                              version_description='Updated version',
                              model_id='{model_id}'
                          ).get_result()
                          print(json.dumps(model, indent=2))

                    Response

                    Classifications model

                    Classifications model.

                    Classifications model.

                    Classifications model.

                    Classifications model.

                    Status Code

                    • Model overwrite successful

                    • Invalid request

                    • Access forbidden

                    Example responses
                    • {
                        "models": [
                          {
                            "name": "MyClassificationsModel",
                            "language": "en",
                            "model_version": "1.0.1",
                            "status": "deploying",
                            "notices": [],
                            "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                            "features": [
                              "classifications"
                            ],
                            "created": "2020-04-10T20:21:46Z",
                            "last_trained": "2020-04-10T20:21:46Z",
                            "last_deployed": "2020-04-10T20:21:46Z"
                          }
                        ]
                      }
                    • {
                        "models": [
                          {
                            "name": "MyClassificationsModel",
                            "language": "en",
                            "model_version": "1.0.1",
                            "status": "deploying",
                            "notices": [],
                            "model_id": "cb3755ad-d226-4587-b956-43a4a7202202",
                            "features": [
                              "classifications"
                            ],
                            "created": "2020-04-10T20:21:46Z",
                            "last_trained": "2020-04-10T20:21:46Z",
                            "last_deployed": "2020-04-10T20:21:46Z"
                          }
                        ]
                      }

                    Delete classifications model

                    Un-deploys the custom classifications model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

                    Un-deploys the custom classifications model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

                    Un-deploys the custom classifications model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

                    Un-deploys the custom classifications model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

                    Un-deploys the custom classifications model with the given model ID and deletes all associated customer data, including any training data or binary artifacts.

                    DELETE /v1/models/classifications/{model_id}
                    ServiceCall<DeleteModelResults> deleteClassificationsModel(DeleteClassificationsModelOptions deleteClassificationsModelOptions)
                    deleteClassificationsModel(params)
                    delete_classifications_model(self,
                            model_id: str,
                            **kwargs
                        ) -> DetailedResponse
                    DeleteClassificationsModel(string modelId)

                    Request

                    Use the DeleteClassificationsModelOptions.Builder to create a DeleteClassificationsModelOptions object that contains the parameter values for the deleteClassificationsModel method.

                    Path Parameters

                    • ID of the model

                    Query Parameters

                    • Release date of the API version you want to use. Specify dates in YYYY-MM-DD format. The current version is 2022-04-07.

                    The deleteClassificationsModel options.

                    parameters

                    • ID of the model.

                    parameters

                    • ID of the model.

                    parameters

                    • ID of the model.

                    • curl -X DELETE -u "apikey:{apikey}" "{url}/v1/models/classifications/{model_id}?version=2022-04-07"
                    • IamAuthenticator authenticator = new IamAuthenticator(
                          apikey: "{apikey}"
                          );
                      
                      NaturalLanguageUnderstandingService naturalLanguageUnderstanding = new NaturalLanguageUnderstandingService("2022-04-07", authenticator);
                      naturalLanguageUnderstanding.SetServiceUrl("{url}");
                      
                      var result = naturalLanguageUnderstanding.DeleteClassificationsModel(
                          modelId: "{modelId}"
                          );
                      
                      Console.WriteLine(result.Response);
                    • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
                      NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding(
                        "2022-04-07", authenticator);
                      naturalLanguageUnderstanding.setServiceUrl("{url}");
                      
                      DeleteClassificationsModelOptions deleteClassificationsModelOptions = new DeleteClassificationsModelOptions.Builder()
                        .modelId("{modelId}")
                        .build();
                      
                      DeleteModelResults response = naturalLanguageUnderstanding.deleteClassificationsModel(deleteClassificationsModelOptions).execute().getResult();
                    • 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 deleteClassificationsModelParams = {
                        modelId: '{model_id}',
                      };
                      
                      naturalLanguageUnderstanding.deleteClassificationsModel(deleteClassificationsModelParams)
                        .then(deleteClassificationsModelResults => {
                          console.log(JSON.stringify(deleteClassificationsModelResults, null, 2));
                        })
                        .catch(err => {
                          console.log('error:', err);
                        });
                    • import json
                      from ibm_watson import NaturalLanguageUnderstandingV1
                      from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
                      
                      authenticator = IAMAuthenticator('{apikey}')
                      natural_language_understanding = NaturalLanguageUnderstandingV1(
                          version='2022-04-07',
                          authenticator=authenticator)
                      
                      natural_language_understanding.set_service_url('{url}')
                      
                      model = natural_language_understanding.delete_classifications_model(
                        model_id='{model_id}',
                      ).get_result()
                      
                      
                      print(json.dumps(model, indent=2))

                    Response

                    Delete model results.

                    Delete model results.

                    Delete model results.

                    Delete model results.

                    Status Code

                    • Delete model results

                    • Invalid request

                    • Access forbidden

                    Example responses
                    • {
                        "deleted": "2987ca3f-205f-4786-a168-2d8026ddcc9b"
                      }
                    • {
                        "deleted": "2987ca3f-205f-4786-a168-2d8026ddcc9b"
                      }