Introduction

IBM Watson™ Natural Language Classifier uses machine learning algorithms to return the top matching predefined classes for short text input. You create and train a classifier to connect predefined classes to example texts so that the service can apply those classes to new inputs.

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.0.0</version>
</dependency>

Gradle

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

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

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 'IBMWatsonNaturalLanguageClassifierV1', '~> 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

IBM Cloud is migrating to token-based Identity and Access Management (IAM) authentication.

  • With some service instances, you authenticate to the API by using IAM. You can pass either a bearer token in an Authorization header or an API key. Tokens support authenticated requests without embedding service credentials in every call. API keys use basic authentication. Learn more about IAM.

    If you pass in an API key, use apikey for the username and the value of the API key as the password.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

    If you pass in the value of the API key, the SDK manages the lifecycle of the tokens. If you pass a token, you maintain the token lifecycle. Learn more about IAM authentication with the SDK.

  • In other instances, you authenticate by providing the username and password for the service instance. For more information, see Service credentials for Watson services.

To find out which authentication to use, view the service credentials by clicking the service instance in the Resource list.

The "username" and "password" in the service credentials are different from your IBM Cloud account IBMid and password.

IAM authentication. Replace {apikey} and {url} with your service credentials.

curl -u "apikey:{apikey}" -X {request_method} "{url}/{method}"

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

curl -u "{username}:{password}" -X {request_method} "{url}/{method}"

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

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();
NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier(options);
naturalLanguageClassifier.setEndPoint("{url}");

Basic authentication. Replace {username}, {password}, and {url}. Use either of the two constructors.

NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier(
    "{username}",
    "{password}");
naturalLanguageClassifier.setEndPoint("{url}");

or

NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier();
naturalLanguageClassifier.setUsernameAndPassword("{username}","{password}");
naturalLanguageClassifier.setEndPoint("{url}");

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

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  iam_apikey: '{apikey}',
  url: '{url}'
});

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

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  username: '{username}',
  password: '{password}',
  url: '{url}'
});

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

from ibm_watson import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey='{apikey}',
    url='{url}'
)

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

from ibm_watson import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
    username='{username}',
    password='{password}',
    url='{url}'
)

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

require "ibm_watson"

natural_language_classifier = IBMWatson::NaturalLanguageClassifierV1.new(
  iam_apikey: "{apikey}",
  url:"{url}"
)

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

require "ibm_watson"

natural_language_classifier = IBMWatson::NaturalLanguageClassifierV1.new(
  username: "{username}",
  password: "{password}",
  url:"{url}"
)

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

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

naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(&naturallanguageclassifierv1.NaturalLanguageClassifierV1Options{
  IAMApiKey: "{apikey}",
  URL: "{url}",
})

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

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

naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(&naturallanguageclassifierv1.NaturalLanguageClassifierV1Options{
  Username: "{username}",
  Password: "{password}",
  URL: "{url}",
})

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

let naturalLanguageClassifier = NaturalLanguageClassifier(apiKey: "{apikey}")

naturalLanguageClassifier.serviceURL = "{url}"

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

let naturalLanguageClassifier = NaturalLanguageClassifier(username: "{username}", password: "{password}")

naturalLanguageClassifier.serviceURL = "{url}"

Service endpoint

The service endpoint is based on the location of the service instance. For example, when Natural Language Classifier is hosted in Washington DC, the base URL is https://gateway-wdc.watsonplatform.net/natural-language-classifier/api. The URL might also be different when you use IBM Cloud Dedicated.

To find out which URL to use, view the service credentials by clicking the service instance in the Resource list.

Use that URL in your requests to Natural Language Classifier.

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

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

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

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

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

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

Service endpoints by location:

  • Dallas: https://gateway.watsonplatform.net/natural-language-classifier/api
  • Frankfurt: https://gateway-fra.watsonplatform.net/natural-language-classifier/api
  • Washington DC: https://gateway-wdc.watsonplatform.net/natural-language-classifier/api
  • Tokyo: https://gateway-tok.watsonplatform.net/natural-language-classifier/api
  • London: https://gateway.watsonplatform.net/natural-language-classifier/api

All locations might not support Natural Language Classifier. For details, see Service availability.

Dallas API endpoint example

curl -u "apikey:{apikey}" -X {request_method} "https://gateway.watsonplatform.net/natural-language-classifier/api"

Your service instance might not use this URL

Default URL

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

Example for the Frankfurt location

NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier();
naturalLanguageClassifier.setEndPoint("https://gateway-fra.watsonplatform.net/natural-language-classifier/api");

Default URL

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

Example for the Frankfurt location

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  iam_apikey: '{apikey}',
  url: 'https://gateway-fra.watsonplatform.net/natural-language-classifier/api'
});

Default URL

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

Examples for the Frankfurt location in the constructor and after instantiation

natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey='{apikey}',
    url='https://gateway-fra.watsonplatform.net/natural-language-classifier/api'
)

or

natural_language_classifier.set_url('https://gateway-fra.watsonplatform.net/natural-language-classifier/api')

Default URL

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

Examples for the Frankfurt location in the constructor and after instantiation

natural_language_classifier = IBMWatson::.new(
  api_key: "{apikey}",
  url: "https://gateway-fra.watsonplatform.net/natural-language-classifier/api"
)

or

natural_language_classifier.url = "https://gateway-fra.watsonplatform.net/natural-language-classifier/api"

Default URL

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

Examples for the Frankfurt location in the constructor and after instantiation

naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(&naturallanguageclassifierv1.NaturalLanguageClassifierV1Options{
  IAMApiKey: "{apikey}",
  URL: "https://gateway-fra.watsonplatform.net/natural-language-classifier/api",
})

or

naturalLanguageClassifier.SetURL("https://gateway-fra.watsonplatform.net/natural-language-classifier/api")

Default URL

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

Example for the Frankfurt location

let naturalLanguageClassifier = NaturalLanguageClassifier(apiKey: "{apikey}")
naturalLanguageClassifier.serviceURL = "https://gateway-fra.watsonplatform.net/natural-language-classifier/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.

You cannot disable SSL verification with the Swift SDK.

Example that disables SSL verification

IAM authentication. Replace {apikey} and {url} with your service credentials.

curl -k -u "apikey:{apikey}" -X {request_method} "{url}/{method}"

Example that disables SSL verification

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();
NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier(options);
naturalLanguageClassifier.setEndPoint("{url}");

HttpConfigOptions configOptions = new HttpConfigOptions.Builder()
  .disableSslVerification(true)
  .build();
naturalLanguageClassifier.configureClient(configOptions);

Example that disables SSL verification

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  iam_apikey: '{apikey}',
  url: '{url}',
  disable_ssl_verification: true,
});

Example that disables SSL verification

from ibm_watson import NaturalLanguageClassifierV1

natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey='{apikey}',
    url='{url}'
)
natural_language_classifier.disable_SSL_verification()

Example that disables SSL verification

require "ibm_watson"

natural_language_classifier = IBMWatson::NaturalLanguageClassifierV1.new(
  iam_apikey: "{apikey}",
  url:"{url}"
)
natural_language_classifier.configure_http_client(disable_ssl: true)

Example that disables SSL verification

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

naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(&naturallanguageclassifierv1.NaturalLanguageClassifierV1Options{
  IAMApiKey: "{apikey}",
  URL: "{url}",
})
naturalLanguageClassifier.DisableSSLVerification()

Error handling

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

ErrorResponse

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

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

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

When the Java SDK receives an error response from the Natural Language Classifier 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 Classifier 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 Classifier 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 Classifier 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 Classifier 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

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

Example error handling

from ibm_watson import ApiException
try:
    # Invoke a Natural Language Classifier 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 Classifier 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/naturallanguageclassifierv1"

// Instantiate a service
naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(&naturalLanguageClassifierv1.NaturalLanguageClassifierV1Options{})

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

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

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

Example error handling

naturalLanguageClassifier.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. See Data collection for an example use of this method.

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

To pass header parameters with every request, specify the headers parameter when you create the service object. See Data collection for an example use of this method.

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

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

To pass header parameters in a single request, include headers as a dict in the request.

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

To pass header parameters in a single request, specify the headers method as a chainable method in the request.

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

To pass header parameters in a single request, specify the Headers as a map in the request.

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.

Example header parameter in a request

curl -u "apikey:{apikey}" -X {request_method} --header "Request-Header: {header_value}" "{url}/{method}"

Example header parameter in a request

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

Example header parameter in a request

const parameters = {
  {parameters}
};

naturalLanguageClassifier.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_classifier.methodName(
    parameters,
    headers = {
        'Custom-Header': '{header_value}'
    })

Example header parameter in a request

response = natural_language_classifier.headers(
  "Custom-Header" => "{header_value}"
).methodName(parameters)

Example header parameter in a request

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

Example header parameter in a request

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

Response details

The Natural Language Classifier 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 additional debugging information, include the --verbose (-v) option with the request.

Example request to access response headers

curl -u "apikey:{apikey}" -X {request_method} --include "{url}/{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 = naturalLanguageClassifier.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.

Example request to access response headers

const parameters = {
  {parameters}
};

parameters.return_response = true;

naturalLanguageClassifier.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_classifier.set_detailed_response(True)
response = natural_language_classifier.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_classifier.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, _ := naturallanguageclassifierv1.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

naturalLanguageClassifier.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)
}

Data collection

By default, all Watson services log requests and their results. Logging is done only to improve the services for future users. The logged data is not shared or made public.

To prevent IBM usage of your data for an API request, set the X-Watson-Learning-Opt-Out header parameter to true.

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

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

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

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

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

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

You can set the header by adding it to the defaultHeaders property 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");

naturalLanguageClassifier.setDefaultHeaders(headers);

Example request

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  iam_apikey: '{apikey}',
  url: '{url}',
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});

Example request

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

Example request

natural_language_classifier.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")
naturallanguageclassifierv1.Service.SetDefaultHeaders(headers)

Example request

naturalLanguageClassifier.defaultHeaders["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 = naturalLanguageClassifier.method(parameters).execute();

Example asynchronous request

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

Example synchronous request

response = natural_language_classifier.method_name(parameters)

or

response = natural_language_classifier.await.method_name(parameters)

Example asynchronous request

response = natural_language_classifier.async.method_name(parameters)

Rate limiting

The service is limited to 80 requests per second on a per-service-instance basis. An HTTP 429 Too Many Requests response status code indicates that the rate limit has been exceeded.

Methods

Classify a phrase (GET)

The status must be Available before you can use the classifier to classify calls.

GET /v1/classifiers/{classifier_id}/classify
Request

Path Parameters

  • Classifier ID to use.

Query Parameters

  • Phrase to classify. The maximum length is 2048 characters.

    Constraints: length ≤ 2048

Response

Response from the classifier for a phrase.

Status Code

  • OK

  • Bad request. Likely caused by a classifier status other than Available or by a missing text parameter.

  • The classifier does not exist or is not available to the user.

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses

Classify a phrase

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

Returns label information for the input. The status must be Available before you can use the classifier to classify text.

POST /v1/classifiers/{classifier_id}/classify
(naturalLanguageClassifier *NaturalLanguageClassifierV1) Classify(classifyOptions *ClassifyOptions) (*core.DetailedResponse, error)
ServiceCall<Classification> classify(ClassifyOptions classifyOptions)
classify(params, callback())
classify(self, classifier_id, text, **kwargs)
classify(classifier_id:, text:)
func classify(
    classifierID: String,
    text: String,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Classification>?, WatsonError?) -> Void)
Request

Instantiate the ClassifyOptions struct and set the fields to provide parameter values for the Classify method.

Use the ClassifyOptions.Builder to create a ClassifyOptions object that contains the parameter values for the classify method.

Path Parameters

  • Classifier ID to use.

Phrase to classify.

The classify options.

The classify options.

parameters

  • Classifier ID to use.

  • The submitted phrase. The maximum length is 2048 characters.

    Constraints: length ≤ 2048

parameters

  • Classifier ID to use.

  • The submitted phrase. The maximum length is 2048 characters.

    Constraints: length ≤ 2048

parameters

  • Classifier ID to use.

  • The submitted phrase. The maximum length is 2048 characters.

    Constraints: length ≤ 2048

parameters

  • Classifier ID to use.

  • The submitted phrase. The maximum length is 2048 characters.

    Constraints: length ≤ 2048

Response

Response from the classifier for a phrase.

Response from the classifier for a phrase.

Response from the classifier for a phrase.

Response from the classifier for a phrase.

Response from the classifier for a phrase.

Response from the classifier for a phrase.

Response from the classifier for a phrase.

Status Code

  • OK.

  • Bad request. Likely caused by a classifier status other than Available or by malformed JSON.

  • The classifier does not exist or is not available to the user.

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses

Classify multiple phrases

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

Returns label information for multiple phrases. The status must be Available before you can use the classifier to classify text.

Note that classifying Japanese texts is a beta feature.

POST /v1/classifiers/{classifier_id}/classify_collection
(naturalLanguageClassifier *NaturalLanguageClassifierV1) ClassifyCollection(classifyCollectionOptions *ClassifyCollectionOptions) (*core.DetailedResponse, error)
ServiceCall<ClassificationCollection> classifyCollection(ClassifyCollectionOptions classifyCollectionOptions)
classifyCollection(params, callback())
classify_collection(self, classifier_id, collection, **kwargs)
classify_collection(classifier_id:, collection:)
func classifyCollection(
    classifierID: String,
    collection: [ClassifyInput],
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<ClassificationCollection>?, WatsonError?) -> Void)
Request

Instantiate the ClassifyCollectionOptions struct and set the fields to provide parameter values for the ClassifyCollection method.

Use the ClassifyCollectionOptions.Builder to create a ClassifyCollectionOptions object that contains the parameter values for the classifyCollection method.

Path Parameters

  • Classifier ID to use.

Phrase to classify. You can submit up to 30 text phrases in a request.

The classifyCollection options.

The classifyCollection options.

parameters

  • Classifier ID to use.

  • The submitted phrases.

parameters

  • Classifier ID to use.

  • The submitted phrases.

parameters

  • Classifier ID to use.

  • The submitted phrases.

parameters

  • Classifier ID to use.

  • The submitted phrases.

Response

Response from the classifier for multiple phrases.

Response from the classifier for multiple phrases.

Response from the classifier for multiple phrases.

Response from the classifier for multiple phrases.

Response from the classifier for multiple phrases.

Response from the classifier for multiple phrases.

Response from the classifier for multiple phrases.

Status Code

  • OK.

  • Bad request. Likely caused by a classifier status other than Available or by malformed JSON.

  • The classifier does not exist or is not available to the user.

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses

Create classifier

Sends data to create and train a classifier and returns information about the new classifier.

Sends data to create and train a classifier and returns information about the new classifier.

Sends data to create and train a classifier and returns information about the new classifier.

Sends data to create and train a classifier and returns information about the new classifier.

Sends data to create and train a classifier and returns information about the new classifier.

Sends data to create and train a classifier and returns information about the new classifier.

Sends data to create and train a classifier and returns information about the new classifier.

POST /v1/classifiers
(naturalLanguageClassifier *NaturalLanguageClassifierV1) CreateClassifier(createClassifierOptions *CreateClassifierOptions) (*core.DetailedResponse, error)
ServiceCall<Classifier> createClassifier(CreateClassifierOptions createClassifierOptions)
createClassifier(params, callback())
create_classifier(self, metadata, training_data, **kwargs)
create_classifier(metadata:, training_data:)
func createClassifier(
    metadata: Data,
    trainingData: Data,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Classifier>?, WatsonError?) -> Void)
Request

Instantiate the CreateClassifierOptions struct and set the fields to provide parameter values for the CreateClassifier method.

Use the CreateClassifierOptions.Builder to create a CreateClassifierOptions object that contains the parameter values for the createClassifier method.

Form Parameters

  • Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639.

    Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Korean (ko), Brazilian Portuguese (pt), and Spanish (es).

  • Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see Data preparation.

The createClassifier options.

The createClassifier options.

parameters

  • Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639.

    Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Korean (ko), Brazilian Portuguese (pt), and Spanish (es).

  • Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see Data preparation.

parameters

  • Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639.

    Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Korean (ko), Brazilian Portuguese (pt), and Spanish (es).

  • Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see Data preparation.

parameters

  • Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639.

    Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Korean (ko), Brazilian Portuguese (pt), and Spanish (es).

  • Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see Data preparation.

parameters

  • Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639.

    Supported languages are English (en), Arabic (ar), French (fr), German, (de), Italian (it), Japanese (ja), Korean (ko), Brazilian Portuguese (pt), and Spanish (es).

  • Training data in CSV format. Each text value must have at least one class. The data can include up to 3,000 classes and 20,000 records. For details, see Data preparation.

Response

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

Status Code

  • OK.

  • Bad request. Might be caused by the size of the training data (too many classes or records or not enough records). Also returned when the training data or metadata is missing or malformed.

  • Conflict with this classifier. Likely caused by a temporary server issue or invalid training data. Make sure that your training data adheres to the format and data requirements and resubmit the request to try again.

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses

List classifiers

Returns an empty array if no classifiers are available.

Returns an empty array if no classifiers are available.

Returns an empty array if no classifiers are available.

Returns an empty array if no classifiers are available.

Returns an empty array if no classifiers are available.

Returns an empty array if no classifiers are available.

Returns an empty array if no classifiers are available.

GET /v1/classifiers
(naturalLanguageClassifier *NaturalLanguageClassifierV1) ListClassifiers(listClassifiersOptions *ListClassifiersOptions) (*core.DetailedResponse, error)
ServiceCall<ClassifierList> listClassifiers()
listClassifiers(params, callback())
list_classifiers(self, **kwargs)
list_classifiers
func listClassifiers(
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<ClassifierList>?, WatsonError?) -> Void)
Request

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.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

Response

List of available classifiers.

List of available classifiers.

List of available classifiers.

List of available classifiers.

List of available classifiers.

List of available classifiers.

List of available classifiers.

Status Code

  • OK

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses

Get information about a classifier

Returns status and other information about a classifier.

Returns status and other information about a classifier.

Returns status and other information about a classifier.

Returns status and other information about a classifier.

Returns status and other information about a classifier.

Returns status and other information about a classifier.

Returns status and other information about a classifier.

GET /v1/classifiers/{classifier_id}
(naturalLanguageClassifier *NaturalLanguageClassifierV1) GetClassifier(getClassifierOptions *GetClassifierOptions) (*core.DetailedResponse, error)
ServiceCall<Classifier> getClassifier(GetClassifierOptions getClassifierOptions)
getClassifier(params, callback())
get_classifier(self, classifier_id, **kwargs)
get_classifier(classifier_id:)
func getClassifier(
    classifierID: String,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Classifier>?, WatsonError?) -> Void)
Request

Instantiate the GetClassifierOptions struct and set the fields to provide parameter values for the GetClassifier method.

Use the GetClassifierOptions.Builder to create a GetClassifierOptions object that contains the parameter values for the getClassifier method.

Path Parameters

  • Classifier ID to query.

The getClassifier options.

The getClassifier options.

parameters

  • Classifier ID to query.

parameters

  • Classifier ID to query.

parameters

  • Classifier ID to query.

parameters

  • Classifier ID to query.

Response

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

A classifier for natural language phrases.

Status Code

  • OK.

  • The classifier does not exist or is not available to the user.

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses

Delete classifier

DELETE /v1/classifiers/{classifier_id}
(naturalLanguageClassifier *NaturalLanguageClassifierV1) DeleteClassifier(deleteClassifierOptions *DeleteClassifierOptions) (*core.DetailedResponse, error)
ServiceCall<Void> deleteClassifier(DeleteClassifierOptions deleteClassifierOptions)
deleteClassifier(params, callback())
delete_classifier(self, classifier_id, **kwargs)
delete_classifier(classifier_id:)
func deleteClassifier(
    classifierID: String,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Void>?, WatsonError?) -> Void)
Request

Instantiate the DeleteClassifierOptions struct and set the fields to provide parameter values for the DeleteClassifier method.

Use the DeleteClassifierOptions.Builder to create a DeleteClassifierOptions object that contains the parameter values for the deleteClassifier method.

Path Parameters

  • Classifier ID to delete.

The deleteClassifier options.

The deleteClassifier options.

parameters

  • Classifier ID to delete.

parameters

  • Classifier ID to delete.

parameters

  • Classifier ID to delete.

parameters

  • Classifier ID to delete.

Response

Status Code

  • OK. Deleted.

  • The classifier does not exist or is not available to the user.

  • Too Many Requests. The rate limit is exceeded for this service instance.

Example responses