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.

25 Comments

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

  1. Former Member

    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?

    (2) 
    1. Former Member

      Hi Joongwon

      Are you able to resolve the issue? I am also facing the same problem. Please can you let  me know  how can we resolve the issue?

       

       

      Thanks

      Srikanth

      (0) 
        1. Soichiro Nakanishi

          I have the similar issue. Could you let me know how you resolve it ?

          Regards

          Soichiro


          I don’t use proxy.

          So I comment out the followings in “DEST_BOT_ODATA.xshttpdest” ;

           proxyType = http;

           proxyHost = “proxy-trial”;

           proxyPort = 8080;

          Then I face the following error ;

           Execution error: Error: HttpClient.getResponse: Can’t get the response from the server: internal error occurred “Connection to xxxtrial.hanatrial.ondemand.com lost while reading response.”

          Soichiro

           

          (0) 
  2. Former Member

    Hi,

    I have created xsjs service. When running the chatbot by the providing the xsjs url in Fulfillment,adding header parameters  x-csrf-token = unsafe and making the package public, its giving the following error :

    “status”: {
    “code”: 206,
    “errorType”: “partial_content”,
    “errorDetails”: “Webhook call failed. Error: Request timeout.”,
    “webhookTimedOut”: true
    },

    When I run the url independently its giving the output.

    Please provide the solution.

     

     

    (0) 
    1. Santi Rai

      Hi  Former Member,

       

      Is your xsjs script is running? because i am getting this error “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data” as other.

      (0) 
  3. Former Member

    Hi,

    I need your help to integrate dialogflow with the xsjs sap service. My requirement is to get the specific order detail from the xsjs service by passing parameter from the chatbot.

    I am not able to pass the parameter from dialogflow chatbot to sap service. Please help me on this.

     

    (0) 
    1. Santi Rai

       

      Hi  Former Member,

      How did you fixed this error “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”.

      (0) 
  4. Former Member

    Hi,

    Facing same issue “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”. Please help to over come this error.

    Thanks,

    Albert Tigga

    (0) 
  5. Former Member

    Hi,

    I am also facing same issue Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data 

    when executing GetAgentsList.xsjs.

     

    please help.

    (0) 
  6. Former Member

    Hi DId anyone solved this issue?

    I have two patterns of error not sure which is correct one.

    var v_dest  = “DEST_BOT_ODATA”;
    var v_pack  = “ChatBotProject.services”;
    var odestination = $.net.http.readDestination(v_pack, v_dest);

    Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

    or

    var v_dest  = “DEST_BOT_ODATA”;
    var v_pack  = “ChatBotProject.Services”;
    var odestination = $.net.http.readDestination(v_pack, v_dest);

    Execution error: Error: User is not authorized to use destination (package: ChatBotProject.services, name: DEST_BOT_ODATA)

    (0) 
    1. Abhishek Tayal

      See if you have sub-package as “Services” in your HANA editor package than Pattern 1 is correct for you.

      and If “services” than Pattern 2. I will say pattern 1 if you have followed the instructions.

      (0) 
  7. Santi Rai

    Hello,

    Somebody got the solution for this?

    Facing same issue “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”.

    (0) 
  8. manoj thatha

    Hi ,

     

    I have tried the same thing using the odata service of hana system and it works perfect. Only issue while trying the hana database it is not working.

    (0) 
  9. manoj thatha

    I have tried the same thing using the odata service of s4hana on premise system and it works perfect. Only issue while trying the hana database on the cloud it is not working.

    (0) 
  10. Ranjeet Jha

    Has anyone got solution for error message

    “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”

     

    Thanks.

    (0) 
  11. vasu Waddar

    Hello Everyone.

    Those who are getting issue as

    ““Execution error: SyntaxError: JSON.parse: unexpected charact at line 1 column 1 of the JSON data”.

     

    Please  find the below solution

     solution :

    We  need import  HCP Trusted  Certificate(HTTPS)  in SAP HANA XS Administration , since we are calling  destination from XS application we  need  to import  Trusted certificate in SAP HANA XS Administration.

     

    step1 : Launch  SAP HANA XS Administration Page

    https://mdcp1942331530trial.hanatrial.ondemand.com/sap/hana/xs/admin/

     

    Step2 : Download HCP HTPS certificate from URL.

    Step3: Click on XS Administrator Tool –

    Import  downloaded SSL certificate from  HCP .

     

     

     

    Regards

    Prakash  Waddar

     

     

    (0) 
    1. Soichiro Nakanishi

      Hello.

       

      Thank you for precious information.

      I could not find “ChatBot” in “Trust Store”.

      So I have the following other error ;

      Execution error: Error: HttpClient.request: request failed: SSL requested, but no trust store configured

      I need any other configuration ? Where can I do it ?

       

      Regards

      Soichiro Nakanishi

      (0) 
    2. Saritha Koroth

      Hi Prakash,

      I followed the certificate import but still face the same error. Could you please share if there are any additional settings that we need to make?

      Regards,

      SK

      (0) 
  12. Abhishek Tayal

    I have followed all the steps:

    When running xsjs file i face below error:

    “Execution error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data”

    So in order to find root cause i have edited the xsjs file as :

    try {
    var v_dest = “DEST_BOT_ODATA”;
    var v_pack = “ChatBotPackage.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();

    $.response.status = $.net.http.OK;
    $.response.contentType = “application/json”;
    $.response.setBody(JSON.stringify({
    “speech”: odata_Response,
    “displayText”: odata_Response
    }));
    break;
    default:
    $.response.status = $.net.http.METHOD_NOT_ALLOWED;
    $.response.setBody(“Request method not allowed”);

    break;
    }
    }
    catch (e)
    {
    $.response.setBody( odata_Response+”Execution error: ” + e.toString());
    }

    OUTPUT for above contains info like:

    <h1 class=”orange”>An error occurred while handling your request</h1>↵↵ <div class=”line”>↵ <div class=”label”>While trying to retrieve the URL:</div>↵ <div class=”desc”> ↵ <span>http://<HANATRIALACOOUNT&gt;:443/ChatBotPackage/Services/ChatBotSM.xsodata/Agents?$format=json</span>↵ </div>↵ </div>↵↵ <div class=”line”>↵ <div class=”label”>The content could not be delivered due to the following condition:</div>↵ <div class=”desc”> ↵ Connection reset by peer↵ </div>↵

    I also noticed that url changes from HTTPS to HTTP.

    Kindly help.

     

    (0) 
  13. Amit Kumar Barik

    Hi,

    I followed all the steps. Everything is fine but while executing .xsjs file it throwing this below error.

    {

    • ERROR“HttpClient.request: request failed: internal error occurred “Failed to send request to socket…rc = -1″”

    }

    Can anyone help me here..

    Thanks in advance.

    Regards,

    Amit

    (0) 

Leave a Reply