- Notifications
You must be signed in to change notification settings - Fork527
🥇 Java SDK to use the IBM Watson services.
License
watson-developer-cloud/java-sdk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Java client library to use theWatson APIs.
- You need anIBM Cloud account.
All the services:
<dependency><groupId>com.ibm.watson</groupId><artifactId>ibm-watson</artifactId><version>16.1.0</version></dependency>
Only Discovery:
<dependency><groupId>com.ibm.watson</groupId><artifactId>discovery</artifactId><version>16.1.0</version></dependency>
All the services:
'com.ibm.watson:ibm-watson:16.1.0'Only Assistant:
'com.ibm.watson:assistant:16.1.0'Now, you are ready to see someexamples.
The examples within each service assume that you already have service credentials. If not,you will have tocreate a service in IBM Cloud.
If you are running your application in IBM Cloud (or other platforms based on Cloud Foundry), you don't need to specify thecredentials; the library will get them for you by looking at theVCAP_SERVICES environment variable.
When running in IBM Cloud (or other platforms based on Cloud Foundry), the library will automatically get the credentials fromVCAP_SERVICES.If you have more than one plan, you can useCredentialUtils to get the service credentials for an specific plan.
Watson services are migrating to token-based Identity and Access Management (IAM) authentication.
As ofv9.2.1, the preferred approach of initializing an authenticator is the builder pattern. This pattern supportsconstructing the authenticator with only the properties that you need. Also, if you're authenticating to a Watson serviceon Cloud Pak for Data that supports IAM, you must use the builder pattern.
- You can initialize the authenticator with either of the following approaches:
- In the builder of the authenticator (builder pattern).
- In the constructor of the authenticator (deprecated, but still available).
- With some service instances, you authenticate to the API by usingIAM.
- In other instances, you authenticate by providing theusername and password for the service instance.
- If you're using a Watson service on Cloud Pak for Data, you'll need to authenticate in aspecific way.
To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services:
- Go to the IBM CloudDashboard page.
- Either click an existing Watson service instance in yourresource list or clickCreate resource > AI and create a service instance.
- Click on theManage item in the left nav bar of your service instance.
On this page, you should be able to see your credentials for accessing your service instance.
In your code, you can use these values in the service constructor or with a method call after instantiating your service.
There are two ways to supply the credentials you found above to the SDK for authentication.
With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing it and authenticating. You can get this file by clicking theDownload button for the credentials in theManage tab of your service instance.
The file downloaded will be calledibm-credentials.env. This is the name the SDK will search for andmust be preserved unless you want to configure the file path (more on that later). The SDK will look for youribm-credentials.env file in the following places (in order):
- Your system's home directory
- The top-level directory of the project you're using the SDK in
As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following:
Discoveryservice =newDiscovery("2023-03-31");
And that's it!
If you're using more than one service at a time in your code and get two differentibm-credentials.env files, just put the contents together in oneibm-credentials.env file and the SDK will handle assigning credentials to their appropriate services.
If you would like to configure the location/name of your credential file, you can set an environment variable calledIBM_CREDENTIALS_FILE.This will take precedence over the locations specified above. Here's how you can do that:
export IBM_CREDENTIALS_FILE="<path>"
where<path> is something like/home/user/Downloads/<file_name>.env.
If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you.
Some services use token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated.
You supply either an IAM serviceAPI key or anaccess token:
- Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary.
- Use the access token if you want to manage the lifecycle yourself. For details, seeAuthenticating with IAM tokens.
Supplying the IAM API key:
Builder pattern approach:
// letting the SDK manage the IAM tokenAuthenticatorauthenticator =newIamAuthenticator.Builder() .apikey("<iam_api_key>") .build();Discoveryservice =newDiscovery("2023-03-31",authenticator);
Deprecated constructor approach:
// letting the SDK manage the IAM tokenAuthenticatorauthenticator =newIamAuthenticator("<iam_api_key>");Discoveryservice =newDiscovery("2023-03-31",authenticator);
Supplying the access token:
// assuming control of managing IAM tokenAuthenticatorauthenticator =newBearerTokenAuthenticator("<access_token>");Discoveryservice =newDiscovery("2023-03-31",authenticator);
Builder pattern approach:
Authenticatorauthenticator =newBasicAuthenticator.Builder() .username("<username>") .password("<password>") .build();Discoveryservice =newDiscovery("2023-03-31",authenticator);
Deprecated constructor approach:
Authenticatorauthenticator =newBasicAuthenticator("<username>","<password>");Discoveryservice =newDiscovery("2023-03-31",authenticator);
Authenticating with ICP is similar to the basic username and password method, except that you need to make sure to disable SSL verification to authenticate properly. Seehere for more information.
Authenticatorauthenticator =newBasicAuthenticator("<username>","<password>");Discoveryservice =newDiscovery("2023-03-31",authenticator);HttpConfigOptionsoptions =newHttpConfigOptions.Builder() .disableSslVerification(true) .build();service.configureClient(options);
Like IAM, you can pass in credentials to let the SDK manage an access token for you or directly supply an access token to do it yourself.
Builder pattern approach:
// letting the SDK manage the tokenAuthenticatorauthenticator =newCloudPakForDataAuthenticator.Builder() .url("<CP4D token exchange base URL>") .username("<username>") .password("<password>") .disableSSLVerification(true) .headers(null) .build();Discoveryservice =newDiscovery("2023-03-31",authenticator);service.setServiceUrl("<service CP4D URL>");
Deprecated constructor approach:
// letting the SDK manage the tokenAuthenticatorauthenticator =newCloudPakForDataAuthenticator("<CP4D token exchange base URL>","<username>","<password>",true,// disabling SSL verificationnull,);Discoveryservice =newDiscovery("2023-03-31",authenticator);service.setServiceUrl("<service CP4D URL>");
// assuming control of managing the access tokenAuthenticatorauthenticator =newBearerTokenAuthenticator("<access_token>");Discoveryservice =newDiscovery("2023-03-31",authenticator);service.setServiceUrl("<service CP4D URL>");
Be sure to both disable SSL verification when authenticating and set the endpoint explicitly to the URL given in Cloud Pak for Data.
To use the SDK through a third party cloud provider (such as AWS), use theMCSPAuthenticator. This will require the base endpoint URL for the MCSP token service (e.g.https://iam.platform.saas.ibm.com) and an apikey.
// letting the SDK manage the tokenAuthenticatorauthenticator =newMCSPAuthenticator.Builder() .apikey("apikey") .url("token_service_endpoint") .build();Assistantservice =newAssistant("2023-06-15",authenticator);service.setServiceUrl("<url_as_per_region>");
No matter which method you use to make an API request (execute(),enqueue(), orreactiveRequest()), you'll get back an object of formResponse<T>, whereT is the model representing the specific response model.
Here's an example of how to parse that response and get additional information beyond the response model:
// listing our workspaces with an instance of the Assistant v1 serviceResponse<WorkspaceCollection>response =service.listWorkspaces().execute();// pulling out the specific API method response, which we can manipulate as usualWorkspaceCollectioncollection =response.getResult();System.out.println("My workspaces: " +collection.getWorkspaces());// grabbing headers that came back with our API responseHeadersresponseHeaders =response.getHeaders();System.out.println("Response header names: " +responseHeaders.names());
The HTTP client can be configured by using thesetProxy() method on your authenticator and using theconfigureClient() method on your service object, passing in anHttpConfigOptions object. For a full list of configurable options look at this linked Builder class forHttpConfigOptions. Currently, the following options are supported:
- Disabling SSL verification (only do this if you really mean to!)
⚠️ - Setting gzip compression
- Setting max retry and retry interval
- Using a proxy (more info here:OkHTTPClient Proxy authentication how to?)
- Setting HTTP logging verbosity
Here's an example of setting the above:
Proxyproxy =newProxy(Proxy.Type.HTTP,newInetSocketAddress("proxyHost",8080));IamAuthenticatorauthenticator =newIamAuthenticator(apiKey);authenticator.setProxy(proxy);Discoveryservice =newDiscovery("2023-03-31",authenticator);// setting configuration optionsHttpConfigOptionsoptions =newHttpConfigOptions.Builder() .disableSslVerification(true) .proxy(proxy) .loggingLevel(HttpConfigOptions.LoggingLevel.BASIC) .build();service.configureClient(options);
The basic, synchronous way to make API calls with this SDK is through the use of theexecute() method. Using this method looks something like this:
// make API callResponse<ListEnvironmentsResponse>response =service.listEnvironments().execute();// continue execution
However, if you need to perform these calls in the background, there are two other methods to do this asynchronously:enqueue() andreactiveRequest().
This method allows you to set a callback for the service response through the use of theServiceCallback object. Here's an example:
// make API call in the backgroundservice.listEnvironments().enqueue(newServiceCallback<ListEnvironmentsResponse>() {@OverridepublicvoidonResponse(Response<ListEnvironmentsResponse>response) {System.out.println("We did it! " +response); }@OverridepublicvoidonFailure(Exceptione) {System.out.println("Whoops..."); }});// continue working in the meantime!
If you're a fan of theRxJava library, this method lets you leverage that to allow for "reactive" programming. The method will return aSingle<T> which you can manipulate how you please. Example:
// get stream with requestSingle<Response<ListEnvironmentsResponse>>observableRequest =service.listEnvironments().reactiveRequest();// make API call in the backgroundobservableRequest .subscribeOn(Schedulers.single()) .subscribe(response ->System.out.println("We did it with s~t~r~e~a~m~s! " +response));// continue working in the meantime!
Default headers can be specified at any time by using thesetDefaultHeaders(Map<String, String> headers) method.
The example below sends theX-Watson-Learning-Opt-Out header in every request preventing Watson from using the payload to improve the service.
PersonalityInsightsservice =newPersonalityInsights("2017-10-13",newNoAuthAuthenticator());Map<String,String>headers =newHashMap<String,String>();headers.put(WatsonHttpHeaders.X_WATSON_LEARNING_OPT_OUT,"true");service.setDefaultHeaders(headers);// All the api calls from now on will send the default headers
Custom headers can be passed with any request. To do so, add the header to theServiceCall object before executing the request. For example, this is what it looks like to send the headerCustom-Header along with a call to the Watson Assistant service:
Response<WorkspaceCollection>workspaces =service.listWorkspaces() .addHeader("Custom-Header","custom_value") .execute();
It's possible that you may want to cancel a request you make to a service. For example, you may set some timeout threshold and just want to cancel an asynchronous if it doesn't respond in time. You can do that by calling thecancel() method on yourServiceCall object. For example:
// time to consider timeout (in ms)longtimeoutThreshold =3000;// storing ServiceCall object we'll use to list our Assistant v1 workspacesServiceCall<WorkspaceCollection>call =service.listWorkspaces();longstartTime =System.currentTimeMillis();call.enqueue(newServiceCallback<WorkspaceCollection>() {@OverridepublicvoidonResponse(Response<WorkspaceCollection>response) {// store the result somewherefakeDb.store("my-key",response.getResult()); }@OverridepublicvoidonFailure(Exceptione) {System.out.println("The request failed :("); }});// keep waiting for the call to complete while we're within the timeout boundswhile ((fakeDb.retrieve("my-key") ==null) && (System.currentTimeMillis() -startTime <timeoutThreshold)) {Thread.sleep(500);}// if we timed out and it's STILL not complete, we'll just cancel the callif (fakeDb.retrieve("my-key") ==null) {call.cancel();}
Doing so will call youronFailure() implementation.
Every SDK call returns a response with a transaction ID in theX-Global-Transaction-Id header. This transaction ID is useful for troubleshooting and accessing relevant logs from your service instance.
Assistantservice =newAssistant("2019-02-28");ListWorkspacesOptionsoptions =newListWorkspacesOptions.Builder().build();Response<WorkspaceCollection>response;try {// In a successful case, you can grab the ID with the following code.response =service.listWorkspaces(options).execute();StringtransactionId =response.getHeaders().values("X-Global-Transaction-Id").get(0);}catch (ServiceResponseExceptione) {// This is how you get the ID from a failed request.// Make sure to use the ServiceResponseException class or one of its subclasses!StringtransactionId =e.getHeaders().values("X-Global-Transaction-Id").get(0);}
However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace<my-unique-transaction-id> in the following example with a unique transaction ID.
Authenticatorauthenticator =newIamAuthenticator("apiKey");service =newAssistant("{version-date}",authenticator);service.setServiceUrl("{serviceUrl}");Map<String,String>headers =newHashMap<>();headers.put("X-Global-Transaction-Id","<my-unique-transaction-id>");service.setDefaultHeaders(headers);MessageOptionsoptions =newMessageOptions.Builder(workspaceId).build();MessageResponseresult =service.message(options).execute().getResult();
It does! You should be able to plug this dependency into your Android app without any issue. In addition, we have an Android SDK meant to be used with this library that adds some Android-specific functionality, which you can findhere.
Great question (and please do)! You can find contributing informationhere.
If you have issues with the APIs or have a question about the Watson services, seeStack Overflow.
We do 😎http://ibm.github.io/
We'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it.
Thanks goes to these wonderful people (emoji key):
Logan Patino 💻🎨🐛 | Ajiemar Santiago 💻🎨🐛 | German Attanasio 💻🎨📖 | Kevin Kowalski 💻🎨🐛📖 | Jeff Arn 💻🎨🐛📖 | Angelo Paparazzi 💻🎨🐛📖 |
This project follows theall-contributors specification. Contributions of any kind welcome!
About
🥇 Java SDK to use the IBM Watson services.
Topics
Resources
License
Code of conduct
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.