Introduction

Analyze various features of text content at scale.

You can create custom models with Watson Knowledge Studio for IBM Cloud Pak for Data to detect custom entities and relations in Natural Language Understanding for IBM Cloud Pak for Data.

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

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

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

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

Maven

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

Gradle

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

GitHub

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

Installation

npm install ibm-watson

GitHub

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

Installation

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

GitHub

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

Installation

gem install ibm_watson

GitHub

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

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

GitHub

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

Cocoapods

pod 'IBMWatsonNaturalLanguageUnderstandingV1', '~> 2.0.3'

Carthage

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

Swift Package Manager

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

GitHub

Authentication

To authenticate to the API, you pass an access token in an Authorization header. The token is associated with a user name.

To authenticate to the API, you can pass either username and password credentials or an access token. Some services support only a single instance of the service and credentials. Other services support multiple instances.

  • Tokens support authenticated requests without embedding credentials in every call. If you pass a token, you maintain the token lifecycle.
  • Username and password credentials use basic authentication. However, the SDK manages the lifecycle of the tokens.

You can use the access token that is displayed in the IBM Cloud Pak for Data web client for testing and development. For production use, generate a token with the appropriate user name.

  • To find the access token in the IBM Cloud Pak for Data web client, view the details for the provisioned service instance. The details also include the service endpoint URL. For security reasons, don't use this token in production.
  • To generate an access token, call the POST preauth/validateAuth method.

To find your value for {url}, {icp4d_cluster_host} and {:port}, view the service credentials by viewing the details for the provisioned service instance in the IBM Cloud Pak for Data web client.

Generating an access token. The response includes an accessToken property.

Replace {icp4d_cluster_host} and {port} with the details for the service instance. Replace {username} and {password} with your IBM Cloud Pak for Data credentials.

curl -u "{username}:{password}" "https://{icp4d_cluster_host}{:port}/v1/preauth/validateAuth"

Authenticating to the API. Replace {token} with your details.

curl -H "Authorization: Bearer {token}" "https://{icp4d_cluster_host}{:port}/v1/{method}"

SDK managing the token.

Replace {icp4d_cluster_host}, {port}, and {url} with the details for the service instance. Replace {username} and {password} with your IBM Cloud Pak for Data credentials. Replace {version} with the service version date.

ICP4DConfig config = new ICP4DConfig.Builder()
  .url("https://{icp4d_cluster_host}{:port}")
  .username("{username}")
  .password("{password}")
  .build();
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", config);
naturalLanguageUnderstanding.setEndPoint("{url}");

SDK managing the token.

Replace {icp4d_cluster_host}, {port}, and {url} with the details for the service instance. Replace {username}, and {password} with your IBM Cloud Pak for Data credentials. Replace {version} with the service version date.

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

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  username: '{username}',
  password: '{password}',
  icp4d_url: 'https://{icp4d_cluster_host}{:port}',
  authentication_type: 'icp4d',
  url: '{url}',
});

SDK managing the token.

Replace {icp4d_cluster_host}, {port}, and {url} with the details for the service instance. Replace {username}, and {password} with your IBM Cloud Pak for Data credentials. Replace {version} with the service version date.

from ibm_watson import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    username='{username}',
    password='{password}',
    icp4d_url='https://{icp4d_cluster_host}{:port}',
    authentication_type='icp4d',
    url='{url}'
)

SDK managing the token.

Replace {icp4d_cluster_host}, {port}, and {url} with the details for the service instance. Replace {username}, and {password} with your IBM Cloud Pak for Data credentials. Replace {version} with the service version date.

require "ibm_watson"

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version: "{version}",
  username: "{username}",
  password: "{password}",
  icp4d_url: "https://{icp4d_cluster_host}{:port}",
  authentication_type: "icp4d",
  url: "{url}"
)

SDK managing the token.

Replace {icp4d_cluster_host}, {port}, and {url} with the details for the service instance. Replace {username}, and {password} with your IBM Cloud Pak for Data credentials. Replace {version} with the service version date.

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

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version:            "{version}",
  Username:           "{username}",
  Password:           "{password}",
  ICP4DURL:           "https://{icp4d_cluster_host}{:port}",
  AuthenticationType: "icp4d",
  URL:                "{url}",
})

SDK managing the token.

Replace {icp4d_cluster_host}, {port}, and {url} with the details for the service instance. Replace {username}, and {password} with your IBM Cloud Pak for Data credentials. Replace {version} with the service version date.

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

Service endpoint

The service endpoint is based on the IBM Cloud Pak for Data cluster and add-on service instance. The URL follows this pattern:

https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api
  • {icp4d_cluster_host} represents the name or IP address where your cluster is deployed.
  • {port} represents the port number that the service listens to.
  • {release} represents the release name specified when the Helm chart was installed.
  • {instance_id} represents the identifier of the service instance.

To find the base URL, view the details for the service instance from the IBM Cloud Pak for Data web client.

Use that URL in your requests to Natural Language Understanding for IBM Cloud Pak for Data.

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

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

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

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

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

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

Example

curl -H "Authorization: Bearer {token}" -X {request_method} "https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api/v1/{method}"

Example

naturalLanguageUnderstanding.setEndPoint("https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api");

Example

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

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  username: '{username}',
  password: '{password}',
  icp4d_url: 'https://{icp4d_cluster_host}{:port}',
  authentication_type: 'icp4d',
  url: 'https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api',
});

Examples in the constructor and after instantiation

from ibm_watson import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    username='{username}',
    password='{password}',
    icp4d_url='https://{icp4d_cluster_host}{:port}',
    authentication_type='icp4d',
    url='https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api'
)

or

natural_language_understanding.set_url('{url}')

Examples in the constructor and after instantiation

require "ibm_watson"

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version:             "{version}",
  username:            "{username}",
  password:            "{password}",
  icp4d_url:           "https://{icp4d_cluster_host}{:port}",
  authentication_type: "icp4d",
  url:                 "https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api"
)

or

natural_language_understanding.url = "https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api"

Examples in the constructor and after instantiation

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

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version:            "{version}",
  Username:           "{username}",
  Password:           "{password}",
  ICP4DURL:           "https://{icp4d_cluster_host}{:port}",
  AuthenticationType: "icp4d",
  URL:                "https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api",
})

or

naturalLanguageUnderstanding.SetURL("https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api")

Example

let naturalLanguageUnderstanding = NaturalLanguageUnderstanding(version: "{version}", username: "{username}", password: "{password}")
naturalLanguageUnderstanding.serviceURL = "https://{icp4d_cluster_host}{:port}/natural-language-understanding/{release}/instances/{instance_id}/api"

Disabling SSL verification

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

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

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

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

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

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

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

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

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

To disable SSL verification, call the disableSSLVerification() method on the service instance. You cannot disable SSL verification on Linux.

Example that disables SSL verification

curl -k -X {request_method} -H "Authorization: Bearer {token}" "{url}/v1/{method}"

Example that disables SSL verification

ICP4DConfig config = new ICP4DConfig.Builder()
  .url("https://{icp4d_cluster_host}{:port}")
  .username("{username}")
  .password("{password}")
  .disableSSLVerification(true)
  .build();
NaturalLanguageUnderstanding naturalLanguageUnderstanding = new NaturalLanguageUnderstanding("{version}", )config);
naturalLanguageUnderstanding.setEndPoint("{url}");

Example that disables SSL verification

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

const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
  version: '{version}',
  username: '{username}',
  password: '{password}',
  icp4d_url: 'https://{icp4d_cluster_host}{:port}',
  authentication_type: 'icp4d',
  url: '{url}',
  disable_ssl_verification: true,
});

Example that disables SSL verification

from ibm_watson import NaturalLanguageUnderstandingV1

natural_language_understanding = NaturalLanguageUnderstandingV1(
    version='{version}',
    username='{username}',
    password='{password}',
    icp4d_url='https://{icp4d_cluster_host}{:port}',
    authentication_type='icp4d',
    url='{url}'
)
natural_language_understanding.disable_SSL_verification()

Example that disables SSL verification

require "ibm_watson"

natural_language_understanding = IBMWatson::NaturalLanguageUnderstandingV1.new(
  version:             "{version}",
  username:            "{username}",
  password:            "{password}",
  icp4d_url:           "https://{icp4d_cluster_host}{:port}",
  authentication_type: "icp4d",
  url:                 "{url}"
)
natural_language_understanding.configure_http_client(disable_ssl: true)

Example that disables SSL verification

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

naturalLanguageUnderstanding, naturalLanguageUnderstandingErr := naturallanguageunderstandingv1.NewNaturalLanguageUnderstandingV1(&naturallanguageunderstandingv1.NaturalLanguageUnderstandingV1Options{
  Version:            "{version}",
  Username:           "{username}",
  Password:           "{password}",
  ICP4DURL:           "https://{icp4d_cluster_host}{:port}",
  AuthenticationType: "icp4d",
  URL:                "{url}",
})
naturalLanguageUnderstanding.DisableSSLVerification()

Example that disables SSL verification


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

Versioning

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

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

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

This documentation describes the current version of Natural Language Understanding for IBM Cloud Pak for Data, 2019-06-04. In some cases, differences in earlier versions are noted in the descriptions of parameters and response models.

Error handling

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

ErrorResponse

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

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

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

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

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

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

Error

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

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

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

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

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

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

Error

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

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

Field Description
errorDescription A message that describes the error.

Example error handling

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

Example error handling

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

Example error handling

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

Example error handling

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

Example error handling

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

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

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

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

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

Example error handling

naturalLanguageUnderstanding.method() {
  response, error in

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

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

  print(result)
}

Data handling

Additional headers

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

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

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

To pass header parameters with every request, use the setDefaultHeaders method of the service object.

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

To pass header parameters with every request, specify the headers parameter when you create the service object.

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

To pass header parameters with every request, specify the set_default_headers method of the service object.

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.

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.

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.

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

Example header parameter in a request

curl "Authorization: Bearer {token}" -X {request_method} --header "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

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

Example header parameter in a request

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

Response details

Natural Language Understanding for IBM Cloud Pak for Data might return information to the application in response headers.

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

Example request to access response headers

curl "Authorization: Bearer {token}" -X {request_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();

To access information in the response headers, add the return_response parameter set to true and specify the headers attribute on the response object that is returned by the method. 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

const parameters = {
  {parameters}
};

parameters.return_response = true;

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

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

DetailedResponse

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

Example request to access response headers

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

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

DetailedResponse

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

Example request to access response headers

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

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

DetailedResponse

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

Example request to access response headers

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

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

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

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

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

Example request to access response headers

naturalLanguageUnderstanding.methodName(parameters) {
  response, error in

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

Synchronous and asynchronous requests

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

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

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

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

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

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

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

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

Example synchronous request

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

Example asynchronous request

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

Example synchronous request

response = natural_language_understanding.method_name(parameters)

or

response = natural_language_understanding.await.method_name(parameters)

Example asynchronous request

response = natural_language_understanding.async.method_name(parameters)

Methods

Analyze text (GET)

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment
GET /v1/analyze
Request

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

  • URL-encoded text to analyze.

  • Comma separated list of analysis features

    Allowable values: [entities,keywords,relations,sentiment]

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

    Default: false

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

  • Maximum number of entities to return.

    Constraints: value ≤ 250

    Default: 50

  • Set this to true to return locations of entity mentions

    Default: false

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

    Default: false

  • Maximum number of keywords to return.

    Constraints: value ≤ 250

    Default: 50

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

    Default: false

  • Set this to false to disable document level sentiment analysis

    Default: true

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

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

Response

Results of the analysis, organized by feature

Status Code

  • Analysis results

  • Invalid request

Example responses

Analyze text

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment.

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment.

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment.

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment.

Analyzes text for the following features:

  • Entities
  • Keywords
  • Relations
  • Sentiment.
POST /v1/analyze
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) Analyze(analyzeOptions *AnalyzeOptions) (*core.DetailedResponse, error)
ServiceCall<AnalysisResults> analyze(AnalyzeOptions analyzeOptions)
analyze(params, [ callback() ])
analyze(self, features, text=None, return_analyzed_text=None, language=None, limit_text_characters=None, **kwargs)
analyze(features:, text: nil, return_analyzed_text: nil, language: nil, limit_text_characters: nil)
Request

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

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

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

An object containing request parameters. The features object and the text attribute are required.

The Analyze options.

The analyze options.

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze.

  • Whether or not to return the analyzed text.

    Default: false

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

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

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze.

  • Whether or not to return the analyzed text.

    Default: false

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

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

parameters

  • Specific features to analyze the document for.

  • The plain text to analyze.

  • Whether or not to return the analyzed text.

    Default: false

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

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

Response

Results of the analysis, organized by feature

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

List models

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

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

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

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

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

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

GET /v1/models
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) ListModels(listModelsOptions *ListModelsOptions) (*core.DetailedResponse, error)
ServiceCall<ListModelsResults> listModels()
listModels(params, [ callback() ])
list_models(self, **kwargs)
list_models
Request

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

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.

Custom models that are available for entities and relations.

Status Code

  • List models results

  • Invalid request

Example responses

Delete model

Deletes a custom 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}
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) DeleteModel(deleteModelOptions *DeleteModelOptions) (*core.DetailedResponse, error)
ServiceCall<DeleteModelResults> deleteModel(DeleteModelOptions deleteModelOptions)
deleteModel(params, [ callback() ])
delete_model(self, model_id, **kwargs)
delete_model(model_id:)
Request

Instantiate the DeleteModelOptions struct and set the fields to provide parameter values for the DeleteModel method.

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

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

The DeleteModel options.

The deleteModel options.

parameters

  • Model ID of the model.

parameters

  • Model ID of the model.

parameters

  • Model ID of the model.

Response

Delete model results.

Delete model results.

Delete model results.

Delete model results.

Delete model results.

Status Code

  • Delete model results

  • Invalid request

Example responses

Create entities model

Create a new custom entities or relations model by uploading a model binary and associated metadata. The model will begin deploying immediately.

Create a new custom entities or relations model by uploading a model binary and associated metadata. The model will begin deploying immediately.

Create a new custom entities or relations model by uploading a model binary and associated metadata. The model will begin deploying immediately.

Create a new custom entities or relations model by uploading a model binary and associated metadata. The model will begin deploying immediately.

Create a new custom entities or relations model by uploading a model binary and associated metadata. The model will begin deploying immediately.

Create a new custom entities or relations model by uploading a model binary and associated metadata. The model will begin deploying immediately.

POST /v1/models/entities
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) CreateEntitiesModel(createEntitiesModelOptions *CreateEntitiesModelOptions) (*core.DetailedResponse, error)
ServiceCall<Model> createEntitiesModel()
createEntitiesModel(params, [ callback() ])
create_entities_model(self, **kwargs)
create_entities_model
Request

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

Form Parameters

  • The language code of this model

    Example: en

  • An optional name for the model

    Example: MyEntitiesModel

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

    Example:
  • An optional description of the model

    Example: My custom categories model

  • An optional version string

    Example: 1.0.1

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

    Example: 3beb8bd5-7d02-4eb3-ab99-3fc6328df29e

  • The description of the version

    Example: My version description

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

Response

Metadata associated with this custom model

Metadata associated with this custom model.

Metadata associated with this custom model.

Metadata associated with this custom model.

Metadata associated with this custom model.

Metadata associated with this custom model.

Status Code

  • Model created successfully

  • Access forbidden

  • Invalid request

  • Internal server error

No Sample Response

This method does not specify any sample responses.

List entities models

Returns all custom entities and relations models associated with this service instance.

Returns all custom entities and relations models associated with this service instance.

Returns all custom entities and relations models associated with this service instance.

Returns all custom entities and relations models associated with this service instance.

Returns all custom entities and relations models associated with this service instance.

Returns all custom entities and relations models associated with this service instance.

GET /v1/models/entities
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) ListEntitiesModels(listEntitiesModelsOptions *ListEntitiesModelsOptions) (*core.DetailedResponse, error)
ServiceCall<ListModelsResults> listEntitiesModels()
listEntitiesModels(params, [ callback() ])
list_entities_models(self, **kwargs)
list_entities_models
Request

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

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.

Custom models that are available for entities and relations.

Status Code

  • List models results

  • Access forbidden

  • Invalid request

  • Internal server error

Example responses

Get entities model details

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

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

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

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

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

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

GET /v1/models/entities/{model_id}
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) GetEntitiesModel(getEntitiesModelOptions *GetEntitiesModelOptions) (*core.DetailedResponse, error)
ServiceCall<Model> getEntitiesModel(GetEntitiesModelOptions getEntitiesModelOptions)
getEntitiesModel(params, [ callback() ])
get_entities_model(self, model_id, **kwargs)
get_entities_model(model_id:)
Request

Instantiate the GetEntitiesModelOptions struct and set the fields to provide parameter values for the GetEntitiesModel method.

Use the GetEntitiesModelOptions.Builder to create a GetEntitiesModelOptions object that contains the parameter values for the getEntitiesModel method.

Path Parameters

  • Model ID of the model

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

The GetEntitiesModel options.

The getEntitiesModel options.

parameters

  • Model ID of the model.

parameters

  • Model ID of the model.

parameters

  • Model ID of the model.

Response

Metadata associated with this custom model

Metadata associated with this custom model.

Metadata associated with this custom model.

Metadata associated with this custom model.

Metadata associated with this custom model.

Metadata associated with this custom model.

Status Code

  • Model retrieved

  • Access forbidden

  • Invalid request

  • Internal server error

No Sample Response

This method does not specify any sample responses.

Update entities model

Overwrite the model binary associated with this custom entities model. The new model binary will replace the current deployment.

Overwrite the model binary associated with this custom entities model. The new model binary will replace the current deployment.

Overwrite the model binary associated with this custom entities model. The new model binary will replace the current deployment.

Overwrite the model binary associated with this custom entities model. The new model binary will replace the current deployment.

Overwrite the model binary associated with this custom entities model. The new model binary will replace the current deployment.

Overwrite the model binary associated with this custom entities model. The new model binary will replace the current deployment.

PUT /v1/models/entities/{model_id}
(naturalLanguageUnderstanding *NaturalLanguageUnderstandingV1) UpdateEntitiesModel(updateEntitiesModelOptions *UpdateEntitiesModelOptions) (*core.DetailedResponse, error)
ServiceCall<Model> updateEntitiesModel(UpdateEntitiesModelOptions updateEntitiesModelOptions)
updateEntitiesModel(params, [ callback() ])
update_entities_model(self, model_id, **kwargs)
update_entities_model(model_id:)
Request

Instantiate the UpdateEntitiesModelOptions struct and set the fields to provide parameter values for the UpdateEntitiesModel method.

Use the UpdateEntitiesModelOptions.Builder to create a UpdateEntitiesModelOptions object that contains the parameter values for the updateEntitiesModel method.

Path Parameters

  • Model ID of the model

Query Parameters

  • The release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2019-06-04.

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

Form Parameters

  • The language code of this model

    Example: en

  • An optional name for the model

    Example: MyEntitiesModel

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

    Example:
  • An optional description of the model

    Example: My custom categories model

  • An optional version string

    Example: 1.0.1

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

    Example: 3beb8bd5-7d02-4eb3-ab99-3fc6328df29e

  • The description of the version

    Example: My version description

The UpdateEntitiesModel options.

The updateEntitiesModel options.

parameters

  • Model ID of the model.

parameters

  • Model ID of the model.

parameters

  • Model ID of the model.

Response

Metadata associated with this custom model

Metadata associated with this custom model.