Curl Node Java Python

Language Translator

API Reference

Introduction

API Reference pages provide an easy way for you to see the methods that are provided by a service and how to call them. This column provides general information and explains the parameters that are required by methods when called from different languages. Its content changes based on the selected langauge. On screens that are wide enough, the right column provides selectable tabs that show how to make sample method calls in REST (via the cURL command), Node.js, and Java, and includes example responses to those calls. On narrow screens, these examples are inlined, and you can access the page navigation and switch between REST, Node.js, and Java examples from the menu at the left.

API Endpoint

https://gateway.watsonplatform.net/language-translator/api

Important: If you have Bluemix Dedicated, this may not be your service endpoint. Double check your endpoint URL on the Service Credentials page in your instance of the Language Translator service on Bluemix.

The code examples on this tab use the client-side library that is provided for Node.js, rather than issuing REST calls.

Node

npm install watson-developer-cloud

The code examples on this tab use the client-side library that is provided for java, rather than issuing REST calls.

Maven

<dependency>
        <groupId>com.ibm.watson.developer_cloud</groupId>
        <artifactId>java-sdk</artifactId>
        <version>3.3.1</version>
        </dependency>

Gradle


    compile 'com.ibm.watson.developer_cloud:java-sdk:3.3.1'
    

Python

pip install --upgrade watson-developer-cloud

API explorer

To interact with this API, use the Language Translator Service API explorer. Use the explorer to test your calls to the API, and to view live responses from the server.

Authentication

You authenticate to the Language Translator API by providing the username and password that are provided in the service credentials for the service instance that you want to use. The API uses Basic Authentication.

After creating an instance of the Language Translator service, select Service Credentials from the left navigation for its dashboard to see the username and password that are associated with that instance.

Replace {username} and {password} with your credentials


curl -u "{username}":"{password}" \
"https://gateway.watsonplatform.net/language-translator/api/v2"

var watson = require('watson-developer-cloud');
var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});

LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}","{password}");

from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

Methods

Translate

Translates input text from the source language to the target language.

Use GET /v2/translate for smaller request data sizes and for URL query parameters, and use POST /v2/translate for larger request data sizes and for JSON requests.


GET  /v2/translate
POST  /v2/translate

Request

Parameter Type Description
model_id query The unique model_id of the translation model used to translate text. The model_id inherently specifies source, target language, and domain. If the model_id is specified, there is no need for the source and target parameters, and the values will be ignored.
source query Used in combination with target as an alternative way to select the model for translation. When target and source are set, and model_id is not set, the system choose a default model with the right language pair to translate (usually the model based on the news domain).
target query Translation target language in 2 or 5 letter language code. Should use 2 letter codes except for when clarifying between multiple supported languages. When model_id is used directly, it will override the source-target language combination. Also, when a 2 letter language code is used, and no suitable default is found (such as “zh”), it returns an error.
text query (Required) Input text in UTF-8 encoding. Multiple text query parameters indicate multiple input paragraphs, and a single string is valid input.
accept header Describes the format of the return values. Valid values are “text/plain”, or “application/json”. When left undefined, empty, or '*/*', the default is "text/plain".

Example GET request


curl -u "{username}":"{password}" \
"https://gateway.watsonplatform.net/language-translator/api/v2/translate?source=en&target=es&text=hello"

Example POST request


curl -u "{username}":"{password}" \
-X POST \
-F "text=Hello World" \
-F "source=en" \
-F "target=es" \
"https://gateway.watsonplatform.net/language-translator/api/v2/translate"
Parameter Type Description
model_id string The unique model_id of the translation model used to translate text. The model_id inherently specifies source, target language, and domain. If the model_id is specified, there is no need for the source and target parameters, and the values will be ignored.
source string Used in combination with target as an alternative way to select the model for translation. When target and source are set, and model_id is not set, the system choose a default model with the right language pair to translate (usually the model based on the news domain).
target string Translation target language in 2 or 5 letter language code. Should use 2 letter codes except for when clarifying between multiple supported languages. When model_id is used directly, it will override the source-target language combination. Also, when a 2 letter language code is used, and no suitable default is found (such as “zh”), it returns an error.
text string (Required) Input text in UTF-8 encoding. Multiple text query parameters indicate multiple input paragraphs, and a single string is valid input.

Example request


var watson = require('watson-developer-cloud');
var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});
language_translator.translate({
    text: 'hello',
    source: 'en',
    target: 'es'
  }, function(err, translation) {
    if (err)
      console.log(err)
    else
      console.log(translation);
});
Parameter Type Description
model_id string The unique model_id of the translation model used to translate text. The model_id inherently specifies source, target language, and domain. If the model_id is specified, there is no need for the source and target parameters, and the values will be ignored.
source string To be used in combination with target as an alternative way to select the model for translation. When both are set and model_id is NOT set, the system will choose a default model with the right language pair to translate (usually the model based on the news
target string To be used in combination with source as an alternative way to select which model is used for translation
text string (Required) Input text in UTF-8 encoding. Multiple text query parameters indicate multiple input paragraphs, and a single string is valid input.

Example request


LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}","{password}");

TranslationResult result = service.translate("hello", "en", "es");
System.out.println(result);
Parameter Type Description
model_id string The unique model_id of the translation model used to translate text. The model_id inherently specifies source, target language, and domain. If the model_id is specified, there is no need for the source and target parameters, and the values will be ignored.
source string To be used in combination with target as an alternative way to select the model for translation. When both are set and model_id is NOT set, the system will choose a default model with the right language pair to translate (usually the model based on the news
target string To be used in combination with source as an alternative way to select which model is used for translation
text string (Required) Input text in UTF-8 encoding. Multiple text query parameters indicate multiple input paragraphs, and a single string is valid input.

Example request


import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

translation = language_translator.translate(
    text='hello',
    source='en',
    target='es')
print(json.dumps(translation, indent=2, ensure_ascii=False))

Response

Name Description
translations Array of translation output, corresponding to the list of input text
translation List of translation output in UTF-8, corresponding to the list of input text
word_count Number of words of the complete input text
character_count Number of characters of the complete input text

Example response


com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationResult

{
  "translations": [{
    "translation": "Hola"
  }],
  "word_count": 1,
  "character_count": 5
}

Identifiable languages

Return the list of languages it can detect.


GET  /v2/identifiable_languages

Request

No arguments

Example request


  curl -u "{username}":"{password}" \
  "https://gateway.watsonplatform.net/language-translator/api/v2/identifiable_languages"
  

var watson = require('watson-developer-cloud');
var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});
language_translator.getIdentifiableLanguages(null,
  function(err, languages) {
    if (err)
      console.log(err)
    else
      console.log(languages);
});

LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}","{password}");

List <IdentifiableLanguages> langs = service.getIdentifiableLanguages();
System.out.println(langs);

import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

languages = language_translator.get_identifiable_languages()
print(json.dumps(languages, indent=2))

Response

Name Description
languages Array of languages
language The 2 or 5 letter language code
name The language name

Example response


com.ibm.watson.developer_cloud.language_translator.v2.model.IdentifiableLanguage

{
    "languages": [
        {
            "language": "af",
            "name": "Afrikaans"
        },
        {
            "language": "ar",
            "name": "Arabic"
        },
        {
            "language": "az",
            "name": "Azerbaijani"
        },
        {
            "language": "ba",
            "name": "Bashkir"
        },
        //...
    ]
}

Identify language

Identify the language in which a text is written.


GET  /v2/identify
POST  /v2/identify

Request

Parameter Type Description
text query for GET
text block for POST
(Required) Input text in UTF-8 format
content-type header (Required) Describes the format of the request values. Default value is "text/plain".
accept header Describes the format of the return values. Valid values are "text/plain" (default), or "application/json". To retrieve a JSON object containing a ranking of identified languages with confidence scores, set the accept header parameter to "application/json".

Example GET request


curl -u "{username}":"{password}" \
"https://gateway.watsonplatform.net/language-translator/api/v2/identify?text=this+is+a+test"

Example POST request


curl -u "{username}":"{password}" \
-H "content-type: text/plain" \
-H "accept: application/json" \
-X POST \
-d "this is a test" \
"https://gateway.watsonplatform.net/language-translator/api/v2/identify"
Parameter Type Description
text string Input text in UTF-8 format

Example request


var watson = require('watson-developer-cloud');
var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});
language_translator.identify({ text: 'this is a test'},
  function(err, identifiedLanguages) {
    if (err)
      console.log(err)
    else
      console.log(identifiedLanguages);
});
Parameter Type Description
text string Input text in UTF-8 format

Example request


LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}","{password}");

List <IdentifiedLanguage> langs = service.identify("this is a test").execute();
System.out.println(langs);
Parameter Type Description
text string Input text in UTF-8 format

Example request


import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

language = language_translator.identify('this is a test')
print(json.dumps(language, indent=2))

Response

Name Description
languages Array of languages
language The 2 letter language code
confidence A ranking of languages with confidence scores

Example response


com.ibm.watson.developer_cloud.language_translator.v2.model.IdentifiedLanguage

{
    "languages": [
        {
            "confidence": 0.9143,
            "language": "en-US"
        },
        {
            "confidence": 0.0396,
            "language": "hu-HU"
        },
        {
            "confidence": 0.0093,
            "language": "ro-RO"
        },
        {
            "confidence": 0.005,
            "language": "nl-NL"
        },
        //...
    ]
}

List models

Lists available models for the Language translator service with option to filter by source or by target language.


GET  /v2/models

Request

Parameter Type Description
default query Valid values are leaving it unset, 'true' and 'false'. When 'true', it filters models to return the default model or models. When 'false' it returns the non-default model or models. If not set, all models (default and non-default) return.
source query Define with target. Filters models by source language.
target
query Define with source. Filters models by target language.

Example request


curl -u "{username}":"{password}" \
"https://gateway.watsonplatform.net/language-translator/api/v2/models"
Parameter Type Description
default string Valid values are leaving it unset, 'true' and 'false'. When 'true', it filters models to return the default model or models. When 'false' it returns the non-default model or models. If not set, all models (default and non-default) return.
source string Define with target. Filters models by source language.
target
string Define with source. Filters models by target language.

Example request


var watson = require('watson-developer-cloud');
var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});

language_translator.getModels({}, function(err, models) {
    if (err)
      console.log(err)
    else
      console.log(models);
});
Parameter Type Description
default string Valid values are leaving it unset, 'true' and 'false'. When 'true', it filters models to return the default model or models. When 'false' it returns the non-default model or models. If not set, all models (default and non-default) return.
source string Define with target. Filters models by source language.
target
string Define with source. Filters models by target language.

Example request


LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}","{password}");

List <TranslationModel> models = service.getModels();
System.out.println(models);
Parameter Type Description
default string Valid values are leaving it unset, 'true' and 'false'. When 'true', it filters models to return the default model or models. When 'false' it returns the non-default model or models. If not set, all models (default and non-default) return.
source string Define with target. Filters models by source language.
target
string Define with source. Filters models by target language.

Example request


import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

models = language_translator.get_models()
print(json.dumps(models, indent=2))

Response

Name Description
model_id A globally unique string that identifies the underlying model used for translation. This string contains all the information about source language, target language, and domain.
source Translation source language in 2 or 5 letter language code. Should use 2 letter codes except for when clarifying between multiple supported languages. When model_id is used directly, it will override the source-target language combination. Also, when a 2 letter language code is used, and no suitable default is found, it returns an error.
target Translation target language in 2 or 5 letter language code. Should use 2 letter codes except for when clarifying between multiple supported languages. When model_id is used directly, it will override the source-target language combination. Also, when a 2 letter language code is used, and no suitable default is found, it returns an error.
base_model_id For a model, returns the base model it was trained on. For a base model, the response value is empty.
customizable Describes whether this model can be used as a base for customization. Customized models are not further customizable, and we don't allow the customization of certain base models.
owner Either an empty string, indicating it’s a model trained by IBM, or the bluemix-instance-id of the instance where the model was created.
status Availability of a model. Valid response values are "available", "training", or "error".
default_model Describes whether this model is considered default, and whether it is used when the source and target languages are specified without the model_id.
domain The domain of the translation model.
name If a model is trained by a user, there could be an optional “name” parameter attached during training to help the user identify his model.

Example response


com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationModel

{
  models: [{
    "model_id ": "3e7dfdbe-f757-4150-afee-458e71eb93fb",
    "source": "en",
    "target": "es",
    "base_model_id": "en-es",
    "customizable": "false",
    "default_model": "false",
    "domain": "travel",
    "owner": "74a239fa-f2db-42ef-8737-7bf74f49e35f",
    "status": "available",
    "name": "mymodel"
  }]
}

Create model

Uploads a TMX glossary file on top of a domain to customize a translation model.

Depending on the size of the file, training can range from minutes for a glossary to several hours for a large parallel corpus. Glossary files must be less than 10 MB. The cumulative file size of all uploaded glossary and corpus files is limited to 250 MB.


POST  /v2/models

Request

Parameter Type Description
base_model_id query (Required). Specifies the domain model that is used as the base for the training. To see current supported domain models, use the GET /v2/models method.
name query The model name. Valid characters are letters, numbers, -, and _. No spaces.

Specify one or more of the following file options:

forced_glossary
file A TMX file with your customizations. As a general rule, anything that is specified in this file completely overwrites the domain data translation. However, high frequency or high confidence phrase translations will not be overwritten (the word "policy", for example). This helps to avoid inadvertently changing these high confidence translations, and will result in such words, when used in "forced_glossary", to be ignored. You can upload only one glossary with a file size less than 10 MB per call.
parallel_corpus
file A TMX file that contains entries that are treated as a parallel corpus instead of a glossary.
monolingual_corpus
file A UTF-8 encoded plain text file that is used to customize the target language model.

Example request


curl -u "{username}":"{password}" \
-X POST \
-F base_model_id="en-es" \
-F name="custom-english-to-spanish" \
-F forced_glossary=@glossary.tmx \
"https://gateway.watsonplatform.net/language-translator/api/v2/models"

var watson = require('watson-developer-cloud');
var fs = require('fs');

var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});

var params = {
  name: 'custom-english-to-spanish',
  base_model_id: 'en-es',
  forced_glossary: fs.createReadStream('glossary.tmx')
};

language_translator.createModel(params,
  function(err, model) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(model, null, 2));
  }
);

LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}", "{password}");

Map<String, Object> params = new HashMap<String, Object>();
params.put("name", "custom-english-to-spanish");
params.put("base_model_id", "en-es");
params.put("forced_glossary", new File("glossary.tmx"));

TranslationModel model = service.createModel(params);
System.out.println(model);

import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

with open('glossary.tmx', 'rb') as training_data:
    custom_model = language_translator.create_model(
        base_model_id = 'en-es',
        name = 'custom-english-to-spanish',
        forced_glossary = training_data)
    print(json.dumps(custom_model, indent=2))

Response

Name Description
model_id The identifier for the new model. Use this identifier to get the training status.

Example response


com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationModel

{
  "model_id": "3e7dfdbe-f757-4150-afee-458e71eb93fb"
}

Delete model

Deletes trained translation models.


DELETE  /v2/models/{model_id}

Request

Parameter Type Description
model_id pathstring (Required). The model identifier.

Example request

Replace {model_id} with the model identifier


curl -u "{username}":"{password}" \
-X DELETE
"https://gateway.watsonplatform.net/language-translator/api/v2/models/{model_id}"

var watson = require('watson-developer-cloud');

var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});

language_translator.deleteModel({ model_id:'{model_id}'},
  function(err) {
    if (err)
      console.log('error:', err);
  }
);

LanguageTranslator service = new LanguageTranslator();
service.setUsernameAndPassword("{username}", "{password}");

service.deleteModel("{model_id}");

import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

model = language_translator.delete_model('{model_id}')
print(json.dumps(model, indent=2))

Response

Name Description
status "OK" indicates that the model was successfully deleted.

Example response


{
  "status" : "OK"
}

Get model details

Returns information, including training status, about a specified translation model.


GET  /v2/models/{model_id}

Request

Parameter Type Description
model_id path (Required). The model identifier.

Example request

Replace {model_id} with the model identifier


curl -u "{username}":"{password}" \
"https://gateway.watsonplatform.net/language-translator/api/v2/models/{model_id}"

var watson = require('watson-developer-cloud');

var language_translator = watson.language_translator({
  username: '{username}',
  password: '{password}',
  version: 'v2'
});

language_translator.getModel({ model_id:'{model_id}'},
  function(err) {
    if (err)
      console.log('error:', err);
  }
);

curl -u "{username}":"{password}" \
"https://gateway.watsonplatform.net/language-translator/api/v2/models/{model_id}"

import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator

language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

model_details = language_translator.get_model('{model_id}')
print(json.dumps(model_details, indent=2))

Response

Name Description
model_id A globally unique string that identifies the underlying model used for translation. This string contains all the information about source language, target language, and domain.
source Translation source language in 2 or 5 letter language code. Should use 2 letter codes except for when clarifying between multiple supported languages. When model_id is used directly, it will override the source-target language combination. Also, when a 2 letter language code is used, and no suitable default is found, it returns an error.
target Translation target language in 2 or 5 letter language code. Should use 2 letter codes except for when clarifying between multiple supported languages. When model_id is used directly, it will override the source-target language combination. Also, when a 2 letter language code is used, and no suitable default is found, it returns an error.
base_model_id For a custom model, returns the base model it was trained on. For a base model, the response value is empty.
customizable Describes whether this model can be used as a base for customization. Customized models are not further customizable, and we don't allow the customization of certain base models.
owner Either an empty string, indicating it’s a model trained by IBM, or the bluemix-instance-id of the instance where the model was created.
default_model Describes whether this model is considered default, and whether it is used when the source and target languages are specified without the model_id.
domain The domain of the translation model.
name If a model is trained by a user, there could be an optional “name” parameter attached during training to help the user identify his model.
status The status of training. Possible responses are:
  • training - training is still in progress
  • error - training did not complete because of an error
  • available - training completed and the service is now available

Example response


com.ibm.watson.developer_cloud.language_translator.v2.model.TranslationModel

{
  models: [{
    "model_id ": "3e7dfdbe-f757-4150-afee-458e71eb93fb",
    "source": "en",
    "target": "es",
    "base_model_id": "en-es",
    "customizable": "false",
    "default_model": "false",
    "domain": "travel",
    "owner": "74a239fa-f2db-42ef-8737-7bf74f49e35f",
    "status": "available",
    "name": "mymodel"
  }]
}

Data collection

By default, Bluemix collects data from all requests and uses the data to improve the services. If you do not want to share your data, set a header parameter X-Watson-Learning-Opt-Out with the value true for all requests. If you do not specify this header in all payload data, data is collected and used to improve the service.

Error handling

The Language Translation service uses standard HTTP response codes to display whether a method completed successfully. A 200 response always indicates success. A 400 type response is some sort of failure, and a 500 type response usually indicates an internal system error.

Error information

Status Description
200 - OK Success.
400 - Bad Request Missing a required parameter, or invalid parameter value.
401 - Unauthorized No API key provided, or the API key provided was not valid.
404 - Not Found The requested item or parameter doesn't exist.
500 - Server Errors Internal server error.

Error format

Name Description
error Error description.
code HTTP Status code.
help (Optional)Help message.

Catching an error


curl "https://gateway.watsonplatform.net/language-translator/api/v2/translate?source=en&target=es"

language_translator.translate({
    //text: 'hello',
    source: 'en',
    target: 'es'
  }, function(err, translation) {
  // The error will be the first argument of the callback
    if (err)
      console.log(err)
});

LanguageTranslator service = new LanguageTranslator();

TranslationResult translation = null;
try {
  translation = service.translate(null, "en", "es");
} catch (IllegalArgumentException e) {
  // Missing or invalid parameter
} catch (BadRequestException e) {
  // Missing or invalid parameter
} catch (UnauthorizedException e) {
  // Access is denied due to invalid credentials
} catch (ForbiddenException e) {
  // Forbidden: Service refuse the request
} catch (NotFoundException e) {
  // Not found
} catch (TooManyRequestsException e) {
  // Too many requests
} catch (InternalServerErrorException e) {
  // Internal Server Error
} catch (ServiceUnavailableException e) {
  // Service Unavailable
}

import json
from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslator


language_translator = LanguageTranslator(
    username='{username}',
    password='{password}')

translation = language_translator.translate(
    #missing 'text' parameter
    source='en',
    target='es')
print(json.dumps(translation, indent=2, ensure_ascii=False))

Example error


{
  "error": "Missing required parameter: text",
  "code": 400
}

Traceback (most recent call last):
  File "LT-python.py", line 11, in <module>
    target='es')
TypeError: translate() missing 1 required positional argument: 'text'