Build BTP CAP App with Fiori Integration – Part 2: Implementing End to End App

Estimated read time 21 min read

A quick Recall – So far we have completed the Pre-Requisites and set up the BTP Environment for creating/Deploying CAP Application. BTP Trail Account has been created and within Trail sub-account necessary cloud related roles have been assigned. Post that SAP HANA Cloud instance has been created and BAS Set up has been done. 

PART 1 Link – STAY TUNED…

As a part of second episode in this CAP Application blog series, we are about to develop an end to end CAP Application with layers of validation of security in a detailed way. This blog helps beginner to build end to end CAP Application.

Flowchart giving overview for complete Process

Ever struggled to deploy a CAP app with HANA + XSUAA + App router?.

I did. After multiple failures, here is a complete working guide 👇

BACKEND BUILD :

1. Navigate to BAS->Dev Space and Create new project from Template.

After creating CAP Project Run these Below terminal Commands which has unique operation.

a. This below terminal command to be added which will prepare the CAP project for a real-world cloud environment i.e. SAP BTP. add hana will switch database from SQLITE to HANA Cloud & add xsuaa will enable authorization for the project. Also When we ran the command cds add xsuaa –for production then CAP automatically generates the security folder xs-security.json.

cds add hana,xsuaa –for production

b. Below terminal command will add blueprint for deployment.

cds add mta

c. Below terminal command will install libraries.

npm install

2. Select CAP Project Option and name the project and select options as below. 

3. Click on Finish after selecting all the options.

4. Once Project is created it will be available in the Workspace.

5. We can view the path of the project created using below Terminal command. ( Note : Use Ctrl + ~ to open terminal ).

user: CRUDApp $ pwd

Once this Terminal command is entered the response will come as /home/user/projects/CRUDApp. 

6. Now the Project is created. The Aim is to create service instance in Cloud Foundry space dev which I shown in PART 1 and through the service instance the linkage to HANA Cloud central DB Instance will be triggered with runtime HDI Container created. Through this HDI Container the Deployment data will be mapped to runtime DB. 

Before getting into next point. Let me give a quick overview on different folder paths/ files in CAP Project that has been created. ( Refer to the workspace image from Point 4. )

a) db/ – This is database schema where we will create CDS Entities/tables and it’s relationships. It’s is the source of data structure.

b) app/ – In this folder the front end Fiori Generator App will be mapped which has further navigations to Controllers and views. From here only we will write front end logic.

c) srv/ – This is service folder where api services will be created from backend and if required custom logic can be enabled using node js in js file. 

d) .vscode – This is a hidden folder containing configurations specific to Visual Studio Code or BAS. It stores things like your launch configuration and recommended extensions for the project.

e) mta.yaml Multi-Target Application file is the provides instruction to cloud. It tells SAP BTP how to package and deploy your app, which database to create, which security services to bind, and how much memory to use.

f) package.json – This is the Project Meta data which holds libraries to run project. 

Now let’s continue with further steps from Backend.

7.  Create a file schema.cds as below to /db folder and create Entity bookshop. This Entity is designed to store Book details. The same will be created as table in SAP HANA Cloud.

namespace my.bookshop;

entity Books {
key ID : Integer;
title : String;
stock : Integer;
author : String;
}

8. Create a file schema.cds as below to /srv folder. In this Service folder we are adding annotation @requires: ‘Admin’ which indicates Role required for Authorization.

using { my.bookshop as my } from ‘../db/schema’;

service CatalogService {
@requires: ‘Admin’ // XSUAA Role Required
entity Books as projection on my.Books;
}

FRONT END BUILD:

1. Click Ctrl + Shift + P and select Open Fiori App Generator as shown below.

2. Since this is a basic app and henceforth Select List Report Template as below.

3. Now select Data source as Local CAP Project and select CAP Project and OData service. After this select on Next button. 

4. Give Name to App and Module.

5. Then Deployment configuration should be auto-picked as cloud foundry and If required fill Destination. For this app Im not creating Destination and henceforth selection the option as None. After this select Finish option which will create Fiori App in Project Folder. 

 

VALIDATION :

1. Create a file cat-service.js as below to /srv folder. 

const cds = require(‘@sap/cds’)

module.exports = cds.service.impl(async function() {
const { Books } = this.entities;

// Logic: Validation BEFORE creating a record
this.before(‘CREATE’, ‘Books’, req => {
const { title } = req.data;
if (!title || title.length < 3) {
// This is like an ‘E’ message in ABAP
req.error(400, ‘Title is too short! Minimum 3 characters required.’);
}
})
})

2. As per above logic, we are adding some validation before SAVE using Node JS Function. As per this validation if Title length is less than 3 then error will be thrown. Similarly we can use other functions as well to perform business operation which triggers during save, After save etc. 

SECURITY:

1. When the Environment was set up in BACKEND BUILD->1.a), we ran the command cds add xsuaa –for production which in turn created the folder xs-security.json. 

2. Now the aim is to deploy the app to production and create HTML5 App in BTP. So here we are adding a security layer which tells only Authorized user can access the data. While defining the service in BACKEND BUILD->8. where Admin role is annotated to books entity. 

3. Lets create Approuter now and configure JSON to add necessary roles. 

4. There are two options for adding Approuters.

a. Right click on mta.yaml file and select Create MTA Module From Template and then select Managed Approuter. 

b. If Managed Approuter option is not showing, then below terminal command is a reliable ‘Reset’ button. It cleans up the MTA configuration and sets up a standalone router that works independently of external BTP subscriptions. 

cds add approuter

5. Currently Im going with 4.b) with manual terminal command for adding Approuter. Once that is done then approuter will be added as below in app/ folder. 

6. Add below JSON to folder xs-security.json in project which will define the role which is binded in service and yaml

{
“xsappname”: “my-bookshop”,
“scopes”: [
{
“name”: “$XSAPPNAME.Admin”,
“description”: “Admin”
}
],
“role-templates”: [
{
“name”: “AdminRole”,
“scope-references”: [ “$XSAPPNAME.Admin” ]
}
],
“attributes”: [],
“authorities-inheritance”: false
}

DEPLOYMENT:

1. So till now we have built this CAP Application in “Vertical Stack” (Database → Logic → Security → Routing → UI).

2. Now before final deployment lets test the things done till now is correct. Use below terminal command. If everything is fine then You see your database schema, custom logic, approuter config, and Fiori manifest listed.

 

ls -R | grep -E “schema.cds|cat-service.js|xs-app.json|manifest.json”

3.  Now compile all the files to check if any error occurs. Use below terminal commands.

cds compile db/
cds compile srv/
cds compile srv/ –to xsuaa

 Note: All these commands should not throw error to proceed with next steps.

4.  After Sanity checks, run below command to login to terminal. Note: It will ask for Api Endpoint for first time during login. It can be found from BTP Cockpit -> Overview -> Cloud Foundry Environment -> API End Point.

cf login

5. Now run Deployment command in terminal. This is done to test the app locally. Once testing is completed the app needs to be deployed to Production.

cds deploy –to hana –profile hybrid

6. If cds deploy is not working properly then define step by step process of creating service instance, HDI Containers etc. through terminal commands below. Note: cds deploy will create everything by default so dont use these in combination. use these terminal commands only if cds deploy is not working. 

cf create-service hana hdi-shared my-cap-app
cds bind –to my-cap-app
cds env get requires.db –profile hybrid
cds deploy –to hana –profile hybrid

7. Run below commands to deploy the app to production. 

 

mbt build

 

8. When finished, a new folder named mta_archives/ will appear as below containing Project file. 

9. Now do a login again with below command. Give appropriate API Key and user details.

cf login

10. Run below command to Complete final HTML5 App deployment. 

cf deploy mta_archives/CRUDApp_1.0.0.mtar

Note: Sometimes Deployment will fail. To avoid these common pitfalls,  “Only include essential resources (HANA, XSUAA, Destination, and HTML5) in your mta.yaml and ensure your xsappname in xs-security.json is consistent throughout the project to prevent service plan unavailability and identity mismatch errors on Trial accounts.” If something fails, make these changes and delete the service and redeploy. After redeployment dont forgot to add role collections again to make sure Approuters will not cause auth errors. 

TESTING

1. Run below Terminal command to test the app locally.

cds watch –profile hybrid

 2. After this the app will open in next screen to test it from web level. Note: Make sure your HANA DB Instance is running in HANA Cloud Central which will create entry in DB Level. 

3. Now while testing this app we can see the user login screen which will ask for mail and password for login. This is happening due to XSUAA and Approuter. While trying to make entry to the app it will show error forbidden as below. 

4. Now run this command below to create service Instance first. Even after cds deploy this is required because cds deploy only talks to the Database (HANA). It does not talk to the Security Service (XSUAA). In SAP BTP, the database (CRUDApp-db) and the security (XSUAA) are two completely separate buildings. This terminal logic is required to enable link. 

cf create-service xsuaa application CRUDApp-auth -c xs-security.json

 5. Post this navigate to BTP Cockpit -> SubAccount -> Security -> Role Collections and click on Create Button as below. 

6. Create Role collection Bookshop_Admin_Group with its Description as below.

7. Now Navigate to the Role collection Bookshop_Admin_Group and click on Edit. Open value help of Role and select the App name from Application Identifier dropdown. After selecting Role Admin which enables Authorization, click save. Follow below images sequentially. 

8. After saving, the role will be available in Role collection as below.

9. Now refresh the app and try running, It will work !. Note: Sometimes Auth error will still occur if you test locally. In that case assign your URL to user Alice or deploy and test the app. 

10. Also once deployed to HTML5 Apps or Dev space, the app can be directly tested from there as well. 

FINAL APP EXECUTION🔥:

1. Now, lets open the app as below.

2. Lets create some incorrect entries as below. 

3. Validation Error occurs as per Node js logic for incorrect inputs. 

4. While creating valid records, Data gets created as below without any auth error/Forbidden as the custom role collection created and mapped to Admin Role. Note: Unique UUID will be generated for each record as per CAP Entity definition made. The UUID can be viewed in Cloud DB.

5. Now navigate to SAP HANA Cloud and click on … dots. select option “OPEN IN SAP HANA Database Explorer”.

4. Once SAP HANA Database Explorer opens then login to cloud foundry Environment from there.

5. Now select the “+” icon and select HDI Containers options and then select app container specific to app name.

7. From CRUDAPP-db HDI Container, Navigate to Tables and select open data.

8. The Data created from Fiori App is available in Cloud Table as below along with UUID auto-generated.

CONCLUSION:

Hence the overall flow looks as below.

Fiori UI

App router

CAP Service

HANA DB (HDI Container)

With this blog series we learned how to set up environment, enable cloud instance, create end to end CAP Full stack application which has capability to communicate with SAP HANA Cloud instance and create entries over there, enable App routers to CAP App and Enable validation while creating entries. 

I hope this blog will be helpful for enthusiasts who are learning CAP !. In future I will create add-on series with steps to deploy this app to SAP Build work zone. 

 

​ A quick Recall – So far we have completed the Pre-Requisites and set up the BTP Environment for creating/Deploying CAP Application. BTP Trail Account has been created and within Trail sub-account necessary cloud related roles have been assigned. Post that SAP HANA Cloud instance has been created and BAS Set up has been done. PART 1 Link – STAY TUNED…As a part of second episode in this CAP Application blog series, we are about to develop an end to end CAP Application with layers of validation of security in a detailed way. This blog helps beginner to build end to end CAP Application.Flowchart giving overview for complete ProcessEver struggled to deploy a CAP app with HANA + XSUAA + App router?.I did. After multiple failures, here is a complete working guide 👇BACKEND BUILD :1. Navigate to BAS->Dev Space and Create new project from Template.After creating CAP Project Run these Below terminal Commands which has unique operation.a. This below terminal command to be added which will prepare the CAP project for a real-world cloud environment i.e. SAP BTP. add hana will switch database from SQLITE to HANA Cloud & add xsuaa will enable authorization for the project. Also When we ran the command cds add xsuaa –for production then CAP automatically generates the security folder xs-security.json.cds add hana,xsuaa –for productionb. Below terminal command will add blueprint for deployment.cds add mtac. Below terminal command will install libraries.npm install2. Select CAP Project Option and name the project and select options as below. 3. Click on Finish after selecting all the options.4. Once Project is created it will be available in the Workspace.5. We can view the path of the project created using below Terminal command. ( Note : Use Ctrl + ~ to open terminal ).user: CRUDApp $ pwdOnce this Terminal command is entered the response will come as /home/user/projects/CRUDApp. 6. Now the Project is created. The Aim is to create service instance in Cloud Foundry space dev which I shown in PART 1 and through the service instance the linkage to HANA Cloud central DB Instance will be triggered with runtime HDI Container created. Through this HDI Container the Deployment data will be mapped to runtime DB. Before getting into next point. Let me give a quick overview on different folder paths/ files in CAP Project that has been created. ( Refer to the workspace image from Point 4. )a) db/ – This is database schema where we will create CDS Entities/tables and it’s relationships. It’s is the source of data structure.b) app/ – In this folder the front end Fiori Generator App will be mapped which has further navigations to Controllers and views. From here only we will write front end logic.c) srv/ – This is service folder where api services will be created from backend and if required custom logic can be enabled using node js in js file. d) .vscode – This is a hidden folder containing configurations specific to Visual Studio Code or BAS. It stores things like your launch configuration and recommended extensions for the project.e) mta.yaml – Multi-Target Application file is the provides instruction to cloud. It tells SAP BTP how to package and deploy your app, which database to create, which security services to bind, and how much memory to use.f) package.json – This is the Project Meta data which holds libraries to run project. Now let’s continue with further steps from Backend.7.  Create a file schema.cds as below to /db folder and create Entity bookshop. This Entity is designed to store Book details. The same will be created as table in SAP HANA Cloud.namespace my.bookshop;

entity Books {
key ID : Integer;
title : String;
stock : Integer;
author : String;
}8. Create a file schema.cds as below to /srv folder. In this Service folder we are adding annotation @requires: ‘Admin’ which indicates Role required for Authorization.using { my.bookshop as my } from ‘../db/schema’;

service CatalogService {
@requires: ‘Admin’ // XSUAA Role Required
entity Books as projection on my.Books;
}FRONT END BUILD:1. Click Ctrl + Shift + P and select Open Fiori App Generator as shown below.2. Since this is a basic app and henceforth Select List Report Template as below.3. Now select Data source as Local CAP Project and select CAP Project and OData service. After this select on Next button. 4. Give Name to App and Module.5. Then Deployment configuration should be auto-picked as cloud foundry and If required fill Destination. For this app Im not creating Destination and henceforth selection the option as None. After this select Finish option which will create Fiori App in Project Folder.  VALIDATION :1. Create a file cat-service.js as below to /srv folder. const cds = require(‘@sap/cds’)

module.exports = cds.service.impl(async function() {
const { Books } = this.entities;

// Logic: Validation BEFORE creating a record
this.before(‘CREATE’, ‘Books’, req => {
const { title } = req.data;
if (!title || title.length < 3) {
// This is like an ‘E’ message in ABAP
req.error(400, ‘Title is too short! Minimum 3 characters required.’);
}
})
})2. As per above logic, we are adding some validation before SAVE using Node JS Function. As per this validation if Title length is less than 3 then error will be thrown. Similarly we can use other functions as well to perform business operation which triggers during save, After save etc. SECURITY:1. When the Environment was set up in BACKEND BUILD->1.a), we ran the command cds add xsuaa –for production which in turn created the folder xs-security.json. 2. Now the aim is to deploy the app to production and create HTML5 App in BTP. So here we are adding a security layer which tells only Authorized user can access the data. While defining the service in BACKEND BUILD->8. where Admin role is annotated to books entity. 3. Lets create Approuter now and configure JSON to add necessary roles. 4. There are two options for adding Approuters.a. Right click on mta.yaml file and select Create MTA Module From Template and then select Managed Approuter. b. If Managed Approuter option is not showing, then below terminal command is a reliable ‘Reset’ button. It cleans up the MTA configuration and sets up a standalone router that works independently of external BTP subscriptions. cds add approuter5. Currently Im going with 4.b) with manual terminal command for adding Approuter. Once that is done then approuter will be added as below in app/ folder. 6. Add below JSON to folder xs-security.json in project which will define the role which is binded in service and yaml. {
“xsappname”: “my-bookshop”,
“scopes”: [
{
“name”: “$XSAPPNAME.Admin”,
“description”: “Admin”
}
],
“role-templates”: [
{
“name”: “AdminRole”,
“scope-references”: [ “$XSAPPNAME.Admin” ]
}
],
“attributes”: [],
“authorities-inheritance”: false
}DEPLOYMENT:1. So till now we have built this CAP Application in “Vertical Stack” (Database → Logic → Security → Routing → UI).2. Now before final deployment lets test the things done till now is correct. Use below terminal command. If everything is fine then You see your database schema, custom logic, approuter config, and Fiori manifest listed. ls -R | grep -E “schema.cds|cat-service.js|xs-app.json|manifest.json”3.  Now compile all the files to check if any error occurs. Use below terminal commands.cds compile db/
cds compile srv/
cds compile srv/ –to xsuaa Note: All these commands should not throw error to proceed with next steps.4.  After Sanity checks, run below command to login to terminal. Note: It will ask for Api Endpoint for first time during login. It can be found from BTP Cockpit -> Overview -> Cloud Foundry Environment -> API End Point.cf login5. Now run Deployment command in terminal. This is done to test the app locally. Once testing is completed the app needs to be deployed to Production.cds deploy –to hana –profile hybrid6. If cds deploy is not working properly then define step by step process of creating service instance, HDI Containers etc. through terminal commands below. Note: cds deploy will create everything by default so dont use these in combination. use these terminal commands only if cds deploy is not working. cf create-service hana hdi-shared my-cap-app
cds bind –to my-cap-app
cds env get requires.db –profile hybrid
cds deploy –to hana –profile hybrid7. Run below commands to deploy the app to production.  mbt build 8. When finished, a new folder named mta_archives/ will appear as below containing Project file. 9. Now do a login again with below command. Give appropriate API Key and user details.cf login10. Run below command to Complete final HTML5 App deployment. cf deploy mta_archives/CRUDApp_1.0.0.mtarNote: Sometimes Deployment will fail. To avoid these common pitfalls,  “Only include essential resources (HANA, XSUAA, Destination, and HTML5) in your mta.yaml and ensure your xsappname in xs-security.json is consistent throughout the project to prevent service plan unavailability and identity mismatch errors on Trial accounts.” If something fails, make these changes and delete the service and redeploy. After redeployment dont forgot to add role collections again to make sure Approuters will not cause auth errors. TESTING1. Run below Terminal command to test the app locally.cds watch –profile hybrid 2. After this the app will open in next screen to test it from web level. Note: Make sure your HANA DB Instance is running in HANA Cloud Central which will create entry in DB Level. 3. Now while testing this app we can see the user login screen which will ask for mail and password for login. This is happening due to XSUAA and Approuter. While trying to make entry to the app it will show error forbidden as below. 4. Now run this command below to create service Instance first. Even after cds deploy this is required because cds deploy only talks to the Database (HANA). It does not talk to the Security Service (XSUAA). In SAP BTP, the database (CRUDApp-db) and the security (XSUAA) are two completely separate buildings. This terminal logic is required to enable link. cf create-service xsuaa application CRUDApp-auth -c xs-security.json 5. Post this navigate to BTP Cockpit -> SubAccount -> Security -> Role Collections and click on Create Button as below. 6. Create Role collection Bookshop_Admin_Group with its Description as below.7. Now Navigate to the Role collection Bookshop_Admin_Group and click on Edit. Open value help of Role and select the App name from Application Identifier dropdown. After selecting Role Admin which enables Authorization, click save. Follow below images sequentially. 8. After saving, the role will be available in Role collection as below.9. Now refresh the app and try running, It will work !. Note: Sometimes Auth error will still occur if you test locally. In that case assign your URL to user Alice or deploy and test the app. 10. Also once deployed to HTML5 Apps or Dev space, the app can be directly tested from there as well. FINAL APP EXECUTION🔥:1. Now, lets open the app as below.2. Lets create some incorrect entries as below. 3. Validation Error occurs as per Node js logic for incorrect inputs. 4. While creating valid records, Data gets created as below without any auth error/Forbidden as the custom role collection created and mapped to Admin Role. Note: Unique UUID will be generated for each record as per CAP Entity definition made. The UUID can be viewed in Cloud DB.5. Now navigate to SAP HANA Cloud and click on … dots. select option “OPEN IN SAP HANA Database Explorer”.4. Once SAP HANA Database Explorer opens then login to cloud foundry Environment from there.5. Now select the “+” icon and select HDI Containers options and then select app container specific to app name.7. From CRUDAPP-db HDI Container, Navigate to Tables and select open data.8. The Data created from Fiori App is available in Cloud Table as below along with UUID auto-generated.CONCLUSION:Hence the overall flow looks as below.Fiori UI↓App router↓CAP Service↓HANA DB (HDI Container)With this blog series we learned how to set up environment, enable cloud instance, create end to end CAP Full stack application which has capability to communicate with SAP HANA Cloud instance and create entries over there, enable App routers to CAP App and Enable validation while creating entries. I hope this blog will be helpful for enthusiasts who are learning CAP !. In future I will create add-on series with steps to deploy this app to SAP Build work zone.    Read More Technology Blog Posts by Members articles 

#SAP

#SAPTechnologyblog

You May Also Like

More From Author