SIMPLE NODE.JS SERVER EXAMPLE USING THE WATSON ASSISTANT API V2
Tags: watsonassistant, node, rest, javascript
Published: 2023-01-08 11:13:50

---
title: SIMPLE NODE.JS SERVER EXAMPLE USING THE WATSON ASSISTANT API V2
published: true
description: This blog post is about a simple example to use the [Watson Assistant API v2](https://cloud.ibm.com/apidocs/assistant/assistant-v2) with the [Node.js SDK](https://github.com/watson-developer-cloud/node-sdk) to get a [Watson Assistant](https://cloud.ibm.com/catalog/services/watson-assistant#about) sessionID and send a message to [Watson Assistant](https://cloud.ibm.com/catalog/services/watson-assistant#about) using this sessionID. Here is the GitHub project **[watson-assistant-simple-node-js-server-example](https://github.com/thomassuedbroecker/watson-assistant-simple-node-js-server-example)**.
tags: #watsonassistant #nodejs #rest #javascript
# cover_image: https://suedbroecker.files.wordpress.com/2022/12/assistant-simple-nodejs-server.png
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-08 11:06 +0000
---

This blog post is about a simple example to use the [Watson Assistant API v2](https://cloud.ibm.com/apidocs/assistant/assistant-v2) with the [Node.js SDK](https://github.com/watson-developer-cloud/node-sdk) to get a [Watson Assistant](https://cloud.ibm.com/catalog/services/watson-assistant#about) sessionID and send a message to [Watson Assistant](https://cloud.ibm.com/catalog/services/watson-assistant#about) using this sessionID. Here is the GitHub project **[watson-assistant-simple-node-js-server-example](https://github.com/thomassuedbroecker/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](https://cloud.ibm.com/apidocs/assistant/assistant-v2) methods. The simple Node.js server has implemented following REST endpoints :

- [`GET` getsession (which creates a new `sessionID`)](https://github.com/thomassuedbroecker/watson-assistant-simple-node-js-server-example/blob/main/code/simple-server/server.js#L37)
- [`POST` sendmessage](https://github.com/thomassuedbroecker/watson-assistant-simple-node-js-server-example/blob/main/code/simple-server/server.js#L64)

> The project contains examples for using [Postman](https://www.postman.com/downloads/). ![😉](https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f609.svg)



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](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-07.png?w=731)

> The GitHub project also contains a [bash script to list the environments using cRUL](https://github.com/thomassuedbroecker/watson-assistant-simple-node-js-server-example/blob/main/code/assistant-get-environment-ids.sh).

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

```json
{"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,
      ...
}

```

The relevant code in[ **server.js**](https://github.com/thomassuedbroecker/watson-assistant-simple-node-js-server-example/blob/main/code/simple-server/server.js#L28) file to connect to the right environment of the Watson Assistant service.

```javascript
const assistant = new AssistantV2({
    version: e_version,
    authenticator: new IamAuthenticator({
      apikey: e_apikey,
    }),
    serviceUrl: e_serverUrl,
  });
```

## 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](https://cloud.ibm.com/apidocs/assistant/assistant-v2) documentation for the Node.js SDK in the implementation of our REST endpoint.

```javascript
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();
    });  
});

```

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

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-08-1.png?w=701)



## 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

```bash
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
```

### 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.](https://cloud.ibm.com/apidocs/assistant/assistant-v2#createsession) (Contains the Link to the IBM Cloud documentation)

The image below shows the `environment ID` in the [IBM Cloud UI](https://cloud.ibm.com/resources).

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-01.png?w=1024)

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](https://cloud.ibm.com/resources).

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-02.png?w=1024)

- Create an `.env` file

```bash
cat .env-template > .env
```

- Configure the `.env` file to your needs

```bash
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'
```

### STEP 3: RUN LOCAL ON PORT 3010

```
npm install
npm start
```

### STEP 4: OPEN BROWSER AND INVOKE THE GET SESSION ENDPOINT

It returns the newly created `sessionID`.

```bash
open http://localhost:3010/getsession
```

- Example output:

```json
{
"session_id": "37d13c72-1643-4add-bee5-574c6fd062dc"
}
```

### STEP 5: IMPORT THE POSTMAN COLLECTION INTO POSTMAN

The images shows the import button in postman.

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-03.png?w=1024)



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](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-04.png?w=656)

### 

### STEP 7: SEND A MESSAGE

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

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-08-1.png?w=701)

### 

### 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](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-05.png?w=678)

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

```bash
{ "sendmessage" : {
  "sessionID" : "XXXX",
  "message_type": "text",
  "text": "Hello"
  }
}
```

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-06.png?w=694)



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

## SUMMARY

The usage of the [Watson Assistant API v2](https://cloud.ibm.com/apidocs/assistant/assistant-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”](https://cloud.ibm.com/apidocs/assistant/assistant-v2?code=node#createsession) created on 09.12.2022.

![img](https://suedbroecker.files.wordpress.com/2022/12/watson-assistant-09.png?w=1024)


------

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](https://suedbroecker.net/2022/12/09/simple-node-js-server-example-for-using-the-watson-assistant-api-v2/)