Skip to Content

Next article Here

1 – Introduction


Recently i worked on one of the HYPE topic of the moment called ChatBot or interactive agent.

So i decided to realise this serie of posts, to share this experience by using a practical end-to-end scenario.

I will use SAP Cloud Platform and especially HANA MDC as Back-End technology that expose data through an HTTP REST service.

Using a chatbot tool that will consume this service and integrate it with FaceBook Messenger.

The article will be divided in 3 parts :

  1. Back-End development.
  2. Using DialogFlow tool to create an Agent and consume the Back REST API.
  3. Integrating the Agent with FaceBook Messenger.

So let’s start.

2 – Back-End – REST API & Odata Service creation 


To follow this article you need to create an SAP Cloud Platform Trial Account.

Go to https://account.hanatrial.ondemand.com/

Open your SAP Cloud Platform Cockpit and navigate to Databases & Schemas

Choose your MDC Database

Open Editor link to access SAP HANA Web-based Development Workbench

2.1 – Back-End Project development

In this step you can choose what ever technology you want, an SAP ECC on-premise system or a Third party system. In my case and to be the most generic possible for my article i choose an MDC HANA XS in the Cloud because is free of charge.

Right-click on the root level of your IDE and choose New -> Package

Choose Project Name

Create two sub packages data and services inside your new created project. After that right-click on your project and choose New -> Create Application

A pop-up wll appear choose Empty application and click Create button

Delete index.html generated after this step. The final project would look like

The use case will be very simple. I will create an OData service that expose Sales representante informations.

2.1.1 – Content of data Package :

Right-Click on data Packge and choose New -> File.  Enter SCHATBOTSM.hdbschema as name

SCHATBOTSM.hdbschema source code

schema_name="SCHATBOTSM";

Right-Click on data Packge and choose New -> File. Enter chatbotsm.hdbdd as name

chatbotsm.hdbdd source code

namespace ChatBotProject.data;

@Schema: 'SCHATBOTSM' 

context chatbotsm 
{ 
    type CString    : String(5); 
    type SString    : String(40); 
    
    type tt_error 
    { 
        HTTP_STATUS_CODE: Integer; 
        ERROR_MESSAGE: String(100); 
        DETAIL: String(200); 
    }; 

    @Catalog.tableType : #COLUMN 
    Entity Agent 
    {  
        KEY AGENT_ID: CString;
            FIRST_NAME: SString;
            LAST_NAME: SString; 
    };
};

2.1.2 – Content of services Package :

Right-Click on data Packge and choose New -> File.  Enter ChatBotSM.xsodata as name

ChatBotSM.xsodata source code

service namespace "ChatBotProject.services.ChatBotSM" 
{ 
    "ChatBotProject.data::chatbotsm.Agent" as "Agents";
}

 

2.2 – Back-End Administration Task

Log in as SYSTEM user on https://mdcpXXXXXXtrial.hanatrial.ondemand.com/sap/hana/ide/ and open Security link.

Create new Role and call it R_CHAT_BOT_SM. Open the Object Privileges tab and add the Schema created before in XS Project.

Don’t forget to Save those modifications.

Assign this role to your development user. Select your development user under Users node and open the tab Granted Roles and add the R_CHAT_BOT_SM created previously and click Save button.

2.3 – Back-End Test OData Service

Back to the XS Project and Launch Open OData Explorer of ChatBotSM.xsodata

Select Agents Entity and click Generate Data button.

Again from the XS Project select ChatBotSM.xsodata file from project structure and click run button.

The metadata content of the OData service is shown as below. The service contains one Entity “Agents”.

To display Agents Entity values change the URL on your Browser ( Chrome in my case ) as below

https://mdcpXXXXXXtrial.hanatrial.ondemand.com/ChatBotProject/services/ChatBotSM.xsodata/Agents

If all is done correctly the generated data will be displayed

2.4 – Back-End REST API

The exercise will be so easy if i consume my OData directly from the external side. So to add some tricky stuff i will add an XSJS file that consume the ChatBotSM.xsodata service and apply some logic to transform the OData result.

2.4.1 –  Create an HTTP Destination 

Right-click on services node and choose New -> File. Choose DEST_BOT_ODATA.xshttpdest as name.

DEST_BOT_ODATA.xshttpdest would look like

2.4.1 –  Create XSJS Script

Create new file under services node. Choose GetAgentsList.xsjs as name

GetAgentsList.xsjs source code

try {
       var v_dest  = "DEST_BOT_ODATA";
       var v_pack  = "ChatBotProject.services";
       var v_query  = "/Agents?$format=json";
    switch ($.request.method) 
    {
        case $.net.http.GET:
        case $.net.http.POST:
        case $.net.http.PUT:
          //Reading the destination properties
          var odestination = $.net.http.readDestination(v_pack, v_dest);
          //Creating HTTP Client
          var oclient = new $.net.http.Client();
          //Creating Request
          var orequest = new $.web.WebRequest($.net.http.GET, v_query);
          //Add Header param
          orequest.contentType = "application/json";
          //Call the OData service
          oclient.request(orequest, odestination);
          //Receiving OData service response
          var odata_Response = oclient.getResponse().body.asString();
          
          var JSONObj = JSON.parse(odata_Response);
          var botResponse;
     
          if (JSONObj.d.results.length > 0) 
          {
            botResponse = "Agents List: ";
            for (var i = 0; i < JSONObj.d.results.length; i++) 
            {
              botResponse += " ";
              // Concatenate First & Last Agents names
              botResponse += JSONObj.d.results[i].FIRST_NAME 
                              + JSONObj.d.results[i].LAST_NAME;
            }
          } 
          else 
          {
            botResponse = "No data Found";
          }
     
        $.response.status = $.net.http.OK;
        $.response.contentType = "application/json";
        $.response.setBody(JSON.stringify({
          "speech": botResponse,
          "displayText": botResponse
        }));
        break;
      default:
        $.response.status = $.net.http.METHOD_NOT_ALLOWED;
        $.response.setBody("Request method not allowed");
     
        break;
      }
} 
catch (e) 
{
    $.response.setBody("Execution error: " + e.toString());
}

Select GetAgentsList.xsjs and click run button.

The result is shown as bellow

Our XSJS require an authentication login/password. Launch the XS Admin tools as SYSTEM user to set No Authentication Required option like this for our Package. Save your configuration.

Open a new private Chrome window and put the url below

https://mdcpXXXXXXtrial.hanatrial.ondemand.com/ChatBotProject/services/GetAgentsList.xsjs

The call is working without asking for Login/Password. Great!!! The first step is done and in the next post i will explain how to consume this HTTP REST ( XSJS script ) by a ChaBot Tool.

Next article Here

 

To report this post you need to login first.

1 Comment

You must be Logged on to comment or reply to a post.

  1. Joongwon Chung

    Hi,

    when I tried to run GetAgentsList.xsjs, there is a syntax error “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.”.

    I think I followed step-by-step without any problem, could you recommend where should I check to solve this error?

    (0) 

Leave a Reply