More information about the SAP Cloud Application Programming ModelWelcome to CAP

In this tutorial we will develop and deploy a CAP Node.js Service with simple functions and create an Action Project.The goal is to cover all the necessary steps to consume the CAP Service API functions in a Process, not to proivde a real use case.

Finally we will build and execute a process which combines simple no-code actions for a ToDo service and a CAP service API.

This is part of a blog series for Actions:
SAP Process Automation – Consume APIs with <no-code> using Actions.

Actions – High Level Architecture

We introduced the Action concept to simplify the experience for Citizen Developers to consume APIs without coding (no-code). Here an high level overview of the architecture.

Tutorial steps

Detailed information for CAP Business Service and Action Editor, the consumption should be known from other tutorials (Your first simple Action Project: End to End) and will be covered only high level.

 

Prerequisites

  • Subscribe to SAP Business Application Studio in addtion to SAP Build Process Automation
  • Create a Space if you don’t have one already
  • Make sure your user has a Space Developer Role

SAP Business Application Studio

Develop Node.js Service

  • Click Create Dev Space
  • Define name demo and select kind Low-Code-Based…, click Create Dev Space

  • The Dev Space is created and starting, when the status is running click demo to open
  • Application Studio will open and initialize, this will take some time
  • We will not create a project using the wizard, click cancel
  • Close the Home tab, click x
  • Create a New Project from Template using the File menu
  • From the templates, select CAP Project and click Start
  • Enter name sap-build-cap-sample-library and select feature MTA based…, click Finish
    runtime Node.js is already selected
  • Guided Development and Home tab will be displayed, as we don’t use them, close both tabs
  • From the Project Explorer we will change to the Explorer View, click View -> Explorer
  • the Explorer will show all files of your project
  • open the mty.yaml file with a text editor, to check the content, right-click on the file, select Open With…, select Editor click on Text Editor default

  • in the Explorer, click on folder srv and click New File icon
  • use file name service.cds, press Enter and the empty file editor will open
  • create another file in the same folder, use file name service.js
  • select the file service.cds and copy the following code into the editor
     

    @Capabilities.BatchSupported : false
    
    service sap_build_cap_sample_library @(path : '/api/v1') {
      
      define type DataString {
        value : String;
      }
    
      define type DataInteger {
        value : Integer;
      }
      
      define type DataNumber {
        value : Double;
      }
    
      define type DataList {
          id : Integer;
          title: String;
          userId: Integer;
          completed: Boolean;
      }
    
      @Core.Description : 'toInteger'
      function toInteger(value : String) returns DataInteger;
    
      @Core.Description : 'toNumber'
      function toNumber(value : String) returns DataNumber;
    
      @Core.Description : 'toString'
      function toStr(value : Double) returns DataString;
    
      @Core.Description : 'addQuotes'
      function addQuotes(value : String) returns DataString;
    
      @Core.Description : 'listToString'
      action listToString(responseArray : array of DataList, field : String) returns DataString;
    
    }
  • select the file service.js and copy the following code into the editor
     

    module.exports = srv => {
    
        srv.on('toInteger', req => {
            const {value} = req.data;
    
            return { 'value' : parseInt(value) };
        });
    
        srv.on('toNumber', req => {
            const {value} = req.data;
    
            return { 'value' : parseFloat(value) };
        });
    
        srv.on('toStr', req => {
            const {value} = req.data;
    
            return { 'value' : value.toString() };
        });
    
        srv.on('addQuotes', req => {
            const {value} = req.data;
    
            return { 'value' : "'" + value + "'"};
        });
        
        srv.on('listToString', req => {
    
            var values = req.data.responseArray;
            var resultList = [];
            var field = req.data.field;
            if (values) {
                for (var i = 0; i < values.length; i++) {
                    resultList.push(values[i][field]);
                }
            }
    
            return { value : resultList.toString() };
        });
    }
  • Now you can use a Terminal to test the service already, click New Terminal
  • Terminal window will open, enter command cds watch
    the service is locally build and can be tested
  • to easily test the service, select the folder sap-build-cap-sample-library and click New File icon, use file name test.http
  • select the file test.http and copy the following code into the editor
     

    ###
    #
    # call toInteger
    #
    GET http://localhost:4004/api/v1/toInteger(value='20')
    
    ###
    #
    # call toNumber
    #
    GET http://localhost:4004/api/v1/toNumber(value='20.2')
    
    ###
    #
    # call toString
    #
    GET http://localhost:4004/api/v1/toStr(value=20.2)
    
    ###
    #
    # call addQoutes
    #
    GET http://localhost:4004/api/v1/addQuotes(value='abcd')
    
    ###
    #
    # call listToString
    #
    POST http://localhost:4004/api/v1/listToString
    Content-Type: application/json
    
    {
        "field" : "id",
        "responseArray": [
            {
                "id": 1,
                "title": "delectus aut autem",
                "userId": 1,
                "completed": false
            },
            {
                "id": 2,
                "title": "quis ut nam facilis et officia qui",
                "userId": 1,
                "completed": false
            }
        ]
    }     
  • To test a request, you can just click on Send Request in the file and you will see the response in a separate window

Deploy Service to BTP

We will use a script to build and deploy the service.

  • select the folder sap-build-cap-sample-library and click New File icon, use file name script.sh
  • select the file script.sh and copy the following code into the editor
     

    # set API endpoint and login to Cloud Foundry
    cf api https://api.cf.us10-001.hana.ondemand.com
    cf login
    # some needed npm settings
    npm update --package-lock-only
    npm set registry=https://registry.npmjs.org/
    # build the service locally
    mbt build -t gen --mtar mta.tar
    # deploy the service to the BTP space
    cf deploy gen/mta.tar
    # generate the openAPI spec for the service, used to create the Action project
    cds compile srv --service all -o docs --to openapi
  • execute the script in the terminal, enter command bash script.sh

  • when asked, enter your Email and Password
  • during the execution of the script, the terminal will show informations for each step
  • login
  • build
  • deploy
  • generated openAPI spec
  • after the script execution, check in the BTP Cockpit, if the service is running

 

Generate OpenAPI spec

The openAPI spec was generated as part of the script in the previous step.This definition will be used to create the Action Project in SAP Build and needs some manual changes.

  • open the filesap_build_cap_sample_library.openapi3.json in the editor
  • the following “paths” definitions must be updated with missing quotes (just replace the lines in the generated file)
        "/toInteger(value='{value}')": {
        "/toNumber(value='{value}')": {
        "/addQuotes(value='{value}')": {
  • some “responses” / “schema ” definitions must also be updated,
    Note: this will not be necassary in future versions of the Action Editor.
  • just replace the lines in the generated file
    “/toInteger(value='{value}’)”: {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                          "$ref": "#/components/schemas/sap_build_cap_sample_library.DataInteger"
                    }
                  }
                }
              },
              "4XX": {
  • “/toNumber(value='{value}’)”: {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                          "$ref": "#/components/schemas/sap_build_cap_sample_library.DataNumber"
                    }
                  }
                }
              },
              "4XX": {
  • use the same definition for the following areas:
    “/toStr(value={value})”: {
    “/addQuotes(value='{value}’)”: {
    “/listToString”: {
              "200": {
                "description": "Success",
                "content": {
                  "application/json": {
                    "schema": {
                          "$ref": "#/components/schemas/sap_build_cap_sample_library.DataString"
                    }
                  }
                }
              },
              "4XX": {
  • after changing the definitions, select the file content (Ctrl-a) in the editor and copy (Ctrl-c)
  • create a new file in a local folder of your desktop (e.g. demo.json), open the file, paste the content and save the file (we will use the file later to create the Action Project)

BTP Cockpit

Create Destination

In the SAP BTP Cockpit, create a destination that will be used in the Action Editor to test the Action and in the Process execution.

  • Get the Application Routes URL from the service, click on the Name
  • Copy the URL to use it later in the Destination definition
  • Create the Destination
    Name: Demo_CAP_Sample_Library
    URL:  <Application Routes url>/api/v1
    Additional properties: sap.applicationdevelopment.actions.enabled = true
    Additional properties: sap.processautomation.enabled = true

SAP Build Process Automation

Action Editor

From the Lobby of SAP Build, create an Action Project

  • Select Create, select Build an Automated Process
  • Select Actions
  • Specify the name CAP Sample Actions and upload the API spec demo.json, click Create
    (Note: demo.json was created in section Generate OpenAPI spec)
  • Select the actions from the list, click Add
  • Your Action Project will contain the actions for the CAP service

Test Actions

You can test the execution of your action in the Action Editor. Lets test the Action listToString

  • Select listToString from the list, the action has input parameters field and values
  • Select Tab Test, we will use the Destination for the test and define the Input Values
    field: id
    values: id: 1, title: task1

In the Test you can specify only one value for a list. In the Response View you can see that the values are converted to a string (with more than one value they will be comma separated).
You can also try title as field and check the result.

Lets test the execution of some other actions.

  • toInteger
  • toNumber
  • addQuotes

Release and Publish to the Library

To be able to use the Actions in a Process, we have to release and publish the Action Project.

  • Click Release
  • Provide release information, click Release
  • Click Publish to Library
  • On Publish Project, click Publish

Consumption in Process

If you just want to use simple Actions like toInteger, toString or addQuotes in your process you do not need the ToDo Action and you can ignore what is explained in Prerequisite.

Prerequisite:
for using the listToString Action in your process is the Action Project for ToDos, which is explained and created in the tutorial Walkthrough all steps using a simple REST API SAP Process Automation – Your first simple Action Project: End to End.
Note: Make sure to update the Action Project for ToDos with the latest OpenAPI spec available in the Walkthrough blog. There was a small but important change needed to get the sample process of this tutorial working.

Now lets look into the steps to use the listToString Action in your process.

Configure Destination for SAP Process Automation

To allow the usage of the BTP destination, you have to add the Destination in SAP Build Process Automation.

  • In the Settings or SAP Build Process Automation, select Destinations
  • Click New Destination
    select the Destination from the list and press Add
  • The destination is now added to the list and can be used

Create Business Process and use an Action

  • From the Lobby select Create
  • Select Build an Automated Process, on next screen select Business Process
  • Enter Project Name CAP Sample and click Create
  • On the Create Process Dialog, enter the Process Name myCAPsample and select Create, the canvas will be shown
  • Select the + to add a step to your process
  • From the Browse Library add the actions get list of todos and listToString
  • create Destination variables todoService and capService

  • Configure Process Details – Inputs, define Input field and click Apply
    (click on the canvas to display the Process Details)
  • Define the Inputs for listToString, for input field select field from Process Start Inputs
  • for Input tasks select list – responseArray from get list of todos
    Note: if list – responseArray cannot be selected, you may not have updated the ToDo Action Project with the latest openAPI spec and released/published to the library ?!
  • definition of Inputs for listToString should look like
  • Save, Release and Deploy
  • on the Deploy a project dialog select the Destinations for variables capService and todoService, click Confirm

  • Click on Deploy

Test the Process

  • On Monitor,select Manage –> Process and Workflow Definitions, click on myCAPSample
  • click Start New Instance, on Start New Instance dialog specify the input paramer
    { "field" : "id" }

  • click Start New Instance and Close
  • Select Monitor -> Process and Workflow Instances, clear all filters to make sure your instance is in the list
  • clck on line to display the details of the instance
    the result of the action listToString is shown as comma separated value string

Conclusion

Following this tutorial, you have seen all the steps to create a simple CAP Service and to consume the service in a process using Actions.

 

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x