Curl Node Java

Alchemy API

API Reference

Introduction

The IBM Watson™ AlchemyVision API uses deep learning innovations to understand a picture's content and context. The methods in the AlchemyVision API can analyze an image and return information about the objects and people found within that image.

You authenticate to the AlchemyVision API by providing the API key that is given in the service credentials for the service instance that you want to use. The API uses basic authentication.

After you create an instance of the AlchemyVision service, you can view the API key by selecting Service Credentials from the left pane of the service dashboard.

API Endpoint

https://gateway-a.watsonplatform.net/calls

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>2.3.0</version>
</dependency>

Gradle

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

API explorer

To interact with this API, use the AlchemyVision service API explorer. Use the explorer to test calls to the API, generate curl calls that you can examine and use, and to view responses to those calls from the service.

Methods

Get image link from POSTed HTML

Extract main image from posted HTML

POST /html/HTMLGetImage

Request

Parameter Type Description
html string (Required) HTML document content. Must be base-64 encoded.
url string URL of document for tracking purposes. Must be uri-argument encoded.
apikey string (Required) Your API key
outputMode string Desired output format. One of json or xml (default)

Example request

curl -X POST --data-urlencode html@example.html "https://gateway-a.watsonplatform.net/calls/html/HTMLGetImage?apikey={apikey}&outputMode=json"

        

Note: the --data-urlencode option automatically converts HTML content from the file specified as HTML-file into the appropriate format and supplies the content for the html parameter.

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

var alchemy_vision = watson.alchemy_vision({
  api_key: '{apikey}'
});

var params = {
  html: fs.readFileSync("example.html")
};

alchemy_vision.getImageLinks(params, function (err, keywords) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(keywords, null, 2));
});
AlchemyVision service = new AlchemyVision();
service.setApiKey("{apikey}");

StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("../example.html")));
String line;

try {
  while ((line = br.readLine()) != null) {
    sb.append(line);
  }
} catch (final IOException e) {
  e.printStackTrace();
} finally {
  if (br != null) {
    try {
      br.close();
    } catch (final IOException e) {
      e.printStackTrace();
    }
  }
}

ImageLink image = service.getImageLink(sb.toString());
System.out.println(image);

Response

Name Description
status text string, either OK or ERROR. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
image text string containing URL of primary image

Example response

{
  "status": "OK",
  "usage": "...",
  "url": "http://www.example.com",
  "image": "http://example.com/vehicle.jpg"
}

Get image link from URL

Extract main image from posted HTML

GET /url/URLGetImage

Request

Parameter Type Description
url string (Required) HTTP URL, URI-argument encoded
apikey string (Required) Your API key
outputMode string Desired output format. One of json or xml (default)

Example request

curl "https://gateway-a.watsonplatform.net/calls/url/URLGetImage?url=http://www.example.com&apikey={api-key}&outputMode=json"
var watson = require('watson-developer-cloud');
var fs = require('fs');

var alchemy_vision = watson.alchemy_vision({
  api_key: '{apikey}',
});

var params = {
  url: 'http://www.example.com'
};

alchemy_vision.getImageLinks(params, function (err, keywords) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(keywords, null, 2));
});
AlchemyVision service = new AlchemyVision();
service.setApiKey("{apikey}");

String url = "http://www.example.com";

ImageLink mylink = service.getImageLink(url);

System.out.println(mylink);

Response

Name Description
status text string, either OK or ERROR. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
image text string containing URL of primary image

Example response

{
  "status": "OK",
  "usage": "...",
  "url": "http://www.example.com",
  "image": "http://www.example.com/vehicle.jpg"
}

Tag faces in POSTed image

Performs face recognition on a POSTed image

POST /image/ImageGetRankedImageFaceTags

Request

Parameter Type Description
imagePostMode string (Required) Set to raw to pass an image file using POST
img_file string (Required) Image file to analyze, passed as binary data. Accepted formats are .jpg, .png, or .gif.
apikey string (Required) Your API key
outputMode string Desired output format. One of json or xml (default)
knowledgeGraph boolean Whether or not to provide extra metadata for detected celebrities
Content-Type string (Required) Must be application/x-www-form-urlencoded

Example request

curl -X POST --data-binary @parkbench.jpg "https://gateway-a.watsonplatform.net/calls/image/ImageGetRankedImageFaceTags?apikey={apikey}&outputMode=json&imagePostMode=raw"

        

Note: the --data-binary option automatically sets the Content-type header, converts the file specified as {image-file} into the appropriate format, and supplies that as the content for the img_file parameter.

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

var alchemy_vision = watson.alchemy_vision({
  api_key: '{apikey}',
});

var params = {
  image: fs.createReadStream('parkbench.jpg')
};

alchemy_vision.recognizeFaces(params, function (err, keywords) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(keywords, null, 2));
});
AlchemyVision service = new AlchemyVision();
service.setApiKey("{apikey}");

File image = new File("parkbench.jpg");
ImageFaces faces = service.recognizeFaces(image, true);

System.out.println(faces);

Response

Name Description
status text string, either OK or ERROR. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
totalTransactions number of internal API transactions that were required to satisfy the request
imageFaces container for information about a face that was detected
age estimated age range (ageRange) of the individual whose face was detected, along with a score value that indicates the likelihood that the age range is correct (a floating point value between 0 and 1)
gender suggested gender of the individual whose face was detected, along with a score value that indicates the likelihood that the age range is correct (a floating point value between 0 and 1)
positionX coordinate of the left-most pixel for a detected face in the image
positionY coordinate of the top-most pixekl for a detected face
width width of a detected face, in pixels
height height of a detected face, in pixels

Example response

{
  "status": "OK",
  "usage": "...",
  "totalTransactions": "4",
  "imageFaces": [
    {
      "age": {
      "ageRange": "55-64",
      "score": "0.441192"
      },
      "gender": {
        "gender": "MALE",
        "score": "0.956893"
      },
      "height": "69",
      "positionX": "187",
      "positionY": "72",
      "width": "69"
    }
  ]
}

Identify text in POSTed image

Identifies text in a POSTed image

This is a beta function of the AlchemyVision service that supports only English language text identification.

POST /image/ImageGetRankedImageSceneText

Request

Parameter Type Description
imagePostMode string (Required) Set to raw to pass an image file using POST
img_file string (Required) Image file to analyze, passed as binary data. Accepted formats are .jpg, .png, or .gif.
apikey string (Required) Your API key
outputMode string Desired output format. One of json or raw (default)
Content-Type string (Required) Must be application/x-www-form-urlencoded

Example request

curl -X POST --data-binary @road.jpg "https://gateway-a.watsonplatform.net/calls/image/ImageGetRankedImageSceneText?apikey={apikey}&outputMode=json&imagePostMode=raw"

        

Note: the --data-binary option automatically sets the Content-type header, converts the file specified as {image-file} into the appropriate format, and supplies that as the content for the img_file parameter.

Node.js example coming soon.
Java example coming soon.

Response

Name Description
status text string, either OK or ERROR. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
totalTransactions number of internal API transactions that were required to satisfy the request
sceneText text string aggregate of all lines of text detected in the image
sceneTextLines container for information about lines of text detected in the image
confidence Indicates the likelihood that the identified text is correct (a floating point value between 0 and 1)
region container for imformation about the location of text within the image
x coordinate of the left-most pixel for text detected in the image
y coordinate of the top-most pixel for text detected in the image
width width of of the line of text or word, in pixels
height height of the line of text or word, in pixels
text text string of the line of text or word detected in the image
words container for information about a single word in a line of text detected in the image

Example response

{
  "status": "OK",
  "usage": "...",
  "totalTransactions": "4",
  "sceneText": "no stopping\nanytime",
  "sceneTextLines": [
    {
      "confidence": 0.986614,
      "region": {
        "height": 40,
        "width": 189,
        "x": 25,
        "y": 24
      },
      "text": "no stopping",
      "words": [
        {
          "confidence": 0.983386,
          "region": {
            "height": 32,
            "width": 41,
            "x": 25,
            "y": 32
          },
          "text": "no"
        },
        {
          "confidence": 0.989841,
          "region": {
            "height": 40,
            "width": 140,
            "x": 74,
            "y": 24
          },
          "text": "stopping"
        }
      ]
    },
    {
      "confidence": 0.990438,
      "region": {
        "height": 36,
        "width": 120,
        "x": 56,
        "y": 72
      },
      "text": "anytime",
      "words": [
        {
          "confidence": 0.990438,
          "region": {
            "height": 36,
            "width": 120,
            "x": 56,
            "y": 72
          },
          "text": "anytime"
        }
      ]
    }
  ]
}

Tag POSTed image

Identify keywords that are associated with the POSTed image

POST /image/ImageGetRankedImageKeywords

Request

Parameter Type Description
imagePostMode string (Required) Set to raw to pass an image file using POST
img_file string (Required) Image file to analyze, passed as binary data. Accepted formats are .jpg, .png, or .gif.
apiKey string (Required) Your API key
outputMode string Desired output format. One of json, rdf, or xml (default)
knowledgeGraph boolean Whether or not to provide extra metadata for detected celebrities
Content-Type string (Required) Must be application/x-www-form-urlencoded

Example request

curl -X POST --data-binary @scene.jpg "https://gateway-a.watsonplatform.net/calls/image/ImageGetRankedImageKeywords?apikey={apikey}&outputMode=json&imagePostMode=raw"

        

Note: the --data-binary option automatically sets the Content-type header, converts the file specified as {image-file} into the appropriate format, and supplies that as the content for the img_file parameter.

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

var alchemy_vision = watson.alchemy_vision({
  api_key: '{apikey}'
});

var params = {
  image: fs.createReadStream('scene.jpg')
};

alchemy_vision.getImageKeywords(params, function (err, keywords) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(keywords, null, 2));
});
AlchemyVision service = new AlchemyVision();
service.setApiKey("{apikey}");

File image = new File("scene.jpg");
ImageKeywords keywords = service.getImageKeywords(image, true, true);

System.out.println(keywords);

Response

Name Description
status text string, either OK or ERROR. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
totalTransactions number of internal API transactions that were required to satisfy the request
imageKeywords container for keywords about the tagged image
text text string that summarizes the content of the image
score indicates the likelihood that the keyword is correct (a floating point value between 0 and 1)

Example response

{
  "status": "OK",
  "usage": "...",
  "url": "",
  "totalTransactions": "4",
  "imageKeywords": [
    {
      "text": "person",
      "score": "0.802184"
    }
  ]
}

Tag faces from URL

Tag faces in an image specified by URL or in the primary image in a web page specified by URL

GET /url/URLGetRankedImageFaceTags

Request

Parameter Type Description
url string (Required) HTTP URL, URI-argument encoded
apikey string (Required) Your API key
outputMode string Desired output format. One of json or xml (default)
knowledgeGraph boolean Whether or not to provide extra metadata for detected celebrities

Example request

curl "https://gateway-a.watsonplatform.net/calls/url/URLGetRankedImageFaceTags?url=http://www.example.com&outputMode=json&apikey={apikey}"
var watson = require('watson-developer-cloud');
var fs = require('fs');

var alchemy_vision = watson.alchemy_vision({
  api_key: '{apikey}',
});

var params = {
  url:     'http://www.example.com'
};

alchemy_vision.recognizeFaces(params, function (err, keywords) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(keywords, null, 2));
});
AlchemyVision service = new AlchemyVision();
service.setApiKey("{apikey}");

ImageFaces faces = service.recognizeFaces(HttpUrl.parse("http://www.example.com").url(), false);
System.out.println(faces);

Response

Name Description
status text string, either OK or ERROR See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
totalTransactions number of internal API transactions that were required to satisfy the request
imageFaces container for information about a face that was detected
age estimated age range (ageRange) of the individual whose face was detected, along with a score value that indicates the likelihood that the age range is correct (a floating point value between 0 and 1)
gender suggested gender of the individual whose face was detected, along with a score value that indicates the likelihood that the age range is correct (a floating point value between 0 and 1)
positionX coordinate of the left-most pixel for a detected face in the image
positionY coordinate of the top-most pixel for a detected face
width width of a detected face, in pixels
height height of a detected face, in pixels

Example response

{
  "status": "OK",
  "usage": "...",
  "url": "http://example.com/unnamed.jpg",
  "totalTransactions": "4",
  "imageFaces": [
    {
      "age": {
      "ageRange": "55-64",
      "score": "0.441192"
      },
      "gender": {
        "gender": "MALE",
        "score": "0.956893"
      },
      "height": "69",
      "positionX": "187",
      "positionY": "72",
      "width": "69"
    }
  ]
}

Identify text from URL

Identify text in an image specified by URL or in the primary image in a web page specified by URL

This is a beta function of the AlchemyVision service that supports only English language text identification.

GET /url/URLGetRankedImageSceneText

Request

Parameter Type Description
url string (Required) HTTP URL, URI-argument encoded
apikey string (Required) Your API key
outputMode string Desired output format. One of json or raw (default)

Example request

curl -X GET "https://gateway-a.watsonplatform.net/calls/url/URLGetRankedImageSceneText?apikey={apikey}&url=http://www.example.com/parking&outputMode=json
Node.js example coming soon.
Java example coming soon.

Response

Name Description
status text string, either OK or ERROR. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
totalTransactions number of internal API transactions that were required to satisfy the request
sceneText text string aggregate of all lines of text detected in the image
sceneTextLines container for information about lines of text detected in the image
confidence Indicates the likelihood that the identified text is correct (a floating point value between 0 and 1)
region container for imformation about the location of text within the image
x coordinate of the left-most pixel for text detected in the image
y coordinate of the top-most pixel for text detected in the image
width width of of the line of text or word, in pixels
height height of the line of text or word, in pixels
text text string of the line of text or word detected in the image
words container for information about a single word in a line of text detected in the image

Example response

{
  "status": "OK",
  "usage": "...",
  "url": "http://www.example.com/parking",
  "totalTransactions": "4",
  "sceneText": "no stopping\nanytime",
  "sceneTextLines": [
    {
      "confidence": 0.986614,
      "region": {
        "height": 40,
        "width": 189,
        "x": 25,
        "y": 24
      },
      "text": "no stopping",
      "words": [
        {
          "confidence": 0.983386,
          "region": {
            "height": 32,
            "width": 41,
            "x": 25,
            "y": 32
          },
          "text": "no"
        },
        {
          "confidence": 0.989841,
          "region": {
            "height": 40,
            "width": 140,
            "x": 74,
            "y": 24
          },
          "text": "stopping"
        }
      ]
    },
    {
      "confidence": 0.990438,
      "region": {
        "height": 36,
        "width": 120,
        "x": 56,
        "y": 72
      },
      "text": "anytime",
      "words": [
        {
          "confidence": 0.990438,
          "region": {
            "height": 36,
            "width": 120,
            "x": 56,
            "y": 72
          },
          "text": "anytime"
        }
      ]
    }
  ]
}

Tag image from URL

Tags an image specified by URL or the primary image in a web page specified by URL

GET /url/URLGetRankedImageKeywords

Request

Parameter Type Description
url string (Required) HTTP URL, URI-argument encoded
apikey string (Required) Your API key
outputMode string Desired output format. One of json, rdf, or xml (default)
forceShowAllparameter double Include lower confidence tags. 0 (default) or 1
knowledgeGraph boolean Whether or not to provide extra metadata for detected celebrities. 0 (default) or 1

Example request

curl "https://gateway-a.watsonplatform.net/calls/url/URLGetRankedImagekeywords?url=http://www.example.com&outputMode=json&apikey={apikey}"
var watson = require('watson-developer-cloud');
var fs = require('fs');

var alchemy_vision = watson.alchemy_vision({
  api_key: '{apikey}',
});

var params = {
  url:     'http://www.example.com'
};

alchemy_vision.getImageKeywords(params, function (err, keywords) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(keywords, null, 2));
});
AlchemyVision service = new AlchemyVision();
service.setApiKey("{apikey}");

ImageKeywords keywords =
  service.getImageKeywords(HttpUrl.parse("http://www.example.com").url(), true, true);
System.out.println(keywords);

Response

Name Description
status text string, either OK or ERROR See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.
usage text string explaining terms of use
url text string containing URL specified as parameter
totalTransactions number of internal API transactions that were required to satisfy the request
imageKeywords container for keywords about the tagged image
text text string that summarizes the content of the image
score indicates the likelihood that the keyword is correct (a floating point value between 0 and 1)

Example response

{
  "status": "OK",
  "usage": "...",
  "url": "http://example.com/unnamed.jpg",
  "totalTransactions": "5",
  "imageKeywords": [
    {
      "text": "person",
      "score": "0.802184"
    }
  ]
}

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 from accessing your data for general service improvements, set the X-Watson-Learning-Opt-Out header parameter to true for all requests. (Any value other than false or 0 disables request logging for that call.) You must set the header on each request that you do not want IBM to access for general service improvements.

Response handling

The AlchemyVision service uses standard HTTP response codes to indicate internal API error conditions, and uses the traditional HTTP response code 200 in a custom way. For AlchemyVision method calls, the HTTP response code 200 means that the AlchemyVision API could be successfully communicated with, not that the call to the API completed successfully. The Error Information table summarizes standard HTTP response codes that you may see for invalid calls to the API.

In most cases, calls to the AlchemyVision REST API that can successfully communicate with the API but trigger an internal error that can be caught result in a HTTP response code of 200. The Node.js and Java SDKs catch and report the actual error codes correctly, but direct calls to the REST API (such as those made from the curl command) indicate error status by returning ERROR information in their output. See Status Codes for information about status codes that can be returned to clarify the reason for an ERROR status.

Error information

Status Description
400 - Bad Request Missing a required parameter, or invalid parameter value.
404 - Not Found The requested item or parameter doesn't exist.

Example error

{
  "status": "ERROR",
  "statusInfo": "daily-transaction-limit-exceeded"
}
error: { error: 'daily-transaction-limit-exceeded', code: 400 }
SEVERE: {"error":"daily-transaction-limit-exceeded","code":429}