Introduction

Private beta: The Text model is a private beta feature, and you must have permission from IBM to make calls to the model. Request access. For more information see Beta features in the Release notes.

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

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

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

Maven

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

Gradle

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

GitHub

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

Installation

npm install ibm-watson

GitHub

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

Installation

pip install --upgrade "ibm-watson>=2.4.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/...

GitHub

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

Cocoapods

pod 'IBMWatsonVisualRecognitionV3', '~> 1.4.0'

Carthage

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

Swift Package Manager

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

GitHub

Authentication

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

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

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

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

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

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

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

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

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

curl -u "apikey:{apikey}" "https://gateway.watsonplatform.net/visual-recognition/api/v3/{method}"

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

IamOptions options = new IamOptions.Builder()
    .apiKey("{apikey}")
    .build();

VisualRecognition visualRecognition = new VisualRecognition("{version}", options);

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

const VisualRecognitionV3 = require('ibm-watson/visual-recognition/v3');

const visualRecognition = new VisualRecognitionV3({
  version: '{version}',
  iam_apikey: '{apikey}'
});

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

from ibm_watson import VisualRecognitionV3

visual_recognition = VisualRecognitionV3(
    version='{version}',
    iam_apikey='{apikey}'
)

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

require "ibm_watson"

visual_recognition = IBMWatson::VisualRecognitionV3.new(
  version: "{version}",
  iam_apikey: "{apikey}"
)

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

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

visualRecognition, visualRecognitionErr := visualrecognitionv3.NewVisualRecognitionV3(&visualrecognitionv3.VisualRecognitionV3Options{
  Version: "{version}",
  IAMApiKey: "{apikey}",
})

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

let visualRecognition = VisualRecognition(version: "{version}", apiKey: "{apikey}")

Service endpoint

The Visual Recognition v3 API is hosted only in the Dallas location and has a single service endpoint.

API endpoint

https://gateway.watsonplatform.net/visual-recognition/api

The URL is different when you use IBM Cloud Dedicated

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 Visual Recognition, 2018-03-19. In some cases, differences in earlier versions are noted in the descriptions of parameters and response models.

Error handling

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

ErrorResponse

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

ErrorAuthentication

Name Description
status
string
The status of error.
statusInfo
string
Information about the error.

ErrorInfo

Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error.

Name Description
code
integer
HTTP response code.
description
string
Human-readable error description. For example, File size limit exceeded.
error_id
string
Codified error string. For example, limit_exceeded.

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

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

When the Java SDK receives an error response from the Visual Recognition service, it generates an exception from the com.ibm.watson.developer_cloud.service.exception package. All service exceptions contain the following fields.

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

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

Error

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

The Python SDK generates an exception for any unsuccessful method invocation. When the Python SDK receives an error response from the Visual Recognition service, it generates an APIException that contains the following fields.

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

When the Ruby SDK receives an error response from the Visual Recognition service, it generates a ApiException that contains the following fields.

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

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

Error

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

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

Field Description
errorDescription A message that describes the error.

Example error handling

try {
  // Invoke a Visual Recognition 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

visualRecognition.method(params,
  function (err, response) {
    // The error will be the first argument of the callback
    if (err.code == 404) {

      // Handle Not Found (404) error
    } else if (err.code == 413) {

      // Handle Request Too Large (413) error
    } else {
      console.log('Unexpected error: ', err.code);
      console.log('error:', err);
    }
  });

Example error handling

from ibm_watson import ApiException
try:
    # Invoke a Visual Recognition 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 Visual Recognition 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/visualrecognitionv3"

// Instantiate a service
visualRecognition, visualRecognitionErr := visualrecognitionv3.NewVisualRecognitionV3(&visualRecognitionv3.VisualRecognitionV3Options{})

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

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

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

Example error handling

visualRecognition.method() {
  response, error in

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

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

  print(result)
}

Data handling

Additional headers

Some Watson services accept special parameters in headers that are passed with the request. You can pass request header parameters in all requests or in a single request to the service.

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

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

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

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

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

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

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

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

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

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

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

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

Example header parameter in a request

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

Example header parameter in a request

visualRecognition.methodName({
  parameters,
  headers: {
    'Custom-Header': '{header_value}'
  }
},
  function (err, response) {
    if (err) {
      console.log('error:', err);
    } else {
      console.log(response);
    }
  }
);

Example header parameter in a request

response = visual_recognition.methodName(
    parameters,
    headers = {
        'Custom-Header': '{header_value}'
    })

Example header parameter in a request

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

Example header parameter in a request

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

Example header parameter in a request

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

Response details

The Visual Recognition service might return information to the application in response headers.

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 = visualRecognition.methodName(parameters)
  .executeWithDetails();
// Access response from methodName
ReturnType returnValue = response.getResult();
// Access information in response headers
Headers responseHeaders = response.getHeaders();

To access information in the response headers, specify the headers attribute on the third parameter (response) that is passed to the callback function.

Example request to access response headers

visualRecognition.methodName({
  parameters
},
  function (err, result, response) {
    if (err) {
      console.log('error:', err);
    } else {
      console.log(response.headers);
    }
  }
);

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

visual_recognition.set_detailed_response(True)
response = visual_recognition.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 = visual_recognition.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 result object or response headers, use the following methods.

DetailedResponse

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

Example request to access response headers

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

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

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

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

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

Example request to access response headers

visualRecognition.methodName(parameters) {
  response, error in

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

Data collection

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

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

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

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

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

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

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

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

You can set the header by adding it to the defaultHeaders property of the service object.

Example request

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

Example request

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

visualRecognition.setDefaultHeaders(headers);

Example request

const VisualRecognitionV3 = require('ibm-watson/visual-recognition/v3');

const visualRecognition = new VisualRecognitionV3({
  version: '{version}',
  iam_apikey: '{apikey}',
  headers: {
    'X-Watson-Learning-Opt-Out': 'true'
  }
});

Example request

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

Example request

visual_recognition.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")
visualrecognitionv3.Service.SetDefaultHeaders(headers)

Example request

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

Synchronous and asynchronous requests

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

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

The Ruby SDK supports both synchronous (blocking) and asynchronous (non-blocking) execution of service methods. All service methods implement the Concurrent::Async module. When you use the synchronous/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 = visualRecognition.method(parameters).execute();

Example asynchronous request

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

Example synchronous request

response = visual_recognition.method_name(parameters)

or

response = visual_recognition.await.method_name(parameters)

Example asynchronous request

response = visual_recognition.async.method_name(parameters)

Methods

Recognize text in an image (GET) (Beta)

Recognizes English language text in an image. This feature uses a built-in model, so you do not train it on custom models.

GET /v3/recognize_text
Request

Query Parameters

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

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

  • The URL of an image file (.gif, .jpg, .png, or .tif). Maximum image size is 10 MB. Redirects are followed, so you can use a shortened URL.

Response

Text recognition results for multiple images.

Status Code

  • success

  • Invalid request due to user input, such as a bad query parameter or header

  • No API key, or the key is not valid.

Example responses

Recognize text in images (Beta)

Recognizes English language text in images. This feature uses a built-in model, so you do not train it on custom models.

POST /v3/recognize_text
Request

Query Parameters

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

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

Form Parameters

  • An image file (.gif, .jpg, .png, or .tif) or .zip file with images. Maximum image size is 10 MB. Minimum width and height is 30 pixels and the maximum is 4096 pixels for either height or width. Minimum recommended pixel density is 32X32 pixels per inch. For .zip files, include no more than 10 images and limit the .zip file to 10 MB.

    You can also include an image with the url parameter.

  • The URL of an image to analyze. Must be in .gif, .jpg, .png, or .tif format. Maximum image size is 10 MB. Minimum width and height is 30 pixels and the maximum is 4096 pixels for either height or width. Minimum recommended pixel density is 32X32 pixels per inch.

    You can also include images with the images_file parameter.

Response

Text recognition results for multiple images.

Status Code

  • success

  • Invalid request due to user input, such as a bad query parameter or header

  • No API key, or the key is not valid.

Example responses