Introduction

IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the globe and present it in your language, communicate with your customers in their own language, and more.

This documentation describes Java SDK major version 9. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes Node SDK major version 6. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes Python SDK major version 5. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes Ruby SDK major version 2. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes .NET Standard SDK major version 5. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes Go SDK major version 2. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes Swift SDK major version 4. For more information about how to update your code from the previous version, see the migration guide.

This documentation describes Unity SDK major version 5. For more information about how to update your code from the previous version, see the migration guide.

The IBM Watson Unity SDK has the following requirements.

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

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

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

Maven

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

Gradle

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

GitHub

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

Installation

npm install ibm-watson@^6.0.0

GitHub

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

Installation

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

GitHub

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

Installation

gem install ibm_watson

GitHub

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

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

GitHub

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

Cocoapods

pod 'IBMWatsonLanguageTranslatorV3', '~> 4.0.0'

Carthage

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

Swift Package Manager

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

GitHub

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

Package Manager

Install-Package IBM.Watson.LanguageTranslator.v3 -Version 5.0.0

.NET CLI

dotnet add package IBM.Watson.LanguageTranslator.v3 --version 5.0.0

PackageReference

<PackageReference Include="IBM.Watson.LanguageTranslator.v3" Version="5.0.0" />

GitHub

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

GitHub

Authentication

You authenticate to the API by using IBM Cloud Identity and Access Management (IAM).

You can pass either a bearer token in an authorization header or an API key. Tokens support authenticated requests without embedding service credentials in every call. API keys use basic authentication. For more information, see Authenticating to Watson services.

  • For testing and development, you can pass an API key directly.
  • For production use, unless you use the Watson SDKs, use an IAM token.

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

curl -u "apikey:f5sAznhrKQyvBFFaZbtF60m5tzLbqWhyALQawBg5TjRI"

For IBM Cloud instances, the SDK provides initialization methods for each form of authentication.

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

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

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

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

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

IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
LanguageTranslator languageTranslator = new LanguageTranslator("{version}", authenticator);
languageTranslator.setServiceUrl("{url}");

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

const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
const { IamAuthenticator } = require('ibm-watson/auth');

const languageTranslator = new LanguageTranslatorV3({
  version: '{version}',
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  serviceUrl: '{url}',
});

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

from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
language_translator = LanguageTranslatorV3(
    version='{version}',
    authenticator=authenticator
)

language_translator.set_service_url('{url}')

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

require "ibm_watson/authenticators"
require "ibm_watson/language_translator_v3"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
language_translator = LanguageTranslatorV3.new(
  version: "{version}",
  authenticator: authenticator
)
language_translator.service_url = "{url}"

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

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

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

  options := &languagetranslatorv3.LanguageTranslatorV3Options{
    Version: "{version}",
    Authenticator: authenticator,
  }

  languageTranslator, languageTranslatorErr := languagetranslatorv3.NewLanguageTranslatorV3(options)

  if languageTranslatorErr != nil {
    panic(languageTranslatorErr)
  }

  languageTranslator.SetServiceURL("{url}")
}

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

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let languageTranslator = LanguageTranslator(version: "{version}", authenticator: authenticator)
languageTranslator.serviceURL = "{url}"

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

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

LanguageTranslatorService languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

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

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

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

var languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

Access between services

Your application might use more than one Watson service. You can grant access between services and you can grant access to more than one service for your applications.

For IBM Cloud services, the method to grant access between Watson services varies depending on the type of API key. For more information, see IAM access.

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

Make sure that you use an endpoint URL that includes the service instance ID (for example, https://api.us-south.language-translator.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.

Endpoint URLs

Identify the base URL for your service instance.

IBM Cloud URLs

The base URLs come from the service instance. To find the URL, view the service credentials by clicking the name of the service in the Resource list. Use the value of the URL. Add the method to form the complete API endpoint for your request.

The following example URL represents a Language Translator instance that is hosted in Washington DC:

https://api.us-east.language-translator.watson.cloud.ibm.com/instances/6bbda3b3-d572-45e1-8c54-22d6ed9e52c2

The following URLs represent the base URLs for Language Translator. When you call the API, use the URL that corresponds to the location of your service instance.

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

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

Set the correct service URL by specifying the serviceUrl parameter when you create the service instance.

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

Set the correct service URL by specifying the service_url property of the service instance.

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

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

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

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

Dallas API endpoint example for services managed on IBM Cloud

curl -X {request_method} -u "apikey:{apikey}" "https://api.us-south.language-translator.watson.cloud.ibm.com/instances/{instance_id}"

Your service instance might not use this URL

Default URL

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

Example for the Washington DC location

IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
LanguageTranslator languageTranslator = new LanguageTranslator("{version}", authenticator);
languageTranslator.setServiceUrl("https://api.us-east.language-translator.watson.cloud.ibm.com");

Default URL

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

Example for the Washington DC location

const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
const { IamAuthenticator } = require('ibm-watson/auth');

const languageTranslator = new LanguageTranslatorV3({
  version: '{version}',
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  serviceUrl: 'https://api.us-east.language-translator.watson.cloud.ibm.com',
});

Default URL

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

Example for the Washington DC location

from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
language_translator = LanguageTranslatorV3(
    version='{version}',
    authenticator=authenticator
)

language_translator.set_service_url('https://api.us-east.language-translator.watson.cloud.ibm.com')

Default URL

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

Example for the Washington DC location

require "ibm_watson/authenticators"
require "ibm_watson/language_translator_v3"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
language_translator = LanguageTranslatorV3.new(
  version: "{version}",
  authenticator: authenticator
)
language_translator.service_url = "https://api.us-east.language-translator.watson.cloud.ibm.com"

Default URL

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

Example for the Washington DC location

languageTranslator, languageTranslatorErr := languagetranslatorv3.NewLanguageTranslatorV3(options)

if languageTranslatorErr != nil {
  panic(languageTranslatorErr)
}

languageTranslator.SetServiceURL("https://api.us-east.language-translator.watson.cloud.ibm.com")

Default URL

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

Example for the Washington DC location

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let languageTranslator = LanguageTranslator(version: "{version}", authenticator: authenticator)
languageTranslator.serviceURL = "https://api.us-east.language-translator.watson.cloud.ibm.com"

Default URL

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

Example for the Washington DC location

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

LanguageTranslatorService languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("https://api.us-east.language-translator.watson.cloud.ibm.com");

Default URL

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

Example for the Washington DC location

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

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

var languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("https://api.us-east.language-translator.watson.cloud.ibm.com");

Disabling SSL verification

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

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

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

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

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

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

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

To disable SSL verification, set the disable_ssl_verification parameter to true in the configure_http_client() method for the service instance.

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

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

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

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

Example to disable SSL verification. Replace {apikey} and {url} with your service credentials.

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

Example to disable SSL verification

IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
LanguageTranslator languageTranslator = new LanguageTranslator("{version}", authenticator);
languageTranslator.setServiceUrl("{url}");

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

Example to disable SSL verification

const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
const { IamAuthenticator } = require('ibm-watson/auth');

const languageTranslator = new LanguageTranslatorV3({
  version: '{version}',
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  serviceUrl: '{url}',
  disableSslVerification: true,
});

Example to disable SSL verification

from ibm_watson import LanguageTranslatorV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
language_translator = LanguageTranslatorV3(
    version='{version}',
    authenticator=authenticator
)

language_translator.set_service_url('{url}')

language_translator.set_disable_ssl_verification(True)

Example to disable SSL verification

require "ibm_watson/authenticators"
require "ibm_watson/language_translator_v3"
include IBMWatson

authenticator = Authenticators::IamAuthenticator.new(
  apikey: "{apikey}"
)
language_translator = LanguageTranslatorV3.new(
  version: "{version}",
  authenticator: authenticator
)
language_translator.service_url = "{url}"

language_translator.configure_http_client(disable_ssl_verification: true)

Example to disable SSL verification

languageTranslator, languageTranslatorErr := languagetranslatorv3.NewLanguageTranslatorV3(options)

if languageTranslatorErr != nil {
  panic(languageTranslatorErr)
}

languageTranslator.SetServiceURL("{url}")

languageTranslator.DisableSSLVerification()

Example to disable SSL verification

let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
let languageTranslator = LanguageTranslator(version: "{version}", authenticator: authenticator)
languageTranslator.serviceURL = "{url}"

languageTranslator.disableSSLVerification()

Example to disable SSL verification

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

LanguageTranslatorService languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

languageTranslator.DisableSslVerification(true);

Example to disable SSL verification

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

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

var languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

languageTranslator.DisableSslVerification = true;

Versioning

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

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

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

This documentation describes the current version of Language Translator, 2018-05-01. In some cases, differences in earlier versions are noted in the descriptions of parameters and response models.

Error handling

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

ErrorResponse

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

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

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

When the Java SDK receives an error response from the Language Translator 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 Language Translator 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 Language Translator service, it generates an ApiException with the following fields.

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

When the Ruby SDK receives an error response from the Language Translator service, it generates an ApiException with the following fields.

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

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

Error

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

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

Field Description
errorDescription A message that describes the error.

When the .NET Standard SDK receives an error response from the Language Translator service, it generates a ServiceResponseException with the following fields.

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

When the Unity SDK receives an error response from the Language Translator service, it generates an IBMError with the following fields.

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

Example error handling

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

Example error handling

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

Example error handling

from ibm_watson import ApiException
try:
    # Invoke a method
except ApiException as ex:
    print "Method failed with status code " + str(ex.code) + ": " + ex.message

Example error handling

require "ibm_watson"
begin
  # Invoke a method
rescue IBMWatson::ApiException => ex
  print "Method failed with status code #{ex.code}: #{ex.error}"
end

Example error handling

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

// Instantiate a service
languageTranslator, languageTranslatorErr := languagetranslatorv3.NewLanguageTranslatorV3(options)

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

// Call a method
result, response, responseErr := languageTranslator.MethodName(&methodOptions)

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

Example error handling

languageTranslator.method() {
  response, error in

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

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

  print(result)
}

Example error handling

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

Example error handling

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

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

Data handling

Additional headers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

To pass header parameters in a single request, use the WithHeader() method as a modifier on the request before you execute it. See Data collection for an example use of this method.

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

Example header parameter in a request

curl -X {request_method} -H "Request-Header: {header_value}" "{url}/v3/{method}"

Example header parameter in a request

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

Example header parameter in a request

const parameters = {
  {parameters}
};

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

Example header parameter in a request

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

Example header parameter in a request

result, response, responseErr := languageTranslator.MethodName(
  &methodOptions{
    Headers: map[string]string{
      "Accept": "application/json",
    },
  },
)

Example header parameter in a request

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

Example header parameter in a request

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

LanguageTranslatorService languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

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

Example header parameter in a request

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

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

var languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

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

Response details

The Language Translator service might return information to the application in response headers.

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

Example request to access response headers

curl -X {request_method} {authentication_method} --include "{url}/v3/{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 = languageTranslator.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

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

language_translator.set_detailed_response(True)
response = language_translator.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 = language_translator.methodName(parameters)
# Access response from methodName
print response.result
# Access information in response headers
print response.headers
# Access HTTP response status
print response.status

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

DetailedResponse

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

Example request to access response headers

import (
  "github.com/IBM/go-sdk-core/core"
  "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
)
result, response, responseErr := languageTranslator.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

languageTranslator.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 = languageTranslator.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()
{
    languageTranslator.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, Language Translator service instances that are not part of Premium plans 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. Logging is disabled for services that are part of Premium plans.

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

You 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");

languageTranslator.setDefaultHeaders(headers);

Example request

const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
const { IamAuthenticator } = require('ibm-watson/auth');

const languageTranslator = new LanguageTranslatorV3({
  version: '{version}',
  authenticator: new IamAuthenticator({
    apikey: '{apikey}',
  }),
  serviceUrl: '{url}',
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});

Example request

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

Example request

language_translator.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")
languageTranslator.SetDefaultHeaders(headers)

Example request

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

Example request

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

LanguageTranslatorService languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

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

Example request

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

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

var languageTranslator = new LanguageTranslatorService("{version}", authenticator);
languageTranslator.SetServiceUrl("{url}");

languageTranslator.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 = languageTranslator.method(parameters).execute();

Example asynchronous request

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

Example synchronous request

response = language_translator.method_name(parameters)

or

response = language_translator.await.method_name(parameters)

Example asynchronous request

response = language_translator.async.method_name(parameters)

Methods

List supported languages

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

Lists all supported languages for translation. The method returns an array of supported languages with information about each language. Languages are listed in alphabetical order by language code (for example, af, ar). In addition to basic information about each language, the response indicates whether the language is supported_as_source for translation and supported_as_target for translation. It also lists whether the language is identifiable.

GET /v3/languages
(languageTranslator *LanguageTranslatorV3) ListLanguages(listLanguagesOptions *ListLanguagesOptions) (result *Languages, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) ListLanguagesWithContext(ctx context.Context, listLanguagesOptions *ListLanguagesOptions) (result *Languages, response *core.DetailedResponse, err error)
ServiceCall<Languages> listLanguages(ListLanguagesOptions listLanguagesOptions)
listLanguages(params)
list_languages(self,
        **kwargs
    ) -> DetailedResponse
list_languages
func listLanguages(
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Languages>?, WatsonError?) -> Void)
ListLanguages()
ListLanguages(Callback<Languages> callback)

Request

Instantiate the ListLanguagesOptions struct and set the fields to provide parameter values for the ListLanguages method.

Use the ListLanguagesOptions.Builder to create a ListLanguagesOptions object that contains the parameter values for the listLanguages method.

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

WithContext method only

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • curl -X GET --user apikey:{apikey} "{url}/v3/languages?version=2018-05-01"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    LanguageTranslatorService languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    var result = service.ListLanguages();
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &languagetranslatorv3.LanguageTranslatorV3Options{
        Version: "2018-05-01",
        Authenticator: authenticator,
      }
    
      languageTranslator, languageTranslatorErr := languagetranslatorv3.
        NewLanguageTranslatorV3(options)
    
      if languageTranslatorErr != nil {
        panic(languageTranslatorErr)
      }
    
      languageTranslator.SetServiceURL("{url}")
    
      result, response, responseErr := languageTranslator.ListLanguages(
        &languagetranslatorv3.ListLanguagesOptions{},
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
    languageTranslator.setServiceUrl("{url}");
    
    Languages languages = languageTranslator.listLanguages()
      .execute().getResult();
    
    System.out.println(languages);
  • const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const languageTranslator = new LanguageTranslatorV3({
      version: '2018-05-01',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    languageTranslator.listLanguages()
      .then(languages => {
        console.log(JSON.stringify(languages, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import LanguageTranslatorV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    language_translator = LanguageTranslatorV3(
        version='2018-05-01',
        authenticator=authenticator
    )
    
    language_translator.set_service_url('{url}')
    
    languages = language_translator.list_languages().get_result()
    print(json.dumps(languages, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/language_translator_v3"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    language_translator = LanguageTranslatorV3.new(
      version: "2018-05-01",
      authenticator: authenticator
    )
    language_translator.service_url = "{url}"
    
    languages = language_translator.list_languages
    puts JSON.pretty_generate(languages.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let languageTranslator = LanguageTranslator(version: "2018-05-01", authenticator: authenticator)
    languageTranslator.serviceURL = "{url}"
    
    languageTranslator.listLanguages() {
      response, error in
    
      guard let languages = response?.result else {
        print(error?.localizedDescription ?? "unknown error")
        return
      }
    
      print(languages)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    Languages listLanguagesResponse = null;
    service.ListLanguages(
        callback: (DetailedResponse<Languages> response, IBMError error) =>
        {
            Log.Debug("LanguageTranslatorServiceV3", "ListLanguages result: {0}", response.Response);
            listLanguagesResponse = response.Result;
        }
    );
    
    while (listLanguagesResponse == null)
        yield return null;

Response

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

The response type for listing supported languages.

Status Code

  • Success

  • Invalid request. See the response body for details.

Example responses
  • {
      "languages": [
        {
          "language": "af",
          "language_name": "Afrikaans",
          "native_language_name": "Afrikaans",
          "country_code": "ZA",
          "words_separated": true,
          "direction": "left_to_right",
          "supported_as_source": false,
          "supported_as_target": false,
          "identifiable": true
        },
        {
          "language": "ar",
          "language_name": "Arabic",
          "native_language_name": "العربية",
          "country_code": "AR",
          "words_separated": true,
          "direction": "right_to_left",
          "supported_as_source": true,
          "supported_as_target": true,
          "identifiable": true
        }
      ]
    }
  • {
      "languages": [
        {
          "language": "af",
          "language_name": "Afrikaans",
          "native_language_name": "Afrikaans",
          "country_code": "ZA",
          "words_separated": true,
          "direction": "left_to_right",
          "supported_as_source": false,
          "supported_as_target": false,
          "identifiable": true
        },
        {
          "language": "ar",
          "language_name": "Arabic",
          "native_language_name": "العربية",
          "country_code": "AR",
          "words_separated": true,
          "direction": "right_to_left",
          "supported_as_source": true,
          "supported_as_target": true,
          "identifiable": true
        }
      ]
    }

Translate

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

Translates the input text from the source language to the target language. Specify a model ID that indicates the source and target languages, or specify the source and target languages individually. You can omit the source language to have the service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language.

You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be encoded in UTF-8 format.

POST /v3/translate
(languageTranslator *LanguageTranslatorV3) Translate(translateOptions *TranslateOptions) (result *TranslationResult, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) TranslateWithContext(ctx context.Context, translateOptions *TranslateOptions) (result *TranslationResult, response *core.DetailedResponse, err error)
ServiceCall<TranslationResult> translate(TranslateOptions translateOptions)
translate(params)
translate(self,
        text: List[str],
        *,
        model_id: str = None,
        source: str = None,
        target: str = None,
        **kwargs
    ) -> DetailedResponse
translate(text:, model_id: nil, source: nil, target: nil)
func translate(
    text: [String],
    modelID: String? = nil,
    source: String? = nil,
    target: String? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<TranslationResult>?, WatsonError?) -> Void)
Translate(List<string> text, string modelId = null, string source = null, string target = null)
Translate(Callback<TranslationResult> callback, List<string> text, string modelId = null, string source = null, string target = null)

Request

Instantiate the TranslateOptions struct and set the fields to provide parameter values for the Translate method.

Use the TranslateOptions.Builder to create a TranslateOptions object that contains the parameter values for the translate method.

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

The translate request containing the text, and either a model ID or source and target language pair.

Example:

WithContext method only

The Translate options.

The translate options.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single request. Multiple elements result in multiple translations in the response.

  • The model to use for translation. For example, en-de selects the IBM-provided base model for English-to-German translation. A model ID overrides the source and target parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language.

  • Language code that specifies the language of the input text. If omitted, the service derives the source language from the input text. The input must contain sufficient text for the service to identify the language reliably.

  • Language code that specifies the target language for translation. Required if model ID is not specified.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single request. Multiple elements result in multiple translations in the response.

  • The model to use for translation. For example, en-de selects the IBM-provided base model for English-to-German translation. A model ID overrides the source and target parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language.

  • Language code that specifies the language of the input text. If omitted, the service derives the source language from the input text. The input must contain sufficient text for the service to identify the language reliably.

  • Language code that specifies the target language for translation. Required if model ID is not specified.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single request. Multiple elements result in multiple translations in the response.

  • The model to use for translation. For example, en-de selects the IBM-provided base model for English-to-German translation. A model ID overrides the source and target parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language.

  • Language code that specifies the language of the input text. If omitted, the service derives the source language from the input text. The input must contain sufficient text for the service to identify the language reliably.

  • Language code that specifies the target language for translation. Required if model ID is not specified.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single request. Multiple elements result in multiple translations in the response.

  • The model to use for translation. For example, en-de selects the IBM-provided base model for English-to-German translation. A model ID overrides the source and target parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language.

  • Language code that specifies the language of the input text. If omitted, the service derives the source language from the input text. The input must contain sufficient text for the service to identify the language reliably.

  • Language code that specifies the target language for translation. Required if model ID is not specified.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single request. Multiple elements result in multiple translations in the response.

  • The model to use for translation. For example, en-de selects the IBM-provided base model for English-to-German translation. A model ID overrides the source and target parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language.

  • Language code that specifies the language of the input text. If omitted, the service derives the source language from the input text. The input must contain sufficient text for the service to identify the language reliably.

  • Language code that specifies the target language for translation. Required if model ID is not specified.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a single request. Multiple elements result in multiple translations in the response.

  • The model to use for translation. For example, en-de selects the IBM-provided base model for English-to-German translation. A model ID overrides the source and target parameters and is required if you use a custom model. If no model ID is specified, you must specify at least a target language.

  • Language code that specifies the language of the input text. If omitted, the service derives the source language from the input text. The input must contain sufficient text for the service to identify the language reliably.

  • Language code that specifies the target language for translation. Required if model ID is not specified.

  • curl -X POST --user apikey:{apikey} --header "Content-Type: application/json" --data "{\"text\":[\"Hello, how are you today?\"],\"model_id\":\"en-es\"}" "{url}/v3/translate?version=2018-05-01"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    LanguageTranslatorService languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    var result = service.Translate(
        text: new List<string>() { "Hello, how are you today?" },
        modelId: "en-es"
        );
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &languagetranslatorv3.LanguageTranslatorV3Options{
        Version: "2018-05-01",
        Authenticator: authenticator,
      }
    
      languageTranslator, languageTranslatorErr := languagetranslatorv3.
        NewLanguageTranslatorV3(options)
    
      if languageTranslatorErr != nil {
        panic(languageTranslatorErr)
      }
    
      languageTranslator.SetServiceURL("{url}")
    
      result, response, responseErr := languageTranslator.Translate(
        &languagetranslatorv3.TranslateOptions{
          Text:    []string{"Hello, how are you today?"},
          ModelID: core.StringPtr("en-es"),
        },
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
    languageTranslator.setServiceUrl("{url}");
    
    TranslateOptions translateOptions = new TranslateOptions.Builder()
      .addText("Hello, how are you today?")
      .modelId("en-es")
      .build();
    
    TranslationResult result = languageTranslator.translate(translateOptions)
      .execute().getResult();
    
    System.out.println(result);
  • const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const languageTranslator = new LanguageTranslatorV3({
      version: '2018-05-01',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    const translateParams = {
      text: 'Hello, how are you today?',
      modelId: 'en-es',
    };
    
    languageTranslator.translate(translateParams)
      .then(translationResult => {
        console.log(JSON.stringify(translationResult, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import LanguageTranslatorV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    language_translator = LanguageTranslatorV3(
        version='2018-05-01',
        authenticator=authenticator
    )
    
    language_translator.set_service_url('{url}')
    
    translation = language_translator.translate(
        text='Hello, how are you today?',
        model_id='en-es').get_result()
    print(json.dumps(translation, indent=2, ensure_ascii=False))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/language_translator_v3"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    language_translator = LanguageTranslatorV3.new(
      version: "2018-05-01",
      authenticator: authenticator
    )
    language_translator.service_url = "{url}"
    
    translation = language_translator.translate(
      text: "Hello, how are you today?",
      model_id: "en-es"
    )
    puts JSON.pretty_generate(translation.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let languageTranslator = LanguageTranslator(version: "2018-05-01", authenticator: authenticator)
    languageTranslator.serviceURL = "{url}"
    
    languageTranslator.translate(text: ["Hello, how are you today?"], modelID: "en-es") {
      response, error in
    
      guard let translation = response?.result else {
        print(error?.localizedDescription ?? "unknown error")
        return
      }
    
      print(translation)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    TranslationResult translateResponse = null;
     service.Translate(
        callback: (DetailedResponse<TranslationResult> response, IBMError error) =>
        {
            Log.Debug("LanguageTranslatorServiceV3", "Translate result: {0}", response.Response);
            translateResponse = response.Result;
        },
        text: new List<string>() { "Hello, how are you today?" },
        modelId: "en-es"
    );
    
    while (translateResponse == null)
        yield return null;

Response

Status Code

  • Success

  • Invalid request. See the response body for details.

  • Model Not Found: the specified model_id does not exist or specified source - target language pair is not supported.

    Unable to automatically detect the source language, confidence too low: the request contains insufficient input text for the service to identify the source language reliably.

  • Request Entity Too Large: You sent a request that exceeds the maximum translation size (50 KB) supported by the service.

  • Too Many Requests: The service is currently processing too many requests. Wait a short time and try the request again. If you are submitting multiple concurrent requests, consider throttling the rate at which you submit requests.

Example responses
  • {
      "translations": [
        {
          "translation": "Hola, ¿cómo estás hoy?"
        }
      ],
      "word_count": 7,
      "character_count": 25
    }
  • {
      "translations": [
        {
          "translation": "Hola, ¿cómo estás hoy?"
        }
      ],
      "word_count": 7,
      "character_count": 25
    }

List identifiable languages

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

Lists the languages that the service can identify. Returns the language code (for example, en for English or es for Spanish) and name of each language.

GET /v3/identifiable_languages
(languageTranslator *LanguageTranslatorV3) ListIdentifiableLanguages(listIdentifiableLanguagesOptions *ListIdentifiableLanguagesOptions) (result *IdentifiableLanguages, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) ListIdentifiableLanguagesWithContext(ctx context.Context, listIdentifiableLanguagesOptions *ListIdentifiableLanguagesOptions) (result *IdentifiableLanguages, response *core.DetailedResponse, err error)
ServiceCall<IdentifiableLanguages> listIdentifiableLanguages(ListIdentifiableLanguagesOptions listIdentifiableLanguagesOptions)
listIdentifiableLanguages(params)
list_identifiable_languages(self,
        **kwargs
    ) -> DetailedResponse
list_identifiable_languages
func listIdentifiableLanguages(
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<IdentifiableLanguages>?, WatsonError?) -> Void)
ListIdentifiableLanguages()
ListIdentifiableLanguages(Callback<IdentifiableLanguages> callback)

Request

Instantiate the ListIdentifiableLanguagesOptions struct and set the fields to provide parameter values for the ListIdentifiableLanguages method.

Use the ListIdentifiableLanguagesOptions.Builder to create a ListIdentifiableLanguagesOptions object that contains the parameter values for the listIdentifiableLanguages method.

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

WithContext method only

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • curl -X GET --user apikey:{apikey} "{url}/v3/identifiable_languages?version=2018-05-01"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    LanguageTranslatorService languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    var result = service.ListIdentifiableLanguages();
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &languagetranslatorv3.LanguageTranslatorV3Options{
        Version: "2018-05-01",
        Authenticator: authenticator,
      }
    
      languageTranslator, languageTranslatorErr := languagetranslatorv3.
        NewLanguageTranslatorV3(options)
    
      if languageTranslatorErr != nil {
        panic(languageTranslatorErr)
      }
    
      languageTranslator.SetServiceURL("{url}")
    
      result, response, responseErr := languageTranslator.ListIdentifiableLanguages(
        &languagetranslatorv3.ListIdentifiableLanguagesOptions{},
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
    languageTranslator.setServiceUrl("{url}");
    
    IdentifiableLanguages languages = languageTranslator.listIdentifiableLanguages()
      .execute().getResult();
    
    System.out.println(languages);
  • const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const languageTranslator = new LanguageTranslatorV3({
      version: '2018-05-01',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    languageTranslator.listIdentifiableLanguages()
      .then(identifiedLanguages => {
        console.log(JSON.stringify(identifiedLanguages, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import LanguageTranslatorV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    language_translator = LanguageTranslatorV3(
        version='2018-05-01',
        authenticator=authenticator
    )
    
    language_translator.set_service_url('{url}')
    
    languages = language_translator.list_identifiable_languages().get_result()
    print(json.dumps(languages, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/language_translator_v3"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    language_translator = LanguageTranslatorV3.new(
      version: "2018-05-01",
      authenticator: authenticator
    )
    language_translator.service_url = "{url}"
    
    languages = language_translator.list_identifiable_languages
    puts JSON.pretty_generate(languages.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let languageTranslator = LanguageTranslator(version: "2018-05-01", authenticator: authenticator)
    languageTranslator.serviceURL = "{url}"
    
    languageTranslator.listIdentifiableLanguages() {
      response, error in
    
      guard let languagesList = response?.result else {
        print(error?.localizedDescription ?? "unknown error")
        return
      }
    
      print(languagesList)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    IdentifiableLanguages listIdentifiableLanguagesResponse = null;
    service.ListIdentifiableLanguages(
        callback: (DetailedResponse<IdentifiableLanguages> response, IBMError error) =>
        {
            Log.Debug("LanguageTranslatorServiceV3", "ListIdentifiableLanguages result: {0}", response.Response);
            listIdentifiableLanguagesResponse = response.Result;
        }
    );
    
    while (listIdentifiableLanguagesResponse == null)
        yield return null;

Response

Status Code

  • Success

  • Invalid request. See the response body for details.

Example responses
  • {
      "languages": [
        {
          "language": "af",
          "name": "Afrikaans"
        },
        {
          "language": "ar",
          "name": "Arabic"
        },
        {
          "language": "az",
          "name": "Azerbaijani"
        },
        {
          "language": "ba",
          "name": "Bashkir"
        }
      ]
    }
  • {
      "languages": [
        {
          "language": "af",
          "name": "Afrikaans"
        },
        {
          "language": "ar",
          "name": "Arabic"
        },
        {
          "language": "az",
          "name": "Azerbaijani"
        },
        {
          "language": "ba",
          "name": "Bashkir"
        }
      ]
    }

Identify language

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

Identifies the language of the input text.

POST /v3/identify
(languageTranslator *LanguageTranslatorV3) Identify(identifyOptions *IdentifyOptions) (result *IdentifiedLanguages, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) IdentifyWithContext(ctx context.Context, identifyOptions *IdentifyOptions) (result *IdentifiedLanguages, response *core.DetailedResponse, err error)
ServiceCall<IdentifiedLanguages> identify(IdentifyOptions identifyOptions)
identify(params)
identify(self,
        text: Union[str, TextIO],
        **kwargs
    ) -> DetailedResponse
identify(text:)
func identify(
    text: String,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<IdentifiedLanguages>?, WatsonError?) -> Void)
Identify(string text)
Identify(Callback<IdentifiedLanguages> callback, string text)

Request

Instantiate the IdentifyOptions struct and set the fields to provide parameter values for the Identify method.

Use the IdentifyOptions.Builder to create a IdentifyOptions object that contains the parameter values for the identify method.

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

Input text in UTF-8 format.

WithContext method only

The Identify options.

The identify options.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 format.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 format.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 format.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 format.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 format.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Input text in UTF-8 format.

  • curl -X POST --user apikey:{apikey} --header "Content-Type: text/plain" --data "Language translator translates text from one language to another" "{url}/v3/identify?version=2018-05-01"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    LanguageTranslatorService languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    var result = service.Identify(
        text: "Language translator translates text from one language to another"
        );
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &languagetranslatorv3.LanguageTranslatorV3Options{
        Version: "2018-05-01",
        Authenticator: authenticator,
      }
    
      languageTranslator, languageTranslatorErr := languagetranslatorv3.
        NewLanguageTranslatorV3(options)
    
      if languageTranslatorErr != nil {
        panic(languageTranslatorErr)
      }
    
      languageTranslator.SetServiceURL("{url}")
    
      result, response, responseErr := languageTranslator.Identify(
        &languagetranslatorv3.IdentifyOptions{
          Text: core.StringPtr("Language translator translates text from one language to another"),
        },
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
    languageTranslator.setServiceUrl("{url}");
    
    IdentifyOptions identifyOptions = new IdentifyOptions.Builder()
      .text("Language translator translates text from one language to another")
      .build();
    
    IdentifiedLanguages languages = languageTranslator.identify(identifyOptions)
      .execute().getResult();
    
    System.out.println(languages);
  • const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const languageTranslator = new LanguageTranslatorV3({
      version: '2018-05-01',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    const identifyParams = {
      text: 'Language translator translates text from one language to another'
    };
    
    languageTranslator.identify(identifyParams)
      .then(identifiedLanguages => {
        console.log(JSON.stringify(identifiedLanguages, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import LanguageTranslatorV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    language_translator = LanguageTranslatorV3(
        version='2018-05-01',
        authenticator=authenticator
    )
    
    language_translator.set_service_url('{url}')
    
    language = language_translator.identify(
        'Language translator translates text from one language to another').get_result()
    print(json.dumps(language, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/language_translator_v3"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    language_translator = LanguageTranslatorV3.new(
      version: "2018-05-01",
      authenticator: authenticator
    )
    language_translator.service_url = "{url}"
    
    language = language_translator.identify(
      text: "Language translator translates text from one language to another"
    )
    puts JSON.pretty_generate(language.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let languageTranslator = LanguageTranslator(version: "2018-05-01", authenticator: authenticator)
    languageTranslator.serviceURL = "{url}"
    
    languageTranslator.identify(text: "Language translator translates text from one language to another") {
      response, error in
    
      guard let languages = response?.result else {
        print(error?.localizedDescription ?? "unknown error")
        return
      }
    
      print(languages)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    IdentifiedLanguages identifyResponse = null;
    service.Identify(
        callback: (DetailedResponse<IdentifiedLanguages> response, IBMError error) =>
        {
            Log.Debug("LanguageTranslatorServiceV3", "Identify language result: {0}", response.Response);
            identifyResponse = response.Result;
        },
        text: "Language translator translates text from one language to another"
    );
    
    while (identifyResponse == null)
        yield return null;

Response

Status Code

  • Success

  • Invalid request. See the response body for details.

Example responses
  • {
      "languages": [
        {
          "language": "en",
          "confidence": 0.9804833843796723
        },
        {
          "language": "nn",
          "confidence": 0.005988721319786277
        },
        {
          "language": "sq",
          "confidence": 0.0036927759389060203
        },
        {
          "language": "nb",
          "confidence": 0.0035802051870239037
        }
      ]
    }
  • {
      "languages": [
        {
          "language": "en",
          "confidence": 0.9804833843796723
        },
        {
          "language": "nn",
          "confidence": 0.005988721319786277
        },
        {
          "language": "sq",
          "confidence": 0.0036927759389060203
        },
        {
          "language": "nb",
          "confidence": 0.0035802051870239037
        }
      ]
    }

List models

Lists available translation models.

Lists available translation models.

Lists available translation models.

Lists available translation models.

Lists available translation models.

Lists available translation models.

Lists available translation models.

Lists available translation models.

Lists available translation models.

GET /v3/models
(languageTranslator *LanguageTranslatorV3) ListModels(listModelsOptions *ListModelsOptions) (result *TranslationModels, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) ListModelsWithContext(ctx context.Context, listModelsOptions *ListModelsOptions) (result *TranslationModels, response *core.DetailedResponse, err error)
ServiceCall<TranslationModels> listModels(ListModelsOptions listModelsOptions)
listModels(params)
list_models(self,
        *,
        source: str = None,
        target: str = None,
        default: bool = None,
        **kwargs
    ) -> DetailedResponse
list_models(source: nil, target: nil, default: nil)
func listModels(
    source: String? = nil,
    target: String? = nil,
    `default`: Bool? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<TranslationModels>?, WatsonError?) -> Void)
ListModels(string source = null, string target = null, bool? _default = null)
ListModels(Callback<TranslationModels> callback, string source = null, string target = null, bool? _default = null)

Request

Instantiate the ListModelsOptions struct and set the fields to provide parameter values for the ListModels method.

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

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

WithContext method only

The ListModels options.

The listModels options.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Specify a language code to filter results by source language.

  • Specify a language code to filter results by target language.

  • If the default parameter isn't specified, the service returns all models (default and non-default) for each language pair. To return only default models, set this parameter to true. To return only non-default models, set this parameter to false. There is exactly one default model, the IBM-provided base model, per language pair.

  • curl -X GET --user apikey:{apikey} "{url}/v3/models?version=2018-05-01"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    LanguageTranslatorService languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    var result = service.ListModels();
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &languagetranslatorv3.LanguageTranslatorV3Options{
        Version: "2018-05-01",
        Authenticator: authenticator,
      }
    
      languageTranslator, languageTranslatorErr := languagetranslatorv3.
        NewLanguageTranslatorV3(options)
    
      if languageTranslatorErr != nil {
        panic(languageTranslatorErr)
      }
    
      languageTranslator.SetServiceURL("{url}")
    
      result, response, responseErr := languageTranslator.ListModels(
        &languagetranslatorv3.ListModelsOptions{},
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
    languageTranslator.setServiceUrl("{url}");
    
    TranslationModels models = languageTranslator.listModels()
      .execute().getResult();
    
    System.out.println(models);
  • const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const languageTranslator = new LanguageTranslatorV3({
      version: '2018-05-01',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    languageTranslator.listModels()
      .then(translationModels => {
        console.log(JSON.stringify(translationModels, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import LanguageTranslatorV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    language_translator = LanguageTranslatorV3(
        version='2018-05-01',
        authenticator=authenticator
    )
    
    language_translator.set_service_url('{url}')
    
    models = language_translator.list_models().get_result()
    print(json.dumps(models, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/language_translator_v3"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    language_translator = LanguageTranslatorV3.new(
      version: "2018-05-01",
      authenticator: authenticator
    )
    language_translator.service_url = "{url}"
    
    models = language_translator.list_models
    puts JSON.pretty_generate(models.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let languageTranslator = LanguageTranslator(version: "2018-05-01", authenticator: authenticator)
    languageTranslator.serviceURL = "{url}"
    
    languageTranslator.listModels() {
      response, error in
    
      guard let models = response?.result else {
        print(error?.localizedDescription ?? "unknown error")
        return
      }
    
      print(models)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    TranslationModels listModelsResponse = null;
    service.ListModels(
        callback: (DetailedResponse<TranslationModels> response, IBMError error) =>
        {
            Log.Debug("LanguageTranslatorServiceV3", "ListModels result: {0}", response.Response);
            listModelsResponse = response.Result;
        }
    );
    
    while (listModelsResponse == null)
        yield return null;

Response

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

The response type for listing existing translation models.

Status Code

  • Success

  • Invalid request. See the response body for details.

Example responses
  • {
      "models": [
        {
          "model_id": "en-nl",
          "source": "en",
          "target": "nl",
          "base_model_id": "",
          "domain": "general",
          "customizable": true,
          "default_model": true,
          "owner": "",
          "status": "available",
          "name": "en-nl"
        },
        {
          "model_id": "en-tr",
          "source": "en",
          "target": "tr",
          "base_model_id": "",
          "domain": "general",
          "customizable": true,
          "default_model": true,
          "owner": "",
          "status": "available",
          "name": "en-tr"
        }
      ]
    }
  • {
      "models": [
        {
          "model_id": "en-nl",
          "source": "en",
          "target": "nl",
          "base_model_id": "",
          "domain": "general",
          "customizable": true,
          "default_model": true,
          "owner": "",
          "status": "available",
          "name": "en-nl"
        },
        {
          "model_id": "en-tr",
          "source": "en",
          "target": "tr",
          "base_model_id": "",
          "domain": "general",
          "customizable": true,
          "default_model": true,
          "owner": "",
          "status": "available",
          "name": "en-tr"
        }
      ]
    }

Create model

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv"

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

Uploads training files to customize a translation model. You can customize a model with a forced glossary or with a parallel corpus:

  • Use a forced glossary to force certain terms and phrases to be translated in a specific way. You can upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model is limited to 10 MB.
  • Use a parallel corpus when you want your custom model to learn from general translation patterns in parallel sentences in your samples. What your model learns from a parallel corpus can improve translation results for input text that the model has not been trained on. You can upload multiple parallel corpora files with a request. To successfully train with parallel corpora, the corpora files must contain a cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a custom model is limited to 250 MB.

Depending on the type of customization and the size of the uploaded files, training time can range from minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then customize the resulting model with a forced glossary.

You can create a maximum of 10 custom models per language pair. For more information about customizing a translation model, including the formatting and character restrictions for data files, see Customizing your model.

Supported file formats

You can provide your training data for customization in the following document formats:

  • TMX (.tmx) - Translation Memory eXchange (TMX) is an XML specification for the exchange of translation memories.
  • XLIFF (.xliff) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories.
  • CSV (.csv) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • TSV (.tsv or .tab) - Tab-separated values (TSV) file with two columns for aligned sentences and phrases. The first row must have two language codes. The first column is for the source language code, and the second column is for the target language code.
  • JSON (.json) - Custom JSON format for specifying aligned sentences and phrases.
  • Microsoft Excel (.xls or .xlsx) - Excel file with the first two columns for aligned sentences and phrases. The first row contains the language code.

You must encode all text data in UTF-8 format. For more information, see Supported document formats for training data.

Specifying file formats

You can indicate the format of a file by including the file extension with the file name. Use the file extensions shown in Supported file formats.

Alternatively, you can omit the file extension and specify one of the following content-type specifications for the file:

  • TMX - application/x-tmx+xml
  • XLIFF - application/xliff+xml
  • CSV - text/csv
  • TSV - text/tab-separated-values
  • JSON - application/json
  • Microsoft Excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

For example, with curl, use the following content-type specification to indicate the format of a CSV file named glossary:

--form "forced_glossary=@glossary;type=text/csv".

POST /v3/models
(languageTranslator *LanguageTranslatorV3) CreateModel(createModelOptions *CreateModelOptions) (result *TranslationModel, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) CreateModelWithContext(ctx context.Context, createModelOptions *CreateModelOptions) (result *TranslationModel, response *core.DetailedResponse, err error)
ServiceCall<TranslationModel> createModel(CreateModelOptions createModelOptions)
createModel(params)
create_model(self,
        base_model_id: str,
        *,
        forced_glossary: BinaryIO = None,
        parallel_corpus: BinaryIO = None,
        name: str = None,
        **kwargs
    ) -> DetailedResponse
create_model(base_model_id:, forced_glossary: nil, parallel_corpus: nil, name: nil)
func createModel(
    baseModelID: String,
    forcedGlossary: Data? = nil,
    parallelCorpus: Data? = nil,
    name: String? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<TranslationModel>?, WatsonError?) -> Void)
CreateModel(string baseModelId, System.IO.MemoryStream forcedGlossary = null, System.IO.MemoryStream parallelCorpus = null, string name = null)
CreateModel(Callback<TranslationModel> callback, string baseModelId, System.IO.MemoryStream forcedGlossary = null, System.IO.MemoryStream parallelCorpus = null, string name = null)

Request

Instantiate the CreateModelOptions struct and set the fields to provide parameter values for the CreateModel method.

Use the CreateModelOptions.Builder to create a CreateModelOptions object that contains the parameter values for the createModel method.

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

Form Parameters

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}.

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}.

WithContext method only

The CreateModel options.

The createModel options.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}..

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}..

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}..

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}..

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}..

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}..

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}..

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}..

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}..

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}..

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • The ID of the translation model to use as the base for customization. To see available models and IDs, use the List models method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary.

  • A file with forced glossary terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations.

    You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB. A forced glossary must contain single words or short phrases. For more information, see Supported file formats in the method description.

    With curl, use --form forced_glossary=@{filename}..

  • A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a maximum of 500,000 parallel sentences across all corpora.

    A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can have a cumulative maximum size of 250 MB. For more information, see Supported file formats in the method description.

    With curl, use --form parallel_corpus=@{filename}..

  • An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 characters.

  • curl -X POST --user apikey:{apikey} --form forced_glossary=@glossary.tmx "{url}/v3/models?version=2018-05-01&base_model_id=en-es&name=custom-en-es"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    LanguageTranslatorService languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    DetailedResponse<TranslationModel> result;
    
    using (FileStream fs = File.OpenRead("glossary.tmx"))
    {
        using (MemoryStream ms = new MemoryStream())
        {
            fs.CopyTo(ms);
            result = service.CreateModel(
                baseModelId: "en-es",
                forcedGlossary: ms,
                name: "custom-en-es"
                );
        }
    }
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/languagetranslatorv3"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &languagetranslatorv3.LanguageTranslatorV3Options{
        Version: "2018-05-01",
        Authenticator: authenticator,
      }
    
      languageTranslator, languageTranslatorErr := languagetranslatorv3.
        NewLanguageTranslatorV3(options)
    
      if languageTranslatorErr != nil {
        panic(languageTranslatorErr)
      }
    
      languageTranslator.SetServiceURL("{url}")
    
      glossary, glossaryErr := os.Open("glossary.tmx")
      if glossaryErr != nil {
        panic(glossaryErr)
        }
      defer glossary.Close()
    
      result, response, responseErr := languageTranslator.CreateModel(
        &languagetranslatorv3.CreateModelOptions{
          BaseModelID:    core.StringPtr("en-es"),
          Name:           core.StringPtr("custom-en-es"),
          ForcedGlossary: glossary,
        },
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
    languageTranslator.setServiceUrl("{url}");
    
    File glossary = new File("glossary.tmx");
    CreateModelOptions createModelOptions = new CreateModelOptions.Builder()
      .baseModelId("en-es")
      .name("custom-en-es")
      .forcedGlossary(glossary)
      .build();
    
    TranslationModel model = languageTranslator.createModel(createModelOptions)
      .execute().getResult();
    
    System.out.println(model);
  • const fs = require('fs');
    const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const languageTranslator = new LanguageTranslatorV3({
      version: '2018-05-01',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    const createModelParams = {
      name: 'custom-en-es',
      baseModelId: 'en-es',
      forcedGlossary: fs.createReadStream('./glossary.tmx'),
    };
    
    languageTranslator.createModel(createModelParams)
      .then(translationModel => {
        console.log(JSON.stringify(translationModel, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import LanguageTranslatorV3
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    language_translator = LanguageTranslatorV3(
        version='2018-05-01',
        authenticator=authenticator
    )
    
    language_translator.set_service_url('{url}')
    
    with open('glossary.tmx', 'rb') as glossary:
        response = language_translator.create_model(
            base_model_id = 'en-es',
            forced_glossary = glossary,
            name = 'custom-en-es'
            ).get_result()
        print(json.dumps(response, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/language_translator_v3"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    language_translator = LanguageTranslatorV3.new(
      version: "2018-05-01",
      authenticator: authenticator
    )
    language_translator.service_url = "{url}"
    
    File.open("glossary.tmx") do |glossary|
      response = language_translator.create_model(
        base_model_id: "en-es",
        name: "custom-en-es",
        forced_glossary: glossary
      )
      puts JSON.pretty_generate(response.result)
    end
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let languageTranslator = LanguageTranslator(version: "2018-05-01", authenticator: authenticator)
    languageTranslator.serviceURL = "{url}"
    
    let glossaryURL = Bundle.main.url(forResource: "glossary", withExtension: "tmx")
    let glossary = try! Data(contentsOf: glossaryURL!)
    languageTranslator.createModel(baseModelID: "en-es", forcedGlossary: glossary, name: "custom-en-es") {
      response, error in
    
      guard let model = response?.result else {
        print(error?.localizedDescription ?? "unknown error")
        return
      }
    
      print(model)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var languageTranslator = new LanguageTranslatorService("2018-05-01", authenticator);
    languageTranslator.SetServiceUrl("{url}");
    
    TranslationModel createModelResponse = null;
    using (FileStream fs = File.OpenRead("glossary.tmx"))
    {
        using (MemoryStream ms = new MemoryStream())
        {
            fs.CopyTo(ms);
            service.CreateModel(
                callback: (DetailedResponse<TranslationModel> response, IBMError error) =>
                {
                    Log.Debug("LanguageTranslatorServiceV3", "CreateModel result: {0}", response.Response);
                    createModelResponse = response.Result;
                    customModelId = createModelResponse.ModelId;
                },
                baseModelId: "en-es",
                forcedGlossary: ms,
                name: "custom-en-es"
            );
    
            while (createModelResponse == null)
                yield return null;
        }
    }

Response

Response payload for models.

Response payload for models.

Response payload for models.

Response payload for models.

Response payload for models.

Response payload for models.

Response payload for models.

Response payload for models.

Response payload for models.

Status Code

  • Success: Training has successfully started

  • Bad request: The base_model_id is not specified or you have reached the maximum limit of customizations for this service instance.

  • Forbidden: You may have reached the limit of 10 custom models per language pair or the service instance's plan id does not allow for customization. Currently, only service instances on the advanced or premium plans are allowed to customize

  • Not found: The base_model_id value is invalid

  • File size exceeded: Payload body exceeded the limit

Example responses
  • {
      "model_id": "9f8d9c6f-2123-462f-9793-f17fdcb77cd6",
      "source": "en",
      "target": "es",
      "base_model_id": "en-es",
      "domain": "general",
      "customizable": false,
      "default_model": false,
      "owner": "212eabae-32bb-4e7d-8873-b28e2364fd11",
      "status": "dispatching",
      "name": "custom-en-es"
    }
  • {
      "model_id": "9f8d9c6f-2123-462f-9793-f17fdcb77cd6",
      "source": "en",
      "target": "es",
      "base_model_id": "en-es",
      "domain": "general",
      "customizable": false,
      "default_model": false,
      "owner": "212eabae-32bb-4e7d-8873-b28e2364fd11",
      "status": "dispatching",
      "name": "custom-en-es"
    }

Delete model

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

Deletes a custom translation model.

DELETE /v3/models/{model_id}
(languageTranslator *LanguageTranslatorV3) DeleteModel(deleteModelOptions *DeleteModelOptions) (result *DeleteModelResult, response *core.DetailedResponse, err error)
(languageTranslator *LanguageTranslatorV3) DeleteModelWithContext(ctx context.Context, deleteModelOptions *DeleteModelOptions) (result *DeleteModelResult, response *core.DetailedResponse, err error)
ServiceCall<DeleteModelResult> deleteModel(DeleteModelOptions deleteModelOptions)
deleteModel(params)
delete_model(self,
        model_id: str,
        **kwargs
    ) -> DetailedResponse
delete_model(model_id:)
func deleteModel(
    modelID: String,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<DeleteModelResult>?, WatsonError?) -> Void)
DeleteModel(string modelId)
DeleteModel(Callback<DeleteModelResult> callback, string modelId)

Request

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

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

Path Parameters

  • Model ID of the model to delete.

Query Parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

WithContext method only

The DeleteModel options.

The deleteModel options.

parameters

  • Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current version is 2018-05-01.

  • Model ID of the model to delete.

parameters

  • Release date of the version of the API you w