https://github.com/watson-developer-cloud/java-sdk
:1st_place_medal: Java SDK to use the IBM Watson services.
Science Score: 26.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
○CITATION.cff file
-
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
○DOI references
-
○Academic publication links
-
○Committers with academic emails
-
○Institutional organization owner
-
○JOSS paper metadata
-
○Scientific vocabulary similarity
Low similarity (9.5%) to scientific vocabulary
Keywords
Keywords from Contributors
Repository
:1st_place_medal: Java SDK to use the IBM Watson services.
Basic Info
- Host: GitHub
- Owner: watson-developer-cloud
- License: apache-2.0
- Language: Java
- Default Branch: master
- Homepage: http://watson-developer-cloud.github.io/java-sdk/
- Size: 394 MB
Statistics
- Stars: 596
- Watchers: 101
- Forks: 531
- Open Issues: 5
- Releases: 116
Topics
Metadata Files
README.md
Watson APIs Java SDK
Deprecated builds
Java client library to use the Watson APIs.
Before you begin
- You need an IBM Cloud account.
Installation
Maven
All the services:
xml
<dependency>
<groupId>com.ibm.watson</groupId>
<artifactId>ibm-watson</artifactId>
<version>15.0.0</version>
</dependency>
Only Discovery:
xml
<dependency>
<groupId>com.ibm.watson</groupId>
<artifactId>discovery</artifactId>
<version>15.0.0</version>
</dependency>
Gradle
All the services:
gradle
'com.ibm.watson:ibm-watson:15.0.0'
Only Assistant:
gradle
'com.ibm.watson:assistant:15.0.0'
Now, you are ready to see some examples.
Usage
The examples within each service assume that you already have service credentials. If not, you will have to create 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 the
credentials; the library will get them for you by looking at the VCAP_SERVICES environment variable.
Running in IBM Cloud
When running in IBM Cloud (or other platforms based on Cloud Foundry), the library will automatically get the credentials from VCAP_SERVICES.
If you have more than one plan, you can use CredentialUtils to get the service credentials for an specific plan.
Authentication
Watson services are migrating to token-based Identity and Access Management (IAM) authentication.
As of v9.2.1, the preferred approach of initializing an authenticator is the builder pattern. This pattern supports
constructing the authenticator with only the properties that you need. Also, if you're authenticating to a Watson service
on 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 using IAM.
- In other instances, you authenticate by providing the username and password for the service instance.
- If you're using a Watson service on Cloud Pak for Data, you'll need to authenticate in a specific way.
Getting credentials
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 Cloud Dashboard page.
- Either click an existing Watson service instance in your resource list or click Create resource > AI and create a service instance.
- Click on the Manage 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.
Supplying credentials
There are two ways to supply the credentials you found above to the SDK for authentication.
Credential file (easier!)
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 the Download button for the credentials in the Manage tab of your service instance.
The file downloaded will be called ibm-credentials.env. This is the name the SDK will search for and must be preserved unless you want to configure the file path (more on that later). The SDK will look for your ibm-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:
java
Discovery service = new Discovery("2023-03-31");
And that's it!
If you're using more than one service at a time in your code and get two different ibm-credentials.env files, just put the contents together in one ibm-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 called IBM_CREDENTIALS_FILE. This will take precedence over the locations specified above. Here's how you can do that:
bash
export IBM_CREDENTIALS_FILE="<path>"
where <path> is something like /home/user/Downloads/<file_name>.env.
Manually
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.
IAM
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 service API key or an access 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, see Authenticating with IAM tokens.
Supplying the IAM API key:
Builder pattern approach:
java
// letting the SDK manage the IAM token
Authenticator authenticator = new IamAuthenticator.Builder()
.apikey("<iam_api_key>")
.build();
Discovery service = new Discovery("2023-03-31", authenticator);
Deprecated constructor approach:
java
// letting the SDK manage the IAM token
Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
Discovery service = new Discovery("2023-03-31", authenticator);
Supplying the access token:
java
// assuming control of managing IAM token
Authenticator authenticator = new BearerTokenAuthenticator("<access_token>");
Discovery service = new Discovery("2023-03-31", authenticator);
Username and password
Builder pattern approach:
java
Authenticator authenticator = new BasicAuthenticator.Builder()
.username("<username>")
.password("<password>")
.build();
Discovery service = new Discovery("2023-03-31", authenticator);
Deprecated constructor approach:
java
Authenticator authenticator = new BasicAuthenticator("<username>", "<password>");
Discovery service = new Discovery("2023-03-31", authenticator);
ICP
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. See here for more information.
```java
Authenticator authenticator = new BasicAuthenticator("
HttpConfigOptions options = new HttpConfigOptions.Builder() .disableSslVerification(true) .build();
service.configureClient(options); ```
Cloud Pak for Data
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:
java
// letting the SDK manage the token
Authenticator authenticator = new CloudPakForDataAuthenticator.Builder()
.url("<CP4D token exchange base URL>")
.username("<username>")
.password("<password>")
.disableSSLVerification(true)
.headers(null)
.build();
Discovery service = new Discovery("2023-03-31", authenticator);
service.setServiceUrl("<service CP4D URL>");
Deprecated constructor approach:
java
// letting the SDK manage the token
Authenticator authenticator = new CloudPakForDataAuthenticator(
"<CP4D token exchange base URL>",
"<username>",
"<password>",
true, // disabling SSL verification
null,
);
Discovery service = new Discovery("2023-03-31", authenticator);
service.setServiceUrl("<service CP4D URL>");
java
// assuming control of managing the access token
Authenticator authenticator = new BearerTokenAuthenticator("<access_token>");
Discovery service = new Discovery("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.
MCSP
To use the SDK through a third party cloud provider (such as AWS), use the MCSPAuthenticator. This will require the base endpoint URL for the MCSP token service (e.g. https://iam.platform.saas.ibm.com) and an apikey.
java
// letting the SDK manage the token
Authenticator authenticator = new MCSPAuthenticator.Builder()
.apikey("apikey")
.url("token_service_endpoint")
.build();
Assistant service = new Assistant("2023-06-15", authenticator);
service.setServiceUrl("<url_as_per_region>");
Using the SDK
Parsing responses
No matter which method you use to make an API request (execute(), enqueue(), or reactiveRequest()), you'll get back an object of form Response<T>, where T 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:
```java
// listing our workspaces with an instance of the Assistant v1 service
Response
// pulling out the specific API method response, which we can manipulate as usual WorkspaceCollection collection = response.getResult(); System.out.println("My workspaces: " + collection.getWorkspaces());
// grabbing headers that came back with our API response Headers responseHeaders = response.getHeaders(); System.out.println("Response header names: " + responseHeaders.names()); ```
Configuring the HTTP client
The HTTP client can be configured by using the setProxy() method on your authenticator and using the configureClient() method on your service object, passing in an HttpConfigOptions object. For a full list of configurable options look at this linked Builder class for HttpConfigOptions. 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:
```java Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyHost", 8080)); IamAuthenticator authenticator = new IamAuthenticator(apiKey); authenticator.setProxy(proxy);
Discovery service = new Discovery("2023-03-31", authenticator);
// setting configuration options HttpConfigOptions options = new HttpConfigOptions.Builder() .disableSslVerification(true) .proxy(proxy) .loggingLevel(HttpConfigOptions.LoggingLevel.BASIC) .build();
service.configureClient(options); ```
Making asynchronous API calls
The basic, synchronous way to make API calls with this SDK is through the use of the execute() method. Using this method looks something like this:
```java
// make API call
Response
// continue execution ```
However, if you need to perform these calls in the background, there are two other methods to do this asynchronously: enqueue() and reactiveRequest().
enqueue()
This method allows you to set a callback for the service response through the use of the ServiceCallback object. Here's an example:
```java
// make API call in the background
service.listEnvironments().enqueue(new ServiceCallback
@Override public void onFailure(Exception e) { System.out.println("Whoops..."); } });
// continue working in the meantime! ```
reactiveRequest()
If you're a fan of the RxJava library, this method lets you leverage that to allow for "reactive" programming. The method will return a Single<T> which you can manipulate how you please. Example:
```java
// get stream with request
Single
// make API call in the background observableRequest .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
Default headers can be specified at any time by using the setDefaultHeaders(Map<String, String> headers) method.
The example below sends the X-Watson-Learning-Opt-Out header in every request preventing Watson from using the payload to improve the service.
```java PersonalityInsights service = new PersonalityInsights("2017-10-13", new NoAuthAuthenticator());
Map
service.setDefaultHeaders(headers);
// All the api calls from now on will send the default headers ```
Sending request headers
Custom headers can be passed with any request. To do so, add the header to the ServiceCall object before executing the request. For example, this is what it looks like to send the header Custom-Header along with a call to the Watson Assistant service:
java
Response<WorkspaceCollection> workspaces = service.listWorkspaces()
.addHeader("Custom-Header", "custom_value")
.execute();
Canceling requests
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 the cancel() method on your ServiceCall object. For example:
```java // time to consider timeout (in ms) long timeoutThreshold = 3000;
// storing ServiceCall object we'll use to list our Assistant v1 workspaces
ServiceCall
long startTime = System.currentTimeMillis();
call.enqueue(new ServiceCallback
@Override public void onFailure(Exception e) { System.out.println("The request failed :("); } });
// keep waiting for the call to complete while we're within the timeout bounds while ((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 call if (fakeDb.retrieve("my-key") == null) { call.cancel(); } ```
Doing so will call your onFailure() implementation.
Transaction IDs
Every SDK call returns a response with a transaction ID in the X-Global-Transaction-Id header. This transaction ID is useful for troubleshooting and accessing relevant logs from your service instance.
```java
Assistant service = new Assistant("2019-02-28");
ListWorkspacesOptions options = new ListWorkspacesOptions.Builder().build();
Response
try { // In a successful case, you can grab the ID with the following code. response = service.listWorkspaces(options).execute(); String transactionId = response.getHeaders().values("X-Global-Transaction-Id").get(0); } catch (ServiceResponseException e) { // This is how you get the ID from a failed request. // Make sure to use the ServiceResponseException class or one of its subclasses! String transactionId = 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.
```java
Authenticator authenticator = new IamAuthenticator("apiKey");
service = new Assistant("{version-date}", authenticator);
service.setServiceUrl("{serviceUrl}");
Map
MessageOptions options = new MessageOptions.Builder(workspaceId).build(); MessageResponse result = service.message(options).execute().getResult(); ```
FAQ
Does this SDK play well with Android?
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 find here.
How can I contribute?
Great question (and please do)! You can find contributing information here.
Where can I get more help with using Watson APIs?
If you have issues with the APIs or have a question about the Watson services, see Stack Overflow.
Does IBM have any other open source work?
We do :sunglasses: http://ibm.github.io/
Featured projects
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.
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Logan Patino 💻 🎨 🐛 |
Ajiemar Santiago 💻 🎨 🐛 |
German Attanasio 💻 🎨 📖 ⚠️ |
Kevin Kowalski 💻 🎨 🐛 📖 ⚠️ 💬️ |
Jeff Arn 💻 🎨 🐛 📖 ⚠️ 💬️ |
Angelo Paparazzi 💻 🎨 🐛 📖 ⚠️ 💬️ 🥷🏼 |
This project follows the all-contributors specification. Contributions of any kind welcome!
Owner
- Name: IBM Watson APIs
- Login: watson-developer-cloud
- Kind: organization
- Location: USA
- Website: https://www.ibm.com/watson/developer/
- Twitter: ibmwatsonx
- Repositories: 97
- Profile: https://github.com/watson-developer-cloud
A collection of SDKs that work with the Watson REST APIs. For more information about the APIs, see https://cloud.ibm.com/docs?tab=api-docs&category=ai
GitHub Events
Total
- Create event: 8
- Release event: 3
- Issues event: 1
- Watch event: 7
- Delete event: 5
- Issue comment event: 12
- Push event: 17
- Pull request review comment event: 10
- Pull request review event: 9
- Pull request event: 9
- Fork event: 2
Last Year
- Create event: 8
- Release event: 3
- Issues event: 1
- Watch event: 7
- Delete event: 5
- Issue comment event: 12
- Push event: 17
- Pull request review comment event: 10
- Pull request review event: 9
- Pull request event: 9
- Fork event: 2
Committers
Last synced: 9 months ago
Top Committers
| Name | Commits | |
|---|---|---|
| Logan Patino | l****0@g****m | 1,217 |
| German Attanasio Ruiz | g****o@g****m | 850 |
| Kevin Kowalski | k****i@i****m | 308 |
| Mike Kistler | m****r@u****m | 98 |
| semantic-release-bot | s****t@m****t | 95 |
| Angelo Paparazzi | a****i@i****m | 65 |
| Michael G Mosca | m****m@u****m | 54 |
| Blake Ball | b****l@u****m | 50 |
| Max Vogler | m****r@d****m | 48 |
| Nizar | n****d@u****m | 40 |
| Gregory Seaman | g****n@u****m | 34 |
| Jeff Kaminski | j****s@u****m | 33 |
| Ajiemar Santiago | a****r@g****m | 30 |
| Samir J. Patel | s****a@u****m | 26 |
| grapebaba | 2****3@q****m | 23 |
| tanmayb123 | t****y@g****m | 22 |
| Dan O'Connor | d****r@u****m | 21 |
| Andrew Turgeon | a****n@g****m | 18 |
| Martin Harvan | m****n@g****m | 18 |
| repjarms | j****2@g****m | 17 |
| Joshua B. Smith | j****h@u****m | 13 |
| April Webster | a****r@u****m | 13 |
| Ruslan Ardashev | r****v@u****m | 12 |
| Aditya Gaitonde | a****n@u****m | 11 |
| Hsaylor | h****r@g****m | 11 |
| Allen Dean | a****n@u****m | 10 |
| Harrison | h****r@u****m | 10 |
| ExtremoBlando | r****a@a****s | 9 |
| Sarah Chen | s****2@g****m | 8 |
| allcontributors[bot] | 4****] | 8 |
| and 61 more... | ||
Committer Domains (Top 20 + Academic)
Issues and Pull Requests
Last synced: 7 months ago
All Time
- Total issues: 83
- Total pull requests: 291
- Average time to close issues: about 2 months
- Average time to close pull requests: 8 days
- Total issue authors: 23
- Total pull request authors: 15
- Average comments per issue: 3.95
- Average comments per pull request: 1.38
- Merged pull requests: 235
- Bot issues: 0
- Bot pull requests: 14
Past Year
- Issues: 1
- Pull requests: 4
- Average time to close issues: N/A
- Average time to close pull requests: about 10 hours
- Issue authors: 1
- Pull request authors: 1
- Average comments per issue: 7.0
- Average comments per pull request: 1.0
- Merged pull requests: 3
- Bot issues: 0
- Bot pull requests: 0
Top Authors
Issue Authors
- premchand-algo (2)
- manojsingh101 (2)
- vinzaceto (1)
- marloncarvalho (1)
- JxSun (1)
- Brian-Woodsworth (1)
- BadSkater0729 (1)
- prasant94 (1)
- munish-usit (1)
- abajzat (1)
- Vitals9367 (1)
- juliankamil (1)
- marconoel (1)
- sarahbacha (1)
- paulombweber (1)
Pull Request Authors
- kevinkowa (36)
- apaparazzi0329 (23)
- Mikemosca (10)
- mediumTaj (8)
- dependabot[bot] (5)
- germanattanasio (5)
- watson-github-bot (2)
- dskeba (2)
- trishahanlon (2)
- jeff-arn (1)
- nan2iz (1)
- JxSun (1)
- lgtm-com[bot] (1)
- ima1mai (1)
- allcontributors[bot] (1)
Top Labels
Issue Labels
Pull Request Labels
Dependencies
- ${project.groupId}:common compile
- com.ibm.cloud:sdk-core
- ${project.groupId}:common test
- com.squareup.okhttp3:mockwebserver test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- com.ibm.cloud:sdk-core
- ch.qos.logback:logback-classic 1.2.3 test
- com.google.guava:guava 27.1-android test
- com.squareup.okhttp3:mockwebserver 4.9.0 test
- junit:junit 4.12 test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- ${project.groupId}:common compile
- com.ibm.cloud:sdk-core
- ${project.groupId}:common test
- com.squareup.okhttp3:mockwebserver test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- com.ibm.watson:ibm-watson 10.0.1
- junit:junit 3.8.1 test
- com.ibm.watson:ibm-watson 9.3.0
- com.ibm.watson:assistant ${project.version} compile
- com.ibm.watson:common ${project.version} compile
- com.ibm.watson:discovery ${project.version} compile
- com.ibm.watson:language-translator ${project.version} compile
- com.ibm.watson:natural-language-understanding ${project.version} compile
- com.ibm.watson:speech-to-text ${project.version} compile
- com.ibm.watson:text-to-speech ${project.version} compile
- ${project.groupId}:common compile
- com.ibm.cloud:sdk-core
- ${project.groupId}:common test
- com.squareup.okhttp3:mockwebserver test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- ${project.groupId}:common compile
- com.ibm.cloud:sdk-core
- ${project.groupId}:common test
- com.squareup.okhttp3:mockwebserver test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- com.ibm.cloud:sdk-core 9.15.0
- com.ibm.watson:common 99-SNAPSHOT
- com.squareup.okhttp3:okhttp 4.9.0
- org.slf4j:slf4j-jdk14 1.7.25
- ch.qos.logback:logback-classic test
- ch.qos.logback:logback-classic 1.2.3 test
- com.ibm.watson:common 99-SNAPSHOT test
- com.squareup.okhttp3:mockwebserver 4.9.0 test
- org.powermock:powermock-api-mockito2 2.0.5 test
- org.powermock:powermock-module-testng 2.0.5 test
- org.testng:testng 7.4.0 test
- ${project.groupId}:common compile
- com.ibm.cloud:sdk-core
- ${project.groupId}:common test
- com.squareup.okhttp3:mockwebserver test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- ${project.groupId}:common compile
- com.ibm.cloud:sdk-core
- ${project.groupId}:common test
- com.squareup.okhttp3:mockwebserver test
- org.powermock:powermock-api-mockito2 test
- org.powermock:powermock-module-testng test
- org.testng:testng test
- 113 dependencies
- actions/checkout v2 composite
- actions/setup-java v2 composite
- actions/checkout v2 composite
- actions/setup-java v2 composite
- actions/setup-node v1 composite
- actions/setup-python v2 composite
- actions/checkout v2 composite
- actions/setup-java v2 composite
- voxmedia/github-action-slack-notify-build v1 composite
- maven 3.6.1-jdk-11-slim build