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.

This documentation describes Java SDK major version 8. For details about how to migrate your code from the previous version see the migration guide.

This documentation describes Node SDK major version 5. For details about how to migrate your code from the previous version, see the migration guide.

This documentation describes Python SDK major version 4. For details about how to migrate your code from the previous version, see the migration guide.

This documentation describes Ruby SDK major version 1. For details about how to migrate your code from the previous version, see the migration guide.

This documentation describes .NET Standard SDK major version 4. For details about how to migrate your code from the previous version, see the migration guide.

This documentation describes Go SDK major version 1. For details about how to migrate your code from the previous version, see the migration guide.

This documentation describes Swift SDK major version 3. For details about how to migrate your code from the previous version, see the migration guide.

This documentation describes Unity SDK major version 4. For details about how to migrate your code from the previous version, see the migration guide.

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 IBM Watson Unity SDK has the following requirements.

  • The SDK requires Unity version 2018.2 or later to support TLS 1.2.
    • Set the project settings for both the Scripting Runtime Version and the Api Compatibility Level to .NET 4.x Equivalent.
    • For more information, see TLS 1.0 support.
  • The SDK does not support the WebGL projects. Change your build settings to any platform except WebGL.

For information about how to install and configure the SDK and SDK Core, see https://github.com/watson-developer-cloud/unity-sdk.

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

Maven

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

Gradle

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

GitHub

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

Installation

npm install ibm-watson@^5.2.1

GitHub

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

Installation

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

GitHub

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

Installation

gem install ibm_watson

GitHub

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

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

GitHub

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

Cocoapods

pod 'IBMWatsonNaturalLanguageClassifierV1', '~> 3.1.0'

Carthage

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

Swift Package Manager

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

GitHub

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

Package Manager

Install-Package IBM.Watson.NaturalLanguageClassifier.v1 -Version 4.1.0

.NET CLI

dotnet add package IBM.Watson.NaturalLanguageClassifier.v1 -version 4.1.0

PackageReference

<PackageReference Include="IBM.Watson.NaturalLanguageClassifier.v1" Version="4.1.0" />

GitHub

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

Github

Authentication

IBM Cloud Identity and Access Management (IAM) is the primary method to authenticate to the API. However, with some older service instances you authenticate by providing a username and password for the service instance.

  • For service instances that use IAM authentication, you can pass either a bearer token in an authorization header or an API key. Tokens support authenticated requests without embedding service credentials in every call. API keys use basic authentication. For testing and development, you can pass an API key directly. However, for production use, unless you use the Watson SDKs, use an IAM token. For more information, see Authenticating to Watson services.

    If you pass in an API key, use apikey for the username and the value of the API key as the password. For example, if the API key is f5sAznhrKQyvBFFaZbtF60m5tzLbqWhyALQawBg5TjRI in the service credentials, include the credentials in your call like this:

      curl -u "apikey:f5sAznhrKQyvBFFaZbtF60m5tzLbqWhyALQawBg5TjRI"
    
  • In other instances, you authenticate by providing the username and password for the service instance. For more information, see Authenticating with Cloud Foundry service credentials.

The SDK provides initialization methods for each form of authentication.

  • For service instances that use IAM authentication, the SDK provides two initialization methods: one that accepts an API key and another that accepts an access token created from an API key.

    • Use the API key to have the SDK manage the lifecycle of the token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
    • Use the access token to manage the lifecycle yourself. You must periodically refresh the token.

      For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.For more information, see IAM authentication with the SDK.

  • For service instances that use username and password authentication, use the BasicAuthenticator initialization method and specify the username and password. For more information, see Authenticating with Cloud Foundry service credentials.

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

IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier(authenticator);
naturalLanguageClassifier.setServiceUrl("{url}");

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

BasicAuthenticator authenticator = new BasicAuthenticator("{username}", "{password}");
NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier( authenticator);
naturalLanguageClassifier.setServiceUrl("{url}");

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

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

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

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

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

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

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

from ibm_watson import NaturalLanguageClassifierV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
natural_language_classifier = NaturalLanguageClassifierV1(
    authenticator=authenticator
)

natural_language_classifier.set_service_url('{url}')

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

from ibm_watson import NaturalLanguageClassifierV1
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator

authenticator = BasicAuthenticator('{username}','{password}')

natural_language_classifier = NaturalLanguageClassifierV1(
)

natural_language_classifier.set_service_url('{url}')

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

require "ibm_watson/authenticators"
require "ibm_watson/natural_language_classifier_v1"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
natural_language_classifier = NaturalLanguageClassifierV1.new(
  authenticator: authenticator
)
natural_language_classifier.service_url = "{url}"

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

require "ibm_watson/natural_language_classifier_v1"
include IBMWatson

authenticator = Authenticators::BasicAuthenticator.new(
  username: "{username}",
  password: "{password}"
)
natural_language_classifier = NaturalLanguageClassifierV1.new(
  authenticator: authenticator
)
natural_language_classifier.service_url = "{url}";

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

import (
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageclassifierv1"
)

func main() {
  authenticator := &core.IamAuthenticator{
    ApiKey: "{apikey}",
  }

  options := &naturallanguageclassifierv1.NaturalLanguageClassifierV1Options{
    Authenticator: authenticator,
  }

  naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(options)

  if naturalLanguageClassifierErr != nil {
    panic(naturalLanguageClassifierErr)
  }

  naturalLanguageClassifier.SetServiceURL("{url}")
}

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

import (
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/naturallanguageclassifierv1"
)

func main() {
  authenticator := &core.BasicAuthenticator{
    Username: "{username}",
    Password: "{password}",
  }

  options := &naturallanguageclassifierv1.NaturalLanguageClassifierV1Options{
    Authenticator: authenticator,
  }

  naturallanguageclassifier, naturallanguageclassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(options)

  if naturallanguageclassifierErr != nil {
  panic(naturallanguageclassifierErr)
  }

  naturallanguageclassifier.SetServiceURL("{url}")
}

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

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageClassifier = NaturalLanguageClassifier(authenticator: authenticator)
naturalLanguageClassifier.serviceURL = "{url}"

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

let authenticator = WatsonBasicAuthenticator(username: "{username}", password: "{password}")
let naturalLanguageClassifier = NaturalLanguageClassifier(authenticator: authenticator)
naturalLanguageClassifier.serviceURL = "{url}"

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

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

NaturalLanguageClassifierService naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

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

BasicAuthenticator authenticator = new BasicAuthenticator(
    username: "{username}",
    password: "{password}"
    );

NaturalLanguageClassifierService naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

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

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

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

var naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

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

var authenticator = new BasicAuthenticator(
    username: "{username}",
    password: "{password}");

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

var naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

Access between services

You can grant access between your IBM Cloud services and to your services by applications that need it.

  • To grant access between IBM Cloud services, create an authorization between the services. For more information, see Granting access between services.
  • To grant access to your services by applications without using user credentials, create a service ID, add an API key, and assign access policies. For more information, see Creating and working with service IDs.

For more information about IAM, see IAM access.

To grant this access, use an endpoint URL that includes the service instance ID (for example, https://api.us-south.natural-language-classifier.watson.cloud.ibm.com/instances/6bbda3b3-d572-45e1-8c54-22d6ed9e52c2). You can find the instance ID in two places:

  • By clicking the service instance row in the Resource list. The instance ID is the GUID in the details pane.
  • By clicking the name of the service instance in the list and looking at the credentials URL.

    If you don't see the instance ID in the URL, you can add new credentials from the Service credentials page.

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://api.us-east.natural-language-classifier.watson.cloud.ibm.com. The URL might be different for instances created before 13 December 2019 or 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 setServiceUrl() 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.

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

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

Service endpoints by location:

  • Dallas: https://api.us-south.natural-language-classifier.watson.cloud.ibm.com
  • Washington DC: https://api.us-east.natural-language-classifier.watson.cloud.ibm.com
  • Frankfurt: https://api.eu-de.natural-language-classifier.watson.cloud.ibm.com
  • Sydney: https://api.au-syd.natural-language-classifier.watson.cloud.ibm.com
  • Tokyo: https://api.jp-tok.natural-language-classifier.watson.cloud.ibm.com
  • London: https://api.eu-gb.natural-language-classifier.watson.cloud.ibm.com
  • Seoul: https://api.kr-seo.natural-language-classifier.watson.cloud.ibm.com

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://api.us-south.natural-language-classifier.watson.cloud.ibm.com"

Your service instance might not use this URL

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier(authenticator);
naturalLanguageClassifier.setServiceUrl("https://api.us-east.natural-language-classifier.watson.cloud.ibm.com");

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  url: 'https://api.us-east.natural-language-classifier.watson.cloud.ibm.com',
});

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

from ibm_watson import NaturalLanguageClassifierV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
natural_language_classifier = NaturalLanguageClassifierV1(
    authenticator=authenticator
)

natural_language_classifier.set_service_url('https://api.us-east.natural-language-classifier.watson.cloud.ibm.com')

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

require "ibm_watson/authenticators"
require "ibm_watson/natural_language_classifier_v1"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
natural_language_classifier = NaturalLanguageClassifierV1.new(
  authenticator: authenticator
)
natural_language_classifier.service_url = "https://api.us-east.natural-language-classifier.watson.cloud.ibm.com"

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(options)

if naturalLanguageClassifierErr != nil {
  panic(naturalLanguageClassifierErr)
}

naturalLanguageClassifier.SetServiceURL("https://api.us-east.natural-language-classifier.watson.cloud.ibm.com")

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageClassifier = NaturalLanguageClassifier(authenticator: authenticator)
naturalLanguageClassifier.serviceURL = "https://api.us-east.natural-language-classifier.watson.cloud.ibm.com"

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

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

NaturalLanguageClassifierService naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("https://api.us-east.natural-language-classifier.watson.cloud.ibm.com");

Default URL

https://api.us-south.natural-language-classifier.watson.cloud.ibm.com

Example for the Washington DC location

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

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

var naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("https://api.us-east.natural-language-classifier.watson.cloud.ibm.com");

Disabling SSL verification

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

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

Enabling SSL verification is highly recommended. Disabling SSL jeopardizes the security of the connection and data. Disable SSL only if 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 disableSslVerification parameter to true when you create the service instance.

To disable SSL verification, specify true on the set_disable_ssl_verification method for the service instance.

To disable SSL verification, specify true on the configure_http_client method for the service instance.

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

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

To disable SSL verification, set the DisableSslVerification method to true on the service instance.

To disable SSL verification, set the DisableSslVerification method to true on the service instance.

Example 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

IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
NaturalLanguageClassifier naturalLanguageClassifier = new NaturalLanguageClassifier(authenticator);
naturalLanguageClassifier.setServiceUrl("{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 { IamAuthenticator } = require('ibm-watson/auth');

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  url: '{url}',
  disableSslVerification: true,
});

Example that disables SSL verification

from ibm_watson import NaturalLanguageClassifierV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
natural_language_classifier = NaturalLanguageClassifierV1(
    authenticator=authenticator
)

natural_language_classifier.set_service_url('{url}')

natural_language_classifier.set_disable_ssl_verification(True)

Example that disables SSL verification

require "ibm_watson/authenticators"
require "ibm_watson/natural_language_classifier_v1"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
natural_language_classifier = NaturalLanguageClassifierV1.new(
  authenticator: authenticator
)
natural_language_classifier.service_url = "{url}"

natural_language_classifier.configure_http_client(disable_ssl: true)

Example that disables SSL verification

naturalLanguageClassifier, naturalLanguageClassifierErr := naturallanguageclassifierv1.NewNaturalLanguageClassifierV1(options)

if naturalLanguageClassifierErr != nil {
  panic(naturalLanguageClassifierErr)
}

naturalLanguageClassifier.SetServiceURL("{url}")

naturalLanguageClassifier.DisableSSLVerification()

Example that disables SSL verification

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let naturalLanguageClassifier = NaturalLanguageClassifier(authenticator: authenticator)
naturalLanguageClassifier.serviceURL = "{url}"

naturalLanguageClassifier.disableSSLVerification()

Example that disables SSL verification

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

NaturalLanguageClassifierService naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

naturalLanguageClassifier.DisableSslVerification(true);

Example that disables SSL verification

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

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

var naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

naturalLanguageClassifier.DisableSslVerification = true;

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 that is 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 that is returned.
message A message that describes the error.

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

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

When the Ruby SDK receives an error response from the Natural Language Classifier service, it generates an ApiException that contains the following fields.

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

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

Error

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

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

Field Description
errorDescription A message that describes the error.

When the .NET Standard SDK receives an error response from the Natural Language Classifier service, it generates a ServiceResponseException that contains the following fields.

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

When the Unity SDK receives an error response from the Natural Language Classifier service, it generates an IBMError that contains the following fields.

Field Description
Url The URL that generated the error.
StatusCode The HTTP response code returned.
ErrorMessage A message that describes the error.
Response The contents of the response from the server.
ResponseHeaders A dictionary of headers returned by the request.

Example error handling

try {
  // Invoke a 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(options)

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

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

// Check for errors
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)
}

Example error handling

try
{
    // Invoke a Watson naturalLanguageClassifier method
}
catch(ServiceResponseException e)
{
    Console.WriteLine("Error: " + e.Message);
}
catch (Exception e)
{
    Console.WriteLine("Error: " + e.Message);
}

Example error handling

// Invoke a method
naturalLanguageClassifier.MethodName(Callback, Parameters);

// Check for errors
private void Callback(DetailedResponse<ExampleResponse> response, IBMError error)
{
    if (error == null)
    {
        Log.Debug("ExampleCallback", "Response received: {0}", response.Response);
    }
    else
    {
        Log.Debug("ExampleCallback", "Error received: {0}, {1}, {3}", error.StatusCode, error.ErrorMessage, error.Response);
    }
}

Data handling

Additional headers

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

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

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

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

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

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

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

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

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

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

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

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

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

To pass header parameters with every request, add them to the defaultHeaders property of the service object. See Data collection for an example use of this method.

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

To pass header parameters in a single request, use the WithHeader() method as a modifier on the request before you execute it.

To pass header parameters in a single request, use the WithHeader() method as a modifier on the request before you execute it.

Example header parameter in a request

curl -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

result, 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
}

Example header parameter in a request

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

NaturalLanguageClassifierService naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

naturalLanguageClassifier.WithHeader("Custom-Header", "header_value");

Example header parameter in a request

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

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

var naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

naturalLanguageClassifier.WithHeader("Custom-Header", "header_value");

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

All response data is available in the Response<T> object that is returned by each method. To access information in the response object, use the following properties.

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

Example request to access response headers

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"
result, 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 that is 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)
}

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

DetailedResponse

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

Example request to access response headers

var results = naturalLanguageClassifier.MethodName(parameters);

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

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

DetailedResponse

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

Example request to access response headers

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

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

Data collection

By default, 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.

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

Example request

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

Example request

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

naturalLanguageClassifier.setDefaultHeaders(headers);

Example request

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

const naturalLanguageClassifier = new NaturalLanguageClassifierV1({
  authenticator: new IamAuthenticator({
    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")
naturalLanguageClassifier.SetDefaultHeaders(headers)

Example request

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

Example request

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

NaturalLanguageClassifierService naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

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

Example request

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

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

var naturalLanguageClassifier = new NaturalLanguageClassifierService(authenticator);
naturalLanguageClassifier.SetServiceUrl("{url}");

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

Synchronous and asynchronous requests

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

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

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

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

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

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

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

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

Example synchronous request

ReturnType returnValue = 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.

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) (result *Classification, response *core.DetailedResponse, err 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)
Classify(string classifierId, string text)
Classify(Callback<Classification> callback, string classifierId, string text)
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

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.

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.

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) (result *ClassificationCollection, response *core.DetailedResponse, err 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)
ClassifyCollection(string classifierId, List<ClassifyInput> collection)
ClassifyCollection(Callback<ClassificationCollection> callback, string classifierId, List<ClassifyInput> collection)
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.

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.

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.

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) (result *Classifier, response *core.DetailedResponse, err error)
ServiceCall<Classifier> createClassifier(CreateClassifierOptions createClassifierOptions)
createClassifier(params, [callback()])
create_classifier(self, training_metadata, training_data, **kwargs)
create_classifier(training_metadata:, training_data:)
func createClassifier(
    trainingMetadata: Data,
    trainingData: Data,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Classifier>?, WatsonError?) -> Void)
CreateClassifier(System.IO.MemoryStream trainingMetadata, System.IO.MemoryStream trainingData)
CreateClassifier(Callback<Classifier> callback, System.IO.MemoryStream trainingMetadata, System.IO.MemoryStream trainingData)
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.

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.

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.

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) (result *ClassifierList, response *core.DetailedResponse, err 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)
ListClassifiers()
ListClassifiers(Callback<ClassifierList> callback)
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.

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.

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.

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) (result *Classifier, response *core.DetailedResponse, err 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)
GetClassifier(string classifierId)
GetClassifier(Callback<Classifier> callback, string classifierId)
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.

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.

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) (response *core.DetailedResponse, err 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)
DeleteClassifier(string classifierId)
DeleteClassifier(Callback<object> callback, string classifierId)
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.

parameters

  • Classifier ID to delete.

parameters

  • Classifier ID to delete.

Response

Response type: object

Response type: object

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