DEV Community

Thomas Südbröcker
Thomas Südbröcker

Posted on

SIMPLE NODE.JS SERVER EXAMPLE USING THE WATSON ASSISTANT API V2

This blog post is about a simple example to use the Watson Assistant API v2 with the Node.js SDK to get a Watson Assistant sessionID and send a message to Watson Assistant using this sessionID. Here is the GitHub project watson-assistant-simple-node-js-server-example.

The objective is only to start a chat session and return the values we get from Watson Assistant API v2 methods. The simple Node.js server has implemented following REST endpoints :

The project contains examples for using Postman. 😉

The blog post is structured in:

  • Connect to an assistant in the right environment
  • Implement a simple endpoint
  • Use the example
  • Summary

CONNECT TO AN ASSISTANT IN THE RIGHT ENVIRONMENT

Therefor we will first connect to our Watson Assistant service instance with the environmentID. Because we need to know to which environment we want to connect our server.

A small diagram with simplified dependencies. In my case I connected to the draft environment.

img

The GitHub project also contains a bash script to list the environments using cRUL.

The following code shows an extract of a return value of a bash script execution.

{"environments":[
    {"name":"draft",
     "description":"My Example Assistant",
     "environment":"draft",
     "assistant_id":"df8d00f8-e9cc-XXXXXXXX",
     "orchestration":{"search_skill_fallback":false},
     "environment_id":"3d6d1cd6-29fd-XXXXXXXX",
     "session_timeout":120,
      ...
}

Enter fullscreen mode Exit fullscreen mode

The relevant code in server.js file to connect to the right environment of the Watson Assistant service.

const assistant = new AssistantV2({
    version: e_version,
    authenticator: new IamAuthenticator({
      apikey: e_apikey,
    }),
    serviceUrl: e_serverUrl,
  });
Enter fullscreen mode Exit fullscreen mode

IMPLEMENT A SIMPLE ENDPOINT

When we are connected to the right assistant with the right environment, we can use this connection and we mostly just reuse the code given in the Watson Assistant API v2 documentation for the Node.js SDK in the implementation of our REST endpoint.

app.get('/getsession', (req, res) => {   
    assistant.createSession({
        assistantId: e_environmentID
    })
    .then(createSessionresult => {
        console.log(JSON.stringify(createSessionresult.result, null, 2));
        sessionID = JSON.stringify(createSessionresult.result, null, 2);
        res.statusCode = 200;
        res.write(sessionID);
        res.end();
    })
    .catch(createSessionError => {
        console.log(createSessionError);
        res.statusCode = 500;
        res.write(createSessionError);
        res.end();
    });  
});

Enter fullscreen mode Exit fullscreen mode

This is a simplified diagram of the given dependencies of our scenario.

img

USE THE EXAMPLE

Here are the steps you can follow to run this example on your local machine.

STEP 1: CLONE THE PROJECT TO YOUR LOCAL COMPUTER

git clone https://github.com/thomassuedbroecker/
watson-assistant-simple-node-js-server-example.git
cd
watson-assistant-simple-node-js-server-example/code/simple-server
Enter fullscreen mode Exit fullscreen mode

STEP 2: CONFIGURE THE ENVIRONMENT VARIABLES

Here we need an environmentID. We can find this ID in the Watson Assistant user interface, by navigating to the Environments page and selecting the environment you want to use (such as Draft or Live). Then you open the environment settings and copy the value from the appropriate field. (Contains the Link to the IBM Cloud documentation)

The image below shows the environment ID in the IBM Cloud UI.

img

We also need an API key and a base URL from the Credentials. The image blow shows the API key and the URL in the IBM Cloud UI.

img

  • Create an .env file
cat .env-template > .env
Enter fullscreen mode Exit fullscreen mode
  • Configure the .env file to your needs
WATSON_ASSISTANT_VERSION='2021-11-27'
WATSON_ASSISTANT_API_KEY='XXXX'
WATSON_ASSISTANT_SERVICE_URL='https://api.us-south.assistant.watson.cloud.ibm.com'
WATSON_ASSISTANT_ENVIRONMENT_ID='XXX'
Enter fullscreen mode Exit fullscreen mode

STEP 3: RUN LOCAL ON PORT 3010

npm install
npm start
Enter fullscreen mode Exit fullscreen mode

STEP 4: OPEN BROWSER AND INVOKE THE GET SESSION ENDPOINT

It returns the newly created sessionID.

open http://localhost:3010/getsession
Enter fullscreen mode Exit fullscreen mode
  • Example output:
{
"session_id": "37d13c72-1643-4add-bee5-574c6fd062dc"
}
Enter fullscreen mode Exit fullscreen mode

STEP 5: IMPORT THE POSTMAN COLLECTION INTO POSTMAN

The images shows the import button in postman.

img

Select the /postman/watson-assistant-example.postman_collection.json in the project for the import.

STEP 6: AFTER THE IMPORT YOU HAVE A NEW COLLECTION INSIDE YOUR POSTMAN

The images shows the imported collection.

img

STEP 7: SEND A MESSAGE

Here again the simplified diagram of the given dependencies of our scenario.

img

STEP 7.1: GET A SESSIONID

Now we need to get the sessionID with GET request using the getsession endpoint. We copy the value of the sessionID to use it inside the next REST endpoint invocation.

img

STEP 7.2: INSERT THE SESSION ID INTO THE BODY OF THE POST REQUEST USING THE SENDMESSAGE ENDPOINT

This is the JSON format which is used in the POST request sendmessage body in Postman. Now we insert the copied sessionID into the body of the request inside postman.

{ "sendmessage" : {
  "sessionID" : "XXXX",
  "message_type": "text",
  "text": "Hello"
  }
}
Enter fullscreen mode Exit fullscreen mode

img

Now we see the output of the sendmessage request in the expected JSON format.

SUMMARY

The usage of the Watson Assistant API v2 is very easy and good documented, but you need to understand the environment topic. At the moment the documentation talks about the assistantID to pass into an invocation as an example, this can cause a misunderstanding. Here a screen shot of the IBM Cloud documentation “createsession” created on 09.12.2022.

img


I hope this was useful for you and let’s see what’s next?

Greetings,

Thomas

watsonassistant, #nodejs, #ibmcloud, #rest, #javascript

Original blog post on www.suedbroecker.net SIMPLE NODE.JS SERVER EXAMPLE USING THE WATSON ASSISTANT API V2

Top comments (0)