Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
In this blog post I will show you how to receive data from the SAP Business Technology Platform REST API (Cloud Management Tool - Feature Set B) in the environment of the SAP Business Application Studio. Therefore, I will create a SAPUI5 application, describe the steps to call the REST API correctly and show you how to display the received data in a simple SAPUI5 TableView.

To perform the following steps, you need to know how to use the APIs provided for SAP Business Technology Platform. For further information please have a look into following materials:

Blog: Introducing Cloud Management Tools – CLI and APIs for SAP Cloud Platform (PART 2)

SAP Help Portal: Cloud Management Tools — Feature Set Overview

SAP Help Portal: Account Administration Using APIs

API Business Hub: Core Services for SAP BTP

This blog post will focus on receiving and displaying cost and usage data. Therefore, I will use the Resource Consumption service which provides REST APIs to help generating reports based on the resource and cost consumption within your accounts. In detail I will send a GET request to receive all monthly cost and usage data for all Subaccounts in the timeframe: January 2021 - September 2021.

GET  [...]/reports/v1/monthlySubaccountsCost?fromDate=202101&toDate=202109

An architecture of the application we will create in this blog can be found below. There you can see how the overall configuration of the application looks like in the SAP Business Application Studio and which services are available in connection with the SAP Business Technology Platform REST APIs. As I mentioned before, in this blog post I will focus on receiving data from the Resource Consumption service, but as you can see in the architecture, it is also possible to connect to other REST APIs provided for SAP Business Technology Platform.

For more information, please have a look into the API Business Hub.


In the end the finished app should be looking something like this:



Prerequisites



  • You have already created a Subaccount in a Global Account (ensure you are using Cloud Management Tools - Feature Set B) - Also possible for Trial accounts.

  • You have enabled Cloud Foundry Environment in the Subaccount.

  • You have created a Cloud Foundry Space.

  • You have entitled SAP Business Application Studio service and subscribed to it.

  • You have created a Dev Space for SAP Fiori inside the SAP Business Application Studio.

  • You have entered the created Dev Space.


If you have ensured that all the prerequisites are in place you can begin to develop the app and connect to the REST API. In the next section I will describe how to set up the SAPUI5 app by using already existing templates in SAP Business Application Studio.

Creating a SAPUI5 application from a template



  1. From the “Welcome” page navigate to “Start from template”

  2. Create a “Basic Multitarget Application”

    • Select the tile “Basic Multitarget Application”

    • Find a project name

    • Select button “Finish”



  3. After the app was created successfully find the “mta.yaml” file

  4. Do a right click on the “mta.yaml” file and select “Create MTA Module from Template”

  5. Create an “Approuter Configuration”

    • Select the tile “Approuter Configuration”

    • Choose the HTML5 Application Runtime “Standalone Approuter”

    • CAUTION: Please pay attention to select the correct approuter. The described steps will not work with the “Managed Approuter”!

    • Select “Yes” to decide that you want to add an authentication and that you plan to add an UI

    • Click “Next”



  6. Wait until the approuter is created successfully

  7. From the “Welcome” page navigate to “Start from template”

  8. Create a “SAP Fiori application”

    • Select the tile “SAP Fiori application”

    • Select Application Type “SAPUI5 freestyle”

    • Choose Floorplan “SAPUI5 Application” and click “Next”

    • Select Data Source “None”

    • Find a view name

    • Find a project name, an application title and an application namespace

    • Choose as folder path the folder of your created "Basic Multitarget Application"

    • Select “Yes” as deployment configuration

    • Keep the default selection of the radio buttons for “FLP configuration” (No) and “Advanced options” (No) and click “Next”

    • Choose “Cloud Foundry” as target

    • Select Destination “None” and click “Finish”




It can take some time until your project was created successfully. A message toast indicates that the creation of all files is finished.


Now the app should be set up completely and the folder structure should look similar to the structure seen in this screenshot:


In the next section I will show you which code snippets you have to add to the corresponding files to receive the data from the REST API.

Tipp: To beautify your code and therefore getting a better overview, please have a look into following blog: SAP Business Application Studio – How to beautify xml and javascript code

Calling the REST API in the SAPUI5 application


In the following screenshot I have marked the files which will be adjusted in the next steps.


 

Change file “index.html”


Change the source (src) to following:



src=https://sapui5.hana.ondemand.com/resources/sap-ui-core.js​

 

Change file “manifest.json”


Add the following code snippet into the “sap.app” section:


First you need to add a comma after "ach": "ach" and secondly you can paste following code snippet below that:
"dataSources": {
"mainService": {
"uri": "reporting/reports/v1/monthlySubaccountsCost?fromDate=202101&toDate=202109",
"type": "JSON"
}
}

The result should look like this:


Add the following code snippet into the “models” section:


First you need to add a comma after the second closing curly bracket and secondly you can paste the following code snippet below that:
"reporting": {
"type": "sap.ui.model.json.JSONModel",
"dataSource": "mainService",
"settings": {
"defaultBindingMode": "TwoWay",
"defaultCountMode": "Inline",
"refreshAfterChange": false
}
}

The result should look like this:


 

Change file “xs-app.json”


Delete the automatically generated first two routes:


Add the following code snippet as a new route to the file:
{
"source": "^/reporting/(.*)$",
"target": "$1",
"service": "com.sap.cloud.udm",
"endpoint":"reporting",
"csrfProtection": false,
"authenticationType": "xsuaa"
},

The result should look like this:


 

Change file “mta.yaml”


Add the following code snippet into the "modules --> requires" section:
- name: udm-resource
parameters:
config:
udm-config-key: "isAppRouter"

The result should look like this:


CAUTION: The line inserts must be according to the code snippet to prevent errors. Be aware that the “udm-resource” is red underlined until the next code snippet is added to the “resources” section (see next step).

Add the following code snippet into the "resources" section:
- name: udm-resource
type: org.cloudfoundry.managed-service
parameters:
service: uas
service-plan: reporting-ga-admin

The result should look like this:


CAUTION: The line inserts must be according to the code snippet to prevent errors.

Now all files are adjusted correctly, and it is possible to receive the data from the API. In the next step I will describe how to display the data from the “Subaccount Cost” API in a simple TableView.

Displaying the received data in a simple UI


To display the data in a TableView we need to change the files marked in the following screenshot.


Tipp: To beautify your code and therefore getting a better overview, please have a look into following blog: SAP Business Application Studio – How to beautify xml and javascript code

Change the title of the app (Optional)


Change the title of the app in the file “i18n.properties” (for e.g., the name of the Global Account of which you are receiving and displaying the data). This step is optional, but it improves the clarity of the app.

Add a table to your view file - “<ViewName>.view.xml”


Replace the “content” item with following code snippet:



<content>
<Table id="table1" items="{path: 'DataModel>/content'}" class="sapUiSizeCompact">
<columns>
<Column>
<Label text="Subaccount"/>
</Column>
<Column>
<Label text="Date"/>
</Column>
<Column>
<Label text="Service"/>
</Column>
<Column>
<Label text="Usage"/>
</Column>
<Column>
<Label text="Metric"/>
</Column>
<Column>
<Label text="Cost"/>
</Column>
<Column>
<Label text="Currency"/>
</Column>
</columns>
<ColumnListItem>
<Text text="{DataModel>subaccountName}"/>
<Text text="{DataModel>reportYearMonth}"/>
<Text text="{DataModel>serviceName}"/>
<Text text="{DataModel>usage}"/>
<Text text="{DataModel>metricName}"/>
<Text text="{DataModel>cost}"/>
<Text text="{DataModel>currency}"/>
</ColumnListItem>
</Table>
</content>

The result should look like this:


 

Add functions to your controller file - “<ControllerName>.controller.json”


Paste the following code snippet into the “onInit” function:
var dataModel = this.getOwnerComponent().getModel("reporting");
this.getView().setModel(dataModel, "DataModel");

The result should look like this:


Now all the components for the UI are defined and you are ready to build, deploy and start the app.

Building and deploying the app


Building the app


Do a right click on the “mta.yaml” file and select the option “Build MTA Project“.

Deploying the app


After successfully building the mta project a new folder “mta_archives” with a “.mtar” file is created.


Do a right click on the “.mtar” file and select the option “Deploy MTA Archive” to start the deployment.

It can be necessary to provide your Cloud Foundry endpoint, your SAP credentials and the organization and the space where you want to deploy your app!

The information “Process Finished” indicates that the deployment was successful (this can take some moments).

Starting the app in the SAP Business Technology Platform Cockpit


Enter your cockpit and navigate to the section “Spaces” under “Cloud Foundry”. Here you get an overview over the spaces you have created. Select the space, where you have deployed your app.


In the space you see all your deployed apps. Select the app you have just created.


After you have entered the overview page of your deployed app, first you need to make sure if the app is already started. The badge in the left corner will show you this information. If the badge is green and the text “started” can be seen, everything works fine. Otherwise please click on the button “start” to start the application manually.

To enter the app you have to select the provided URL in the "Application Routes" section.


 

Now everything should work fine and you should see the data from the “Subaccount Cost” API in the constructed table.



Conclusion


A short recap, what have we achieved?

With the described steps in this blog post we are able to create a SAPUI5 application from a template in SAP Business Application Studio, with some code adaption we can connect a SAP Business Technology REST API to the app and display the received data in a TableView, we manage to build and deploy the developed app and in the end we can see the data after starting the finished app from the SAP Business Technology Platform cockpit.
14 Comments
LuizGomes
Participant

Congratulations on the content, I was looking for it for days. It was very punctual and assertive.

 

LuizGomes
Participant
anett-richel

Could you publish how json is available on the endpoint?

I have been trying to connect to another REST API but without success. it seems that UI5 is not ready to connect to REST APIs. So what magic did you do?

It is possible to consume data from an API such as https://pokeapi.co/?
0 Kudos

Hi 015454888556565665685989

as I have shown in the architecture in this blog post I have used the "Usage Data Management" service in the cockpit to connect to the REST API. Here it is described how to set up the service instance and how to create a service key. In the created service key the information regarding the endpoint, clientID and clientSecret of the REST API is stored.

Regarding your question how to consume an open REST API like https://pokeapi.co/:

I have found a similar question on our SAP Community page, maybe this helps you with your problem: SAP Business Application Studio - Multiple REST API

Best regards, Anett

LuizGomes
Participant
0 Kudos
thanks for answering

but see what we have in issues is an ajax call, this way we lose the direct ui5 components bind with the datasource.

another problem is the lack of a $metadata in the pokemon api

to be viable I need the ui5 behavior to be identical when it is consuming an api with odata.
srinureddy
Explorer
0 Kudos
Hi Anett Richel,

 

Congratulations @anett-richel and Thanks for Publish this Blog.

I have a doubt in(Environment Configuration ) API test. Could you please guide me on how to configure the Environment and test the API in API HUB.

 


Thanks,

Srinivasa Reddy
ramuknura1395
Explorer
0 Kudos
Hi  anett-richel

Thanks to this blog, I have followed the steps and it is working but one query on uri side.

 
"dataSources": {
"mainService": {
"uri": "reporting/reports/v1/monthlySubaccountsCost?fromDate=202101&toDate=202109",
"type": "JSON"
}
}

As per the image above :

You have set the uri manually hardcoded. But in our case it is dynamic one like user selects the date range based on that we have to read data from API. ( Filter dynamically )

Can you please tell me how to achieve that ?
I want to read that values in my controller level.

 

Regards,

Arun Kumar
ramuknura1395
Explorer
0 Kudos
Hi All,

Just an update on this point.

I have achieved this by removing this datasource in manifest.json.
I have called this url through ajax but we have to specify a prefix of app routers xs-app json( welcome file field )


Ajax url like this : Prefix of that field and followed by actual url.

/****/reporting/reports/v1/monthlySubaccountsCostfromDate=202101&toDate=202109

 

Regards,

Arun.D
ramuknura1395
Explorer
0 Kudos

Hi  anett-richel,

Thanks for publishing this blog, Everything works fine when deployed the app into CF Spaces.

Facing issue when we run the application locally in BAS. It is throwing unauthorized error for the API call when checking through console of the app.

If possible, please guide us to call this API locally through BAS because it's taking time every time to deploy the app and then looking for the changes.

Regards,

Arun.D

Gautam_M
Participant
0 Kudos
I am not able to get the data as in response it s coming blank. What else can we provide  in API filter to see the data?
0 Kudos
Can we achieve this calling BTP service with Managed approuter
dibyodeo
Explorer
0 Kudos
Hello anett-richel,

I have maintained the ui5.yaml and ui5-deploy.yaml

 backend:

          - path: /apihub

            url: https://api.authentication.us10.hana.ondemand.com

            destination: apihub



The destination I have created as apihub.But the problem is error fiori-tools-proxy Failed to register backend for /apihub. Check configuration in yaml file.
error fiori-tools-proxy Error. Also CORS issues



   var requestUrl = "https://b6f3e045trial.authentication.us10.hana.ondemand.com" + "/oauth/token?grant_type=client_credentials",

                        uName = "sb-na-1eacdb1e-cb1b-4506-9f8e-cc714d8eba60!a49565",

                        passwrd = "f11db480-d7bb-4450-85e3-b28d6562e948$uXptfdEEip3z96n84VUNs1cEY8ezI5s9G5pc3cNGBmc=";

                    //GETTING ACCESS TOKEN FOR FROM Authorization and Trust Management Service(xsuaa) --instance name "uaa"--

                    $.ajax({

                        type: "POST",

                        url: requestUrl,

                        beforeSend: function (xhr){

                            xhr.setRequestHeader('Authorization', "Basic " + btoa(uName+":"+passwrd));

                        },

                        async: true,

                        success: function(data){

                            console.log(data);

                            var acs_token = data.access_token,

                                tkn_type= data.token_type,

                                // reqUrl = "https://cors-anywhere.herokuapp.com/"+"https://api.authentication.eu10.hana.ondemand.com" + "/sap/rest/authorization/v2/roles";

                                // reqUrl = "https://api.authentication.eu10.hana.ondemand.com/sap/rest/authorization/v2/roles";

                                reqUrl = "apihub/sap/rest/authorization/v2/roles"

                            $.ajax({

                                type: "GET",

                                url: reqUrl,

                                crossDomain: true,

                                beforeSend: function (xhr){

                                    xhr.setRequestHeader("Authorization", tkn_type +" "+ acs_token);

                                    // xhr.setRequestHeader("Authorization", false);

                                    xhr.setRequestHeader("Accept", "application/json");

                                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                                    xhr.setRequestHeader("cache-control", "no-cache");

                                    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");

                                },

                                async: true,

                                success: function(data){

                                    console.log(data);

                                }

                            })

                        }

                    })






Any input or suggestion

Br

Dibya
ChrisSislak
Explorer
0 Kudos
Hi ramuknura1395

did you ever managed a local call through BAS or did you always uploaded it to CF?

BR
0 Kudos
Hi Arun

Even I am facing the same issue, did you got resolved it?

Can anyone help me why I am getting this error

 

Thanks

Arunteja
meetvengi
Explorer
0 Kudos
Hi DEO DEO,

You found the solution for this ? I am also facing this issue.