Skip to Content
Technical Articles
Author's profile photo Sharadha Krishnamoorthy

Serverless Extensions – Part 3: Set up SAP Cloud Platform Backend service and connect the APIs to Functions

Serverless Extensions
Part 1 – Introduction and Set up messaging queue in SAP Cloud Platform Enterprise Messaging
Part 2 – Configure SAP Cloud Platform Open Connectors to connect to Whatsapp and Twitter.
Part 3 – Set up SAP Cloud Platform Backend service and connect the APIs to SAP Cloud Platform Functions.
Part 4 – Set up functions in SAP Cloud Platform Functions and connect them to the queues and open connectors 
Part 5 – Bring it all together – Testing the extension end to end.

For our scenario, we will be using the Backend service to store the customers along with their group and contact number. When the promotions are created, WhatsApp messages are sent only for the customers belonging to the group ‘Priority’. When the promotion message is sent to the queue, the ‘Functions’ service calls the Backend service to get the contact numbers of the ‘Priority’ customers and sends the WhatsApp messages.

Set up SAP Cloud Platform Backend Service and Create APIs

Before we can start creating the APIs, we have to enable and configure the SAP Cloud Platform Backend services. There is an amazing blog series written by Carlos Roggan on SAP Cloud platform Backend Service covering almost every detail of it. Please refer this blog to enable and perform the initial configurations required.

Once the intial set up is complete, go to Trial Subaccount -> Subscriptions -> SAP Cloud Platform Backend Service (Beta)

Click ‘Go to Application’

Go to ‘API’ -> Create API.

I already have created a simple CDS file which can be used to create the backend service. It is a simple table and a service to read from the table.

Context customerModel{

  entity customers{
  key CustomerID: String(10);
  CustomerName : String(255);   
  CustomerGroup: String(15);
  ContactNo: String(255); } 
};

service manageCustomers{
 entity customers as projection on customerModel.customers;
};

Enter the details as below and use the .cds file with the content above and click ‘Create API’

Once the API has been created, you will get the screen as below.

The API deployment logs can be checked as well which is available under ‘Actions’.

Click on the API to get the API documentation and try out the APIs. You can see several APIs created to post and read data from the table.

Use the POST API to add some entries to the table. We will be using the GET API of customers to read the contents of the table. Note down the URL for the same. It should be something like this.

https://xxxxxtrial-backend-service.cfapps.eu10.hana.ondemand.com
/odatav4/DEFAULT/CUSTOMERS;v=1/customers

To call the API from Functions service, we perform the following steps

  1. Set up XSUAA authorisations (OAuth) for the backend service in the Cloud Foundry account
  2. Request Authorisation token – from SAP Cloud Platform Functions
  3. Call the API – from SAP Cloud Platform Functions

Configure and set up XSUAA.

1. Go to Subaccount -> Space ->Service Marketplace ->Authorisation and Trust Management.

2. Enter the service and click ‘Instances’ and click ‘Create Instance’.

3. Choose ‘Application’ and click ‘Next’. Enter the JSON below. This attaches the backend service with the authorisation object. The foreign scope reference can be found under ‘Role templates’ of the backend service.

{

 "xsappname": "myAppName",
 "tenant-mode": "dedicated",
 "foreign-scope-references": [
  "Backend-service!t6131.AllAccess"
 ]

}

Click Next in the two screens and enter an instance name on the last screen and click ‘Finish’.

Click on the newly created instance and choose ‘Service keys’. Click ‘Create Service Key’.

Enter a name for the service key and click ‘Save’. This creates the service key. You know what you have to do now. Yes, Save the following fields from the service key and we would need parts of it to get the authorisation token in the following steps.

"clientid": "sb-xxx!t42193",
"clientsecret": "xxxxx",
"URL": "https://xxxxtrial.authentication.eu10.hana.ondemand.com"

Let us go ahead and call the backend service API from Functions. 

Configure SAP Cloud Platform Functions

Navigate to your Global SAP Cloud Platform account and under “Entitlements” menu, allocate units of Functions to your trial subaccount. Within the space in the Cloud Foundry account, You should now be able to see the service listed in the Service Marketplace.

Click on the “Functions” tile and from the Instances menu, create a new instance.

Choose Service Plan as ‘beta’. Click Next.

Enter the following parameter in the next step. You can give any name here.

{
"name": "function-promotions"
}

Click Next on this step and the next step. Complete the instance creation by providing a name for your function.

Click Finish. You should now be able to see the newly created instance.

For some reason, the dashboard (under Actions) is not accessible from this screen and it gives an error. I was able to access the Functions dashboard by navigating to the sub-account -> Subscriptions -> Functions -> Go to Application. This opens the dashboard.

In case you face any authorisation issues, assign the roles ‘ManageRole’, ‘ReadRole’ through ‘Role Collections’.

Now we are ready to create a function to call the backend service API.

Go to Functions Dashboard. Click Functions -> Create Function.

Write a simple node.js handler function to call the API. We call the API in two steps.

  1. Get Authorisation token from XSUAA
  2. Call the backend service API using the token.

Notice the change in URL.Your API-URL is shown in the cockpit as follows:

https://xxxxxtrial-backend-service.cfapps.eu10.hana.ondemand.com/odatav4/DEFAULT/CUSTOMERS;v=1/customers

However, for external call, the URL has different prefix:

https://backend-service-api.cfapps.xx.hana.ondemand.com/odatav4/DEFAULT/CUSTOMERS;v=1/customers

 

const request = require('request');

var https = require('https');

module.exports = { 
 handler: function (event, context) { 
//get access token - Use the URL, client id and client secret from the servicekey of XSUAA
request({
  url: 'https://xxxxxtrial.authentication.eu10.hana.ondemand.com/oauth/token?grant_type=password&username=<<yourcloudaccountemail>>&password=<yourcloudaccountpassword>',
  method: 'GET',
  headers:{
     Authorization: 'Basic <<Base64 encoded clientid:clientsecret>>'
  }
 }, function(err, res) {
  var json = JSON.parse(res.body);
  console.log("Access Token:", json.access_token);
  //on success call the api
  var url = 'https://backend-service-api.cfapps.eu10.hana.ondemand.com/odatav4/DEFAULT/CUSTOMERS;v=1/customers?filter=CustomerGroup eq Priority&select=ContactNo'
  console.log("URL "+url);
  request({
  url: url,
  method: 'GET',
  headers:{
     Authorization: 'Bearer '+ json.access_token
  }

 }, function(err, res) {
  var json = JSON.parse(res.body);
    console.log("API result:", json);
    console.log("API value:", json.value[0]);
  console.log("API contact:", json.value[0].ContactNo);
  return json.value[0].ContactNo;
 });
});
 } 
 }

If you want more details about calling the backend service APIs securely from external applications, refer to this blog

We can create an HTTP trigger and test this function. Go to dashboard -> Triggers -> Create Trigger. Enter a trigger name.

Click next on step 2.

Review and create the trigger.

Go to the function, open triggers and click the icon shown below.

 

Choose the trigger URL.

Open the URL in a browser. You will just see a blank screen. It is all ok.

Go to Function Dashboard ->click logs -> choose the instance and Function. You will see the output of the console statement in the node JS function. It will display the customers with the customer group set as ‘priority’.

We have now connected the backend and the Functions service. In the next blog, we will connect the Functions service with the messaging queues and open connectors.

Assigned tags

      1 Comment
      You must be Logged on to comment or reply to a post.
      Author's profile photo Akhthaar Ali Badhusha
      Akhthaar Ali Badhusha

      Hi Sharadha Krishnamoorthy  can you please explain the same for POSTing json payload to cloudplatform-backend-service using Nodejs.

      Thanks,

      Badhusha.