Code Robo
Virtual Service
Tester / Comparator
Java Code Complience

Sample Java Code To Connect Watson Assistant

This page demonstrate how to connect to IBM Watson Assistant from Java Applicaton (Java Client Program). .

Here one simple example is given on how to connect to a Watson assistant, create a session and send a request message and get the response.
Pre Requisite: It's assumed that you have already configured a Watson assistant at https://***** you are trying to connect your Watson assistant from a Java client code.
Sample avaCode:
 package com;


public class ConnectWatsonAssistant {

	public static void main(String[] args) {

		String apiKey = "rH*****************************8nV";
		String version = "2021-08-18";
		String serviceUrl = "******************";
		String assistantId = "25**********************5";
		IamAuthenticator authenticator = new IamAuthenticator(apiKey);
		Assistant assistant = new Assistant(version, authenticator);
		CreateSessionOptions options = new CreateSessionOptions.Builder(assistantId).build();
		SessionResponse response = assistant.createSession(options).execute().getResult();


		MessageInput input = new MessageInput.Builder().text("I am not feeling well.").build();
		MessageOptions messageOptions = new MessageOptions.Builder().assistantId(assistantId)
		MessageResponse messageResponse = assistant.message(messageOptions).execute().getResult();

		System.out.println("ResponseFromWatson=" + messageResponse);



It uses IBM Watson Assistant V2 API. It's part of IBM Watson Developer Cloud Java SDK If you are using Maven project please add the following dependency. Or downdload the jar and add to your project.
<?xml version="1.0" encoding="UTF-8"?>

Now main question is from where we get the values of Api Key, Version, Servie URL and Assistant Id:
  • apiKey - API key of to access IBM Watson services(e.g. Watson Assistant) which you have configured in IBM Cloud(e.g. https://******
  • version - This is the most confusing one. Its a date in YYYY-MM-DD format. Mainly it helps to identify if you have multiple version of same Watson Assistant
  • serviceUrl - URL of your Assistant which you have configured.
  • assistantId - Unique identifier of your Watson Assistand

You will get the above parameter values from Assistant settings at IBM Cloud (e.g. https://***** where you have configured your Watson Assistant. Screenshot with navigation is given below.

Assistant Page:

Assistant Setting Page:
Note: There is a catch on serviceUrl value. Please DO NOT take the entire value of Assistant URL from Setting page / screen. Take up to (Upto before /v2)

Output Of The Above Program:
  "session_id": "***********-abb5-4f1c-******2f9d"

  "output": {
    "generic": [
        "response_type": "text",
        "text": "What difficulties you are facing?"
    "intents": [
        "intent": "NotFeelingWell",
        "confidence": 1.0
    "entities": []
  "user_id": "**********-abb5-**********"
Please provide your feedback here