Introduction

IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of results.

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

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

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

This documentation describes Ruby SDK major version 1. 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 4. For more information about how to update your code from the previous version, see the migration guide.

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

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

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

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

This API reference applies to Premium Discovery instances created before 16 July 2020 and to all Lite and Advanced plans. For more information about features in Discovery Premium instances created after that date, see the v2 API.

Beginning with version 4.0.0, the Node SDK returns a Promise for all methods when a callback isn't specified.

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

The IBM Watson Unity SDK has the following requirements.

  • The SDK requires Unity version 2018.2 or later to support 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>8.6.2</version>
</dependency>

Gradle

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

GitHub

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

Installation

npm install ibm-watson@^5.7.1

GitHub

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

Installation

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

GitHub

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

Installation

gem install ibm_watson

GitHub

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

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

GitHub

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

Cocoapods

pod 'IBMWatsonDiscoveryV1', '~> 3.6.0'

Carthage

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

Swift Package Manager

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

GitHub

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

Package Manager

Install-Package IBM.Watson.Discovery.v1 -Version 4.6.0

.NET CLI

dotnet add package IBM.Watson.Discovery.v1 --version 4.6.0

PackageReference

<PackageReference Include="IBM.Watson.Discovery.v1" Version="4.6.0" />

GitHub

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

GitHub

Authentication

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

To find out which authentication to use, view the service credentials by clicking the service instance in the Resource list.

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

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

      curl -u "apikey:f5sAznhrKQyvBFFaZbtF60m5tzLbqWhyALQawBg5TjRI"
    
  • In other instances, you authenticate with the username and password for the service instance. The "username" and "password" in the service credentials are different from your IBM Cloud account IBMid and password. For more information, see Authenticating with Cloud Foundry service credentials.

The SDK provides initialization methods for each form of authentication.

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

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

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

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

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

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

Basic authentication. Replace {username}, {password}, and {url} with your service credentials.

curl -u "{username}:{password}" -X {request_method} "{url}/{method}"

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

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

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

BasicAuthenticator authenticator = new BasicAuthenticator("{username}", "{password}");
Discovery discovery = new Discovery("{version}",  authenticator);
discovery.setServiceUrl("{url}");

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

const DiscoveryV1 = require('ibm-watson/discovery/v1');
const { IamAuthenticator } = require('ibm-watson/auth');

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

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

const DiscoveryV1 = require('ibm-watson/discovery/v1');
const { BasicAuthenticator } = require('ibm-watson/auth');

const discovery = new DiscoveryV1({
  version: '{version}',
  authenticator: new BasicAuthenticator({
    username: '{username}',
    password: '{password}',
  }),
  serviceUrl: '{url}',
});

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

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
discovery = DiscoveryV1(
    version='{version}',
    authenticator=authenticator
)

discovery.set_service_url('{url}')

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

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator

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

discovery = DiscoveryV1(
    version='{version}',
    authenticator=authenticator
)

discovery.set_service_url('{url}')

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

require "ibm_watson/authenticators"
require "ibm_watson/discovery_v1"
include IBMWatson

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

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

require "ibm_watson/discovery_v1"
include IBMWatson

authenticator = Authenticators::BasicAuthenticator.new(
  username: "{username}",
  password: "{password}"
)
discovery = DiscoveryV1.new(
  version: "{version}",
  authenticator: authenticator
)
discovery.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/discoveryv1"
)

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

  options := &discoveryv1.DiscoveryV1Options{
    Version: "{version}",
    Authenticator: authenticator,
  }

  discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)

  if discoveryErr != nil {
    panic(discoveryErr)
  }

  discovery.SetServiceURL("{url}")
}

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

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

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

  options := &discoveryv1.DiscoveryV1Options{
    Version: "{version}",
    Authenticator: authenticator,
  }

  discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)

  if discoveryErr != nil {
  panic(discoveryErr)
  }

  discovery.SetServiceURL("{url}")
}

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

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

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

let authenticator = WatsonBasicAuthenticator(username: "{username}", password: "{password}")
let discovery = Discovery(version: "{version}", authenticator: authenticator)
discovery.serviceURL = "{url}"

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

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

DiscoveryService discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

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

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

DiscoveryService discovery = new DiscoveryService("{version}", authenticator);
discovery.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 discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

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

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

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

var discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

Access between services

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

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

For more information about IAM, see IAM access.

To grant this access, use an endpoint URL that includes the service instance ID (for example, https://api.us-south.discovery.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

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 Discovery instance that is hosted in Washington DC:

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

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

  • Dallas: https://api.us-south.discovery.watson.cloud.ibm.com
  • Washington DC: https://api.us-east.discovery.watson.cloud.ibm.com
  • Frankfurt: https://api.eu-de.discovery.watson.cloud.ibm.com
  • Sydney: https://api.au-syd.discovery.watson.cloud.ibm.com
  • Tokyo: https://api.jp-tok.discovery.watson.cloud.ibm.com
  • London: https://api.eu-gb.discovery.watson.cloud.ibm.com
  • Seoul: https://api.kr-seo.discovery.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.discovery.watson.cloud.ibm.com/instances/{instance_id}"

Your service instance might not use this URL

Default URL

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

Example for the Washington DC location

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

Default URL

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

Example for the Washington DC location

const DiscoveryV1 = require('ibm-watson/discovery/v1');
const { IamAuthenticator } = require('ibm-watson/auth');

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

Default URL

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

Example for the Washington DC location

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
discovery = DiscoveryV1(
    version='{version}',
    authenticator=authenticator
)

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

Default URL

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

Example for the Washington DC location

require "ibm_watson/authenticators"
require "ibm_watson/discovery_v1"
include IBMWatson

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

Default URL

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

Example for the Washington DC location

discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)

if discoveryErr != nil {
  panic(discoveryErr)
}

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

Default URL

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

Example for the Washington DC location

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

Default URL

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

Example for the Washington DC location

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

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

Default URL

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

Example for the Washington DC location

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

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

var discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("https://api.us-east.discovery.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}");
Discovery discovery = new Discovery("{version}", authenticator);
discovery.setServiceUrl("{url}");

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

Example to disable SSL verification

const DiscoveryV1 = require('ibm-watson/discovery/v1');
const { IamAuthenticator } = require('ibm-watson/auth');

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

Example to disable SSL verification

from ibm_watson import DiscoveryV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')
discovery = DiscoveryV1(
    version='{version}',
    authenticator=authenticator
)

discovery.set_service_url('{url}')

discovery.set_disable_ssl_verification(True)

Example to disable SSL verification

require "ibm_watson/authenticators"
require "ibm_watson/discovery_v1"
include IBMWatson

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

discovery.configure_http_client(disable_ssl_verification: true)

Example to disable SSL verification

discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)

if discoveryErr != nil {
  panic(discoveryErr)
}

discovery.SetServiceURL("{url}")

discovery.DisableSSLVerification()

Example to disable SSL verification

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

discovery.disableSSLVerification()

Example to disable SSL verification

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

DiscoveryService discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

discovery.DisableSslVerification(true);

Example to disable SSL verification

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

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

var discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

discovery.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 Discovery, 2019-04-30. In some cases, differences in earlier versions are noted in the descriptions of parameters and response models.

Error handling

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

ErrorResponse

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

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

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

When the Java SDK receives an error response from the Discovery 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 Discovery 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 Discovery 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 Discovery 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 Discovery 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 Discovery 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 Discovery 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

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

Example error handling

from ibm_watson import ApiException
try:
    # Invoke a Discovery 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 Discovery 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/discoveryv1"

// Instantiate a service
discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)

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

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

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

Example error handling

discovery.method() {
  response, error in

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

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

  print(result)
}

Example error handling

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

Example error handling

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

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

Data handling

Additional headers

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example header parameter in a request

curl -u "apikey:{apikey}" -X {request_method} --header "Request-Header: {header_value}" "{url}/{method}"

Example header parameter in a request

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

Example header parameter in a request

const parameters = {
  {parameters}
};

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

Example header parameter in a request

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

Example header parameter in a request

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

Example header parameter in a request

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

Example header parameter in a request

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

DiscoveryService discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

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

Example header parameter in a request

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

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

var discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

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

Response details

The Discovery 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 -u "apikey:{apikey}" -X {request_method} --include "{url}/{method}"

To access information in the response headers, use one of the request methods that returns details with the response: executeWithDetails(), enqueueWithDetails(), or rxWithDetails(). These methods return a Response<T> object, where T is the expected response model. Use the getResult() method to access the response object for the method, and use the getHeaders() method to access information in response headers.

Example request to access response headers

Response<ReturnType> response = discovery.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

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

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

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

DetailedResponse

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

Example request to access response headers

import "github.com/IBM/go-sdk-core/core"
result, response, _ := discoveryv1.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

discovery.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 = discovery.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()
{
    discovery.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 labels

You can remove customer data if you associate the customer and the data when you send the information to a service. First, you label the data with a customer ID, and then you can delete the data by the ID.

  • Use the X-Watson-Metadata header to associate a customer ID with the data. By adding a customer ID to a request, you indicate that it contains data that belongs to that customer.

    Specify a random or generic string for the customer ID. Do not include personal data, such as an email address. Pass the string customer_id={id} as the argument of the header.

  • Use the Delete labeled data method to remove data that is associated with a customer ID.

Labeling data is used only by methods that accept customer data. For more information about Discovery and labeling data, see Information security.

For more information about how to pass headers, see Additional headers.

Data collection

By default, Discovery 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");

discovery.setDefaultHeaders(headers);

Example request

const DiscoveryV1 = require('ibm-watson/discovery/v1');
const { IamAuthenticator } = require('ibm-watson/auth');

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

Example request

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

Example request

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

Example request

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

Example request

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

DiscoveryService discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

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

Example request

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

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

var discovery = new DiscoveryService("{version}", authenticator);
discovery.SetServiceUrl("{url}");

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

Example asynchronous request

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

Example synchronous request

response = discovery.method_name(parameters)

or

response = discovery.await.method_name(parameters)

Example asynchronous request

response = discovery.async.method_name(parameters)

Methods

Create an environment

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

Creates a new environment for private data. An environment must be created before collections can be created.

Note: You can create only one environment for private data per service instance. An attempt to create another environment results in an error.

POST /v1/environments
(discovery *DiscoveryV1) CreateEnvironment(createEnvironmentOptions *CreateEnvironmentOptions) (result *Environment, response *core.DetailedResponse, err error)
ServiceCall<Environment> createEnvironment(CreateEnvironmentOptions createEnvironmentOptions)
createEnvironment(params, [callback()])
create_environment(self, name, description=None, size=None, **kwargs)
create_environment(name:, description: nil, size: nil)
func createEnvironment(
    name: String,
    description: String? = nil,
    size: String? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Environment>?, WatsonError?) -> Void)
CreateEnvironment(string name, string description = null, string size = null)
CreateEnvironment(Callback<ModelEnvironment> callback, string name, string description = null, string size = null)

Request

Instantiate the CreateEnvironmentOptions struct and set the fields to provide parameter values for the CreateEnvironment method.

Use the CreateEnvironmentOptions.Builder to create a CreateEnvironmentOptions object that contains the parameter values for the createEnvironment 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 2019-04-30.

An object that defines an environment name and optional description. The fields in this object are not approved for personal information and cannot be deleted based on customer ID.

Example:

The CreateEnvironment options.

The createEnvironment options.

parameters

  • Name that identifies the environment.

    Constraints: 0 ≤ length ≤ 255

  • Description of the environment.

    Default:

  • Size of the environment. In the Lite plan the default and only accepted value is LT, in all other plans the default is S.

    Allowable values: [LT,XS,S,MS,M,ML,L,XL,XXL,XXXL]

parameters

  • Name that identifies the environment.

    Constraints: 0 ≤ length ≤ 255

  • Description of the environment.

    Default:

  • Size of the environment. In the Lite plan the default and only accepted value is LT, in all other plans the default is S.

    Allowable values: [LT,XS,S,MS,M,ML,L,XL,XXL,XXXL]

parameters

  • Name that identifies the environment.

    Constraints: 0 ≤ length ≤ 255

  • Description of the environment.

    Default:

  • Size of the environment. In the Lite plan the default and only accepted value is LT, in all other plans the default is S.

    Allowable values: [LT,XS,S,MS,M,ML,L,XL,XXL,XXXL]

parameters

  • Name that identifies the environment.

    Constraints: 0 ≤ length ≤ 255

  • Description of the environment.

    Default:

  • Size of the environment. In the Lite plan the default and only accepted value is LT, in all other plans the default is S.

    Allowable values: [LT,XS,S,MS,M,ML,L,XL,XXL,XXXL]

parameters

  • Name that identifies the environment.

    Constraints: 0 ≤ length ≤ 255

  • Description of the environment.

    Default:

  • Size of the environment. In the Lite plan the default and only accepted value is LT, in all other plans the default is S.

    Allowable values: [LT,XS,S,MS,M,ML,L,XL,XXL,XXXL]

parameters

  • Name that identifies the environment.

    Constraints: 0 ≤ length ≤ 255

  • Description of the environment.

    Default:

  • Size of the environment. In the Lite plan the default and only accepted value is LT, in all other plans the default is S.

    Allowable values: [LT,XS,S,MS,M,ML,L,XL,XXL,XXXL]

  • curl -X POST -u "apikey":"{apikey}" -H "Content-Type: application/json" -d '{
      "name": "my_environment",
      "description": "My environment"
    }' "{url}/v1/environments?version=2019-04-30"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    DiscoveryService discovery = new DiscoveryService("2019-04-30", authenticator);
    discovery.SetServiceUrl("{url}");
    
    var result = discovery.CreateEnvironment(
        name: "my_environment",
        description: "My environment"
        );
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/discoveryv1"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &discoveryv1.DiscoveryV1Options{
        Version: "2019-04-30",
        Authenticator: authenticator,
      }
    
      discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)
    
      if discoveryErr != nil {
        panic(discoveryErr)
      }
    
      discovery.SetServiceURL("{url}")
    
      result, response, responseErr := discovery.CreateEnvironment(
        &discoveryv1.CreateEnvironmentOptions{
          Name: core.StringPtr("my_environment"),
          Description: core.StringPtr("My environment"),
        },
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    Discovery discovery = new Discovery("2019-04-30", authenticator);
    discovery.setServiceUrl("{url}");
    
    String environmentName = "my_environment";
    String environmentDesc = "My environment";
    
    CreateEnvironmentOptions.Builder createOptionsBuilder = new CreateEnvironmentOptions.Builder(environmentName);
    createOptionsBuilder.description(environmentDesc);
    Environment createResponse = discovery.createEnvironment(createOptionsBuilder.build()).execute().getResult();
  • const DiscoveryV1 = require('ibm-watson/discovery/v1');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const discovery = new DiscoveryV1({
      version: '2019-04-30',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    const createEnvironmentParams = {
      name: 'my_environment',
      description: 'My environment',
      size: 'LT',
    };
    
    discovery.createEnvironment(createEnvironmentParams)
      .then(environment => {
        console.log(JSON.stringify(environment, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import DiscoveryV1
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    discovery = DiscoveryV1(
        version='2019-04-30',
        authenticator=authenticator
    )
    
    discovery.set_service_url('{url}')
    
    response = discovery.create_environment(
        name="my_environment",
        description="My environment"
    ).get_result()
    
    print(json.dumps(response, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/discovery_v1"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    discovery = DiscoveryV1.new(
      version: "2019-04-30",
      authenticator: authenticator
    )
    discovery.service_url = "{url}"
    
    response = discovery.create_environment(
      name: "my_environment",
      description: "My environment"
    )
    
    puts JSON.pretty_generate(response.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let discovery = Discovery(version: "2019-04-30", authenticator: authenticator)
    discovery.serviceURL = "{url}"
    
    discovery.createEnvironment(name: "my_environment", description: "My environment") {
      response, error in
    
      guard let environment = response?.result else {
        print(error?.localizedDescription ?? "unexpected error")
        return
      }
    
      environmentID = environment.environmentID
      print(environment)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var discovery = new DiscoveryService("2019-04-30", authenticator);
    discovery.SetServiceUrl("{url}");
    
    ModelEnvironment createEnvironmentResponse = null;
    discovery.CreateEnvironment(
        callback: (DetailedResponse<ModelEnvironment> response, IBMError error) =>
        {
            Log.Debug("DiscoveryServiceV1", "CreateEnvironment result: {0}", response.Response);
            createEnvironmentResponse = response.Result;
            createdEnvironmentId = createEnvironmentResponse.EnvironmentId;
        },
        name: "my_environment",
        description: "My environment"
    );
    
    while (createEnvironmentResponse == null)
        yield return null;

Response

Details about an environment.

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Status Code

  • Environment successfully added.

  • Bad request.

Example responses
  • {
      "environment_id": "f822208e-e4c2-45f8-a0d6-c2be950fbcc8",
      "name": "test_environment",
      "description": "Test environment",
      "created": "2016-06-16T10:56:54.957Z",
      "updated": "2017-05-16T13:56:54.957Z",
      "status": "active",
      "read_only": false,
      "size": "M",
      "index_capacity": {
        "documents": {
          "indexed": 0,
          "maximum_allowed": 1000000
        },
        "disk_usage": {
          "used_bytes": 0,
          "maximum_allowed_bytes": 85899345920
        },
        "collections": {
          "available": 1,
          "maximum_allowed": 4
        }
      },
      "search_status": [
        {
          "scope": "environment",
          "status": "NO_DATA",
          "status_description": "The system is employing the default strategy for document search natural_language_query. Enable query and event logging so we can initiate relevancy training to improve search accuracy."
        }
      ]
    }
  • {
      "environment_id": "f822208e-e4c2-45f8-a0d6-c2be950fbcc8",
      "name": "test_environment",
      "description": "Test environment",
      "created": "2016-06-16T10:56:54.957Z",
      "updated": "2017-05-16T13:56:54.957Z",
      "status": "active",
      "read_only": false,
      "size": "M",
      "index_capacity": {
        "documents": {
          "indexed": 0,
          "maximum_allowed": 1000000
        },
        "disk_usage": {
          "used_bytes": 0,
          "maximum_allowed_bytes": 85899345920
        },
        "collections": {
          "available": 1,
          "maximum_allowed": 4
        }
      },
      "search_status": [
        {
          "scope": "environment",
          "status": "NO_DATA",
          "status_description": "The system is employing the default strategy for document search natural_language_query. Enable query and event logging so we can initiate relevancy training to improve search accuracy."
        }
      ]
    }

List environments

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

List existing environments for the service instance.

GET /v1/environments
(discovery *DiscoveryV1) ListEnvironments(listEnvironmentsOptions *ListEnvironmentsOptions) (result *ListEnvironmentsResponse, response *core.DetailedResponse, err error)
ServiceCall<ListEnvironmentsResponse> listEnvironments(ListEnvironmentsOptions listEnvironmentsOptions)
listEnvironments(params, [callback()])
list_environments(self, name=None, **kwargs)
list_environments(name: nil)
func listEnvironments(
    name: String? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<ListEnvironmentsResponse>?, WatsonError?) -> Void)
ListEnvironments(string name = null)
ListEnvironments(Callback<ListEnvironmentsResponse> callback, string name = null)

Request

Instantiate the ListEnvironmentsOptions struct and set the fields to provide parameter values for the ListEnvironments method.

Use the ListEnvironmentsOptions.Builder to create a ListEnvironmentsOptions object that contains the parameter values for the listEnvironments 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 2019-04-30.

  • Show only the environment with the given name.

The ListEnvironments options.

The listEnvironments options.

parameters

  • Show only the environment with the given name.

parameters

  • Show only the environment with the given name.

parameters

  • Show only the environment with the given name.

parameters

  • Show only the environment with the given name.

parameters

  • Show only the environment with the given name.

parameters

  • Show only the environment with the given name.

  • curl -u "apikey":"{apikey}" "{url}/v1/environments?version=2019-04-30"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    DiscoveryService discovery = new DiscoveryService("2019-04-30", authenticator);
    discovery.SetServiceUrl("{url}");
    
    var result = discovery.ListEnvironments();
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/discoveryv1"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &discoveryv1.DiscoveryV1Options{
        Version: "2019-04-30",
        Authenticator: authenticator,
      }
    
      discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)
    
      if discoveryErr != nil {
        panic(discoveryErr)
      }
    
      discovery.SetServiceURL("{url}")
    
      result, response, responseErr := discovery.ListEnvironments(
        &discoveryv1.ListEnvironmentsOptions{},
      )
      if responseErr != nil {
        panic(responseErr)
      }
      var newsEnvironmentId *string
      for _, environment := range result.Environments {
        if *environment.Name == "Watson Discovery News Environment" {
          newsEnvironmentId = environment.EnvironmentID
       }
      }
    
      if newsEnvironmentId != nil {
        response, responseErr = discovery.ListCollections(
          &discoveryv1.ListCollectionsOptions{
            EnvironmentID: newsEnvironmentId,
          },
        )
      }
      if responseErr != nil {
        panic(responseErr)
      }
      fmt.Println(response)
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    Discovery discovery = new Discovery("2019-04-30", authenticator);
    discovery.setServiceUrl("{url}");
    
    ListEnvironmentsOptions options = new ListEnvironmentsOptions.Builder().build();
    ListEnvironmentsResponse listResponse = discovery.listEnvironments(options).execute().getResult();
  • const DiscoveryV1 = require('ibm-watson/discovery/v1');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const discovery = new DiscoveryV1({
      version: '2019-04-30',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    discovery.listEnvironments()
      .then(listEnvironmentsResponse => {
        console.log(JSON.stringify(listEnvironmentsResponse, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import DiscoveryV1
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    discovery = DiscoveryV1(
        version='2019-04-30',
        authenticator=authenticator
    )
    
    discovery.set_service_url('{url}')
    
    environments = discovery.list_environments().get_result()
    print(json.dumps(environments, indent=2))
    
    system_environments = [x for x in environments['environments'] if x['name'] == 'Watson System Environment']
    system_environment_id = system_environments[0]['environment_id']
    
    collections = discovery.list_collections(system_environment_id).get_result()
    system_collections = [x for x in collections['collections']]
    print(json.dumps(system_collections, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/discovery_v1"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    discovery = DiscoveryV1.new(
      version: "2019-04-30",
      authenticator: authenticator
    )
    discovery.service_url = "{url}"
    
    environments = discovery.list_environments
    puts JSON.pretty_generate(environments.result)
    
    news_environments = []
    environments.result["environments"].each { |x| news_environments << x if x["name"] == "Watson System Environment"}
    news_environment_id = news_environments[0]["environment_id"]
    puts news_environment_id
    
    collections = discovery.list_collections(
      environment_id: news_environment_id
    )
    news_collections = []
    collections.result["collections"].each { |x| news_collections << x }
    puts JSON.pretty_generate(news_collections)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let discovery = Discovery(version: "2019-04-30", authenticator: authenticator)
    discovery.serviceURL = "{url}"
    
    discovery.listEnvironments() {
      response, error in
    
      guard let environments = response?.result else {
        print(error?.localizedDescription ?? "unexpected error")
        return
      }
    
      print(environments)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var discovery = new DiscoveryService("2019-04-30", authenticator);
    discovery.SetServiceUrl("{url}");
    
    ListEnvironmentsResponse listEnvironmentsResponse = null;
    discovery.ListEnvironments(
        callback: (DetailedResponse<ListEnvironmentsResponse> response, IBMError error) =>
        {
            Log.Debug("DiscoveryServiceV1", "ListEnvironments result: {0}", response.Response);
            listEnvironmentsResponse = response.Result;
        }
    );
    
    while (listEnvironmentsResponse == null)
        yield return null;

Response

Response object containing an array of configured environments.

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Response object containing an array of configured environments.

Example:

Status Code

  • Successful response.

  • Bad request.

Example responses
  • {
      "environments": [
        {
          "environment_id": "ecbda78e-fb06-40b1-a43f-a039fac0adc6",
          "name": "byod_environment",
          "description": "Private Data Environment",
          "created": "2017-07-14T12:54:40.985Z",
          "updated": "2017-07-14T12:54:40.985Z",
          "read_only": false
        },
        {
          "environment_id": "system",
          "name": "Watson System Environment",
          "description": "Watson System environment",
          "created": "2017-07-13T01:14:20.761Z",
          "updated": "2017-07-13T01:14:20.761Z",
          "read_only": true
        }
      ]
    }
  • {
      "environments": [
        {
          "environment_id": "ecbda78e-fb06-40b1-a43f-a039fac0adc6",
          "name": "byod_environment",
          "description": "Private Data Environment",
          "created": "2017-07-14T12:54:40.985Z",
          "updated": "2017-07-14T12:54:40.985Z",
          "read_only": false
        },
        {
          "environment_id": "system",
          "name": "Watson System Environment",
          "description": "Watson System environment",
          "created": "2017-07-13T01:14:20.761Z",
          "updated": "2017-07-13T01:14:20.761Z",
          "read_only": true
        }
      ]
    }

Get environment info

GET /v1/environments/{environment_id}
(discovery *DiscoveryV1) GetEnvironment(getEnvironmentOptions *GetEnvironmentOptions) (result *Environment, response *core.DetailedResponse, err error)
ServiceCall<Environment> getEnvironment(GetEnvironmentOptions getEnvironmentOptions)
getEnvironment(params, [callback()])
get_environment(self, environment_id, **kwargs)
get_environment(environment_id:)
func getEnvironment(
    environmentID: String,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Environment>?, WatsonError?) -> Void)
GetEnvironment(string environmentId)
GetEnvironment(Callback<ModelEnvironment> callback, string environmentId)

Request

Instantiate the GetEnvironmentOptions struct and set the fields to provide parameter values for the GetEnvironment method.

Use the GetEnvironmentOptions.Builder to create a GetEnvironmentOptions object that contains the parameter values for the getEnvironment method.

Path Parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression ^[a-zA-Z0-9_-]*$

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 2019-04-30.

The GetEnvironment options.

The getEnvironment options.

parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression /^[a-zA-Z0-9_-]*$/

parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression /^[a-zA-Z0-9_-]*$/

parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression /^[a-zA-Z0-9_-]*$/

parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression /^[a-zA-Z0-9_-]*$/

parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression /^[a-zA-Z0-9_-]*$/

parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression /^[a-zA-Z0-9_-]*$/

  • curl -u "apikey":"{apikey}" "{url}/v1/environments/{environment_id}?version=2019-04-30"
  • IamAuthenticator authenticator = new IamAuthenticator(
        apikey: "{apikey}"
        );
    
    DiscoveryService discovery = new DiscoveryService("2019-04-30", authenticator);
    discovery.SetServiceUrl("{url}");
    
    var result = discovery.GetEnvironment(
        environmentId: "{environmentId}"
        );
    
    Console.WriteLine(result.Response);
  • package main
    
    import (
      "encoding/json"
      "fmt"
      "github.com/IBM/go-sdk-core/core"
      "github.com/watson-developer-cloud/go-sdk/discoveryv1"
    )
    
    func main() {
      authenticator := &core.IamAuthenticator{
        ApiKey:     "{apikey}",
      }
    
      options := &discoveryv1.DiscoveryV1Options{
        Version: "2019-04-30",
        Authenticator: authenticator,
      }
    
      discovery, discoveryErr := discoveryv1.NewDiscoveryV1(options)
    
      if discoveryErr != nil {
        panic(discoveryErr)
      }
    
      discovery.SetServiceURL("{url}")
    
      result, response, responseErr := discovery.GetEnvironment(
        &discoveryv1.GetEnvironmentOptions{
          EnvironmentID: core.StringPtr("{environment_id}"),
        },
      )
      if responseErr != nil {
        panic(responseErr)
      }
      b, _ := json.MarshalIndent(result, "", "  ")
      fmt.Println(string(b))
    }
  • IamAuthenticator authenticator = new IamAuthenticator("{apikey}");
    Discovery discovery = new Discovery("2019-04-30", authenticator);
    discovery.setServiceUrl("{url}");
    
    String environmentId = "{environment_id}";
    
    GetEnvironmentOptions getOptions = new GetEnvironmentOptions.Builder(environmentId).build();
    Environment getResponse = discovery.getEnvironment(getOptions).execute().getResult();
  • const DiscoveryV1 = require('ibm-watson/discovery/v1');
    const { IamAuthenticator } = require('ibm-watson/auth');
    
    const discovery = new DiscoveryV1({
      version: '2019-04-30',
      authenticator: new IamAuthenticator({
        apikey: '{apikey}',
      }),
      serviceUrl: '{url}',
    });
    
    const getEnvironmentParams = {
      environmentId: '{environment_id}',
    };
    
    discovery.getEnvironment(getEnvironmentParams)
      .then(environment => {
        console.log(JSON.stringify(environment, null, 2));
      })
      .catch(err => {
        console.log('error:', err);
      });
  • import json
    from ibm_watson import DiscoveryV1
    from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
    
    authenticator = IAMAuthenticator('{apikey}')
    discovery = DiscoveryV1(
        version='2019-04-30',
        authenticator=authenticator
    )
    
    discovery.set_service_url('{url}')
    
    environment_info = discovery.get_environment(
        '{environment_id}').get_result()
    print(json.dumps(environment_info, indent=2))
  • require "json"
    require "ibm_watson/authenticators"
    require "ibm_watson/discovery_v1"
    include IBMWatson
    
    authenticator = Authenticators::IamAuthenticator.new(
      apikey: "{apikey}"
    )
    
    discovery = DiscoveryV1.new(
      version: "2019-04-30",
      authenticator: authenticator
    )
    discovery.service_url = "{url}"
    
    environment_info = discovery.get_environment(
      environment_id: "{environment_id}"
    )
    puts JSON.pretty_generate(environment_info.result)
  • let authenticator = WatsonIAMAuthenticator(apiKey: "{apikey}")
    let discovery = Discovery(version: "2019-04-30", authenticator: authenticator)
    discovery.serviceURL = "{url}"
    
    discovery.getEnvironment(environmentID: "{environment_id}") {
      response, error in
    
      guard let environment = response?.result else {
        print(error?.localizedDescription ?? "unexpected error")
        return
      }
    
      print(environment)
    }
  • var authenticator = new IamAuthenticator(
        apikey: "{apikey}"
    );
    
    while (!authenticator.CanAuthenticate())
        yield return null;
    
    var discovery = new DiscoveryService("2019-04-30", authenticator);
    discovery.SetServiceUrl("{url}");
    
    ModelEnvironment getEnvironmentResponse = null;
    discovery.GetEnvironment(
        callback: (DetailedResponse<ModelEnvironment> response, IBMError error) =>
        {
            Log.Debug("DiscoveryServiceV1", "GetEnvironment result: {0}", response.Response);
            getEnvironmentResponse = response.Result;
        },
        environmentId: "{environmentId}"
    );
    
    while (getEnvironmentResponse == null)
        yield return null;

Response

Details about an environment.

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Details about an environment.

Example:

Status Code

  • Environment fetched.

  • Bad request.

Example responses
  • {
      "environment_id": "f822208e-e4c2-45f8-a0d6-c2be950fbcc8",
      "name": "test_environment",
      "description": "Test environment",
      "created": "2016-06-16T10:56:54.957Z",
      "updated": "2017-05-16T13:56:54.957Z",
      "status": "active",
      "read_only": false,
      "size": "M",
      "index_capacity": {
        "documents": {
          "indexed": 0,
          "maximum_allowed": 1000000
        },
        "disk_usage": {
          "used_bytes": 0,
          "maximum_allowed_bytes": 85899345920
        },
        "collections": {
          "available": 1,
          "maximum_allowed": 4
        }
      },
      "search_status": [
        {
          "scope": "environment",
          "status": "NO_DATA",
          "status_description": "The system is employing the default strategy for document search natural_language_query. Enable query and event logging so we can initiate relevancy training to improve search accuracy."
        }
      ]
    }
  • {
      "environment_id": "f822208e-e4c2-45f8-a0d6-c2be950fbcc8",
      "name": "test_environment",
      "description": "Test environment",
      "created": "2016-06-16T10:56:54.957Z",
      "updated": "2017-05-16T13:56:54.957Z",
      "status": "active",
      "read_only": false,
      "size": "M",
      "index_capacity": {
        "documents": {
          "indexed": 0,
          "maximum_allowed": 1000000
        },
        "disk_usage": {
          "used_bytes": 0,
          "maximum_allowed_bytes": 85899345920
        },
        "collections": {
          "available": 1,
          "maximum_allowed": 4
        }
      },
      "search_status": [
        {
          "scope": "environment",
          "status": "NO_DATA",
          "status_description": "The system is employing the default strategy for document search natural_language_query. Enable query and event logging so we can initiate relevancy training to improve search accuracy."
        }
      ]
    }

Update an environment

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

Updates an environment. The environment's name and description parameters can be changed. You must specify a name for the environment.

PUT /v1/environments/{environment_id}
(discovery *DiscoveryV1) UpdateEnvironment(updateEnvironmentOptions *UpdateEnvironmentOptions) (result *Environment, response *core.DetailedResponse, err error)
ServiceCall<Environment> updateEnvironment(UpdateEnvironmentOptions updateEnvironmentOptions)
updateEnvironment(params, [callback()])
update_environment(self, environment_id, name=None, description=None, size=None, **kwargs)
update_environment(environment_id:, name: nil, description: nil, size: nil)
func updateEnvironment(
    environmentID: String,
    name: String? = nil,
    description: String? = nil,
    size: String? = nil,
    headers: [String: String]? = nil,
    completionHandler: @escaping (WatsonResponse<Environment>?, WatsonError?) -> Void)
UpdateEnvironment(string environmentId, string name = null, string description = null, string size = null)
UpdateEnvironment(Callback<ModelEnvironment> callback, string environmentId, string name = null, string description = null, string size = null)

Request

Instantiate the UpdateEnvironmentOptions struct and set the fields to provide parameter values for the UpdateEnvironment method.

Use the UpdateEnvironmentOptions.Builder to create a UpdateEnvironmentOptions object that contains the parameter values for the updateEnvironment method.

Path Parameters

  • The ID of the environment.

    Constraints: 1 ≤ length ≤ 255, Value must match regular expression ^[a-zA-Z0-9_-]*$

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 2019-04-30.

An object that defines the environment's name and, optionally, description.

The UpdateEnvironment options.