SAP CAP  Application Development

SAP CAP Application Development

Fri 04 Jul 2025

Introduction

In this blog, you’ll get a complete, hands-on walkthrough of developing an end-to-end SAP CAP (Cloud Application Programming) application, including the integration of a fully customized UI using SAPUI5. From setting up your project structure to building services, handling data models, and creating a responsive UI, every step is covered in detail. By the end, you’ll have a working full-stack SAP application and the knowledge to build your own solutions.             

SAP Cloud Application Programming (CAP) is a framework for building cloud-native applications using SAP technologies. It's part of SAP's Business Technology Platform (BTP) and helps developers create scalable, secure, and enterprise-ready applications.

Development Workflow:

  1. Data Modelling: You start by defining the data model using the CAP-specific language. This model represents your entities, relationships, and business logic.
  2. Service Creation: You then define services using the data model. These services expose the application logic (such as CRUD operations) as APIs that external systems or front-end apps can consume.
  3. Business Logic: You implement business logic by writing code (in JavaScript, Node.js, or Java) to handle specific behaviours within the application.
  4. Deployment: Once the application is built, you can deploy it on SAP BTP cloud platform. The deployment process is streamlined to support cloud-native features.

Along with CAP:

  • SAP HANA (Database) for real-time data processing
  • SAP Fiori/UI5 (UI framework) for frontend development
  • SAP BTP (Business Technology Platform) for cloud services and deployment
  • Node.js or Java for server-side application logic
  • OData (In case of consuming on-Premise or external system) or REST APIs for service communication

 Prerequisites:                    

              To develop and deploy an SAP Cloud Application Programming (CAP) application to SAP Business Technology Platform (BTP), you need to subscribe to several services within the SAP BTP. These services provide the necessary environment, tools, and infrastructure to build, deploy, and manage your application.

Here’s an overview of the key services and components you'll need to subscribe (Some of them are optional).

To subscribe and work on various services you are required to have a BTP account.

SAP BTP Account

  • SAP BTP Account: The first step is to create an account in SAP BTP. This will serve as your central platform for subscribing to the required services, managing your applications, and organizing your resources.
  • Create a sub account in your global account this involves in selecting the cloud provider after creating navigate to your sub account there you can enable cloud foundry

 

1.SAP Business Application Studio

  • SAP Business Application Studio: A cloud-based IDE (Integrated Development Environment) for developing cloud applications, including CAP applications. It provides templates, tools for managing your project, and an environment to write and deploy your code.

2.SAP HANA Cloud

  • SAP HANA Cloud: If your CAP application requires database management, you can subscribe to SAP HANA Cloud, which provides a fully managed in-memory database. You can use HANA Cloud as the underlying database to store and manage your application’s data.

3.SAP Cloud Foundry Environment (Need enabling the environment)

  • SAP Cloud Foundry: This is the platform-as-a-service (PaaS) environment within SAP BTP where you can deploy your CAP applications. Cloud Foundry provides a robust, scalable, and secure environment for hosting cloud-native applications.

4.XSUAA (optional in our case)

  • SAP Cloud Platform XS Advanced User Account and Authentication is a service in SAP Business Technology Platform (BTP) that provides user authentication and authorization capabilities for applications built on the SAP Cloud Platform (SAP CP), specifically for applications using the Cloud Foundry environment. It enables the management of user identities, roles, and permissions in the cloud environment to ensure secure access to SAP and non-SAP applications.

5.SAP Build Work Zone (optional in our case)

  • SAP Build Work Zone allows users to access personalized dashboards, applications, and content, tailored to their role or tasks. It provides a simple, efficient way to navigate various applications without jumping between multiple tools.

6.CI/CD (Continuous Integration and Continuous Deployment/Delivery)

  • CI/CD (Continuous Integration and Continuous Deployment/Delivery) is a set of software development practices that aim to automate and improve the process of software delivery. It helps teams deliver software updates more frequently and reliably by integrating code changes, automating tests, and deploying applications seamlessly. CI/CD is a fundamental aspect of DevOps practices, designed to improve collaboration between development and operations teams.

NOTE:  After subscribing the all services, you need to assign all roles to your user for respective service consumption.

 

Development:

Creating a CAP project:

Open business application studio and create a new dev space by selecting Full Stack cloud application and add all HANA tools to your dev space.

  1. Once inside the BAS IDE, open the Terminal window (you can find it at the bottom or use the shortcut ctrl + ~) and navigate to projects folder.
  2. Use the following command to initialize a new CAP project in the terminal:

cds init employee_CAP

Replace ‘employee_CAP’ with the name you want to assign to your CAP project.

This will create a new directory for your project with a basic CAP application template.

Or

  1.  

2.1 Also, you can create by an option called ‘new project from template’ shown below.

  1.  

2.2 Next select the CAP Project from the given templates and click on start  

  1.  

2.3 Next give the project name as you want and select the run time as Node.js If Java preferred select java, select the SAP HANA Cloud as your data base, way of deployment as MTA deployment and finish.

Note: You can also add these configurations later after creating the project by using cds commands through the terminal.

Example: cds add hana à this command adds hana as your application data base (updates package.json file).

  1.  

2.4 Now after finishing your project will be created and folder structure will be like this as shown in the image below.

  1. Now you can see the complete project with empty folders Here you can see the major folders are
    1. App folder à for developing UI
    2. DB folder à to design our data model
    3. Srv folder à for service definition and implementing business logic
  2. Now add a sample project with the cds command à cds add tiny-sample This command adds a simple project. (Adds simple bookshop project)

NOTE: In this blog we are going with a free style application so we build project completely from the basic level.

    1. Create a employeeDataModel.cds file in db folder which holds our data models and give a name space to it and create entities as shown in the image or copy the source code.

Data modelling:

Full Source Code: https://github.com/priyatham14114/employee_CAP.git

namespace employee_CAP.db; // Give a name space to this file to access data models later
using { cuid } from '@sap/cds/common'; // importing
entity employee_Data : cuid {   // here cuid automatically creates a unique ID for every record when it is created
    first_Name      : String not null;
    last_Name       : String not null;
    gender          : String not null;
    age             : Integer not null;
    email           : String;
    phone           : Integer;
    address         : Composition of many employee_Address // A tight coupled relation with address entity
                          on address.employee = $self;  // (when employee have multiple address)
    department      : Association to Department;
}
entity employee_Address : cuid {
  city     : String not null;
  pincode  : Integer not null;
  street   : String;
  landmark : String;
  employee : Association to employee_Data; // this association targets the user ID
}
entity Department : cuid {
  name        : String;
  description : String;
}

 

Service Definition:

    1. Now after creating the data model file successfully, create employee_service.cds in srv folder here you define your service and project entities as shown in the below image.

    1. After service definition open the terminal and give cds add data command this adds a data folder in db folder where you can find all .csv files here you can add mock data for each entity for development purpose.

    1. Let’s add some mock data to csv files to play with it during the development.
      1. Add data in employee_CAP.db-employee_Data.csv
ID,first_Name,last_Name,gender,age,email,phone,department_ID
  1. John,Doe,Male,35,john.doe@example.com,1234567890,1
  2. Jane,Smith,Female,28,jane.smith@example.com,9876543210,2
  3. Robert,Johnson,Male,45,robert.johnson@example.com,1122334455,1
  4. Mary,Evans,Female,30,mary.evans@example.com,6677889900,3
      1. Add data in employee_CAP.db-employee_Address.csv
ID,city,pincode,street,landmark,employee_ID
  1. New York,10001,5th Avenue,Near Central Park,1
  2. Los Angeles,90001,Hollywood Blvd,Near Walk of Fame,1
  3. Boston,02110,Main St,Near Library,2
  4. Chicago,60601,State St,Near Millennium Park,3
  5. San Francisco,94101,Market St,Near Golden Gate Bridge,4
      1. Add data in employee_CAP.db-employee_Address.csv
ID,name,description
  1. HR,Handles human resources and employee welfare.
  2. Engineering,Responsible for developing and maintaining products.
  3. Sales,Handles the selling of the company’s products and services.
    1. After adding mock data open terminal and run below commands
      1. cds deploy à Deploys to in-memory data base (sqlite)
      2. cds watch à Runs the CAP application on a port(4004).
      3. Open the port in the browser you can see your service endpoints something like below and expand each entity, you can see data from your csv files.

  1. Now check your service is working fine or not, let’s perform some CRUD operations in the testing environment, later we deploy our CAP application to HANA database there we work with real-time database.
    1. Now create a .http file in the in the root folder and make calls like below

Source code: https://github.com/priyatham14114/employee_CAP.git

# Get call
###
GET http://localhost:4004/EmployeeSRV/employee_Data HTTP/1.1
# Create call
###
POST http://localhost:4004/EmployeeSRV/employee_Data HTTP/1.1
Content-Type : application/json
{
    "first_Name": "John",
    "last_Name": "Doe",
    "gender": "Male",
    "age": 35,
    "email": "john.doe@example.com",
    "phone": 1234567890,
    "address": [
        {
            "city": "New York",
"pincode": 10001,
            "street": "5th Avenue",
            "landmark": "Near Central Park"
        },
        {
            "city": "Los Angeles",
            "pincode": 90001,
            "street": "Hollywood Blvd",
            "landmark": "Near Walk of Fame"
        }
    ],
    "department_ID": "1"
}

    1. Now click on send request as shown in above image then you will get response as below image if POST request is success, then it opens a new tab and shows status code as 201 created. If there is an error in service then it throws the cause for the error.
    2. If you can see a positive response on your post request congrats your service is working fine.
    3. Now you can see the create record in the records to see the created record send a GET request.

  1. You may wonder how the CRUD operations are going on without any program this is why we choose CAP frame work. CAP has an inbuilt @odata. Create, @odata. Read, @odata. update, @odata. Delete logic for entity operations. However, if you want to add custom logic (e.g., validation or additional processing before insertion), you can implement it in the service logic in the srv folder. Here's an example of how you can write a custom logic in employee_service.js:

Note: Make sure your business logic file name should be the same as your service file name and with .js extension.

Source Code: https://github.com/priyatham14114/employee_CAP.git (Refer git hub link for full source code)
const cds = require('@sap/cds');

module.exports = cds.service.impl(async function () {
    this.on('CREATE', 'employee_Data', async (req) => {
        const { data } = req; // destructure the data
        // You can write custom logic here, for example, validate the input data before creating a record
        try {
            if (!data.first_Name || !data.last_Name) {
                return req.reply({
                    statusCode: 400,       // Bad Request
                    statusText: 'Bad Request',
                    message: 'First name and last name are required fields.'
                });
            }
            const employee = await INSERT.into('employee_Data').entries(data); // Insert employee data into employee_data table
            // you can give response for the request
            return req.reply({
                employee: employee,     // Return the newly created employee
                statusCode:201,         // Return the status code
                statusText: "Created"   // Return the status text
            })
        } catch (error) {
            // General error handling
            return req.reply({
                statusCode: 500,    // Internal Server Error
                statusText: 'Internal Server Error',
                message: 'An unexpected error occurred.',
                details: error.message // Include more details about the error (careful about sensitive info)
            });
        }
    });
});

             

 

  1. Now you all good with CAP application let’s build UI application with UI5 framework.

Creating UI Project:

  1. Now from the same project create a project from template this time select the Fiori generator and follow the below steps.
    1. After selecting the Fiori generator click on start and follow the next steps
    2. Now you can see couple of templates in those choose a Basic freestyle application and click on Next.

    1. Select the data source as Use Local CAP Project and now the wizard fills the remaining data make sure the CAP project selected is correct or not next it automatically selects the OData service as CAP service which you created previously during CAP project creation

    1. And now give the required name to your UI application and name space as give below select the Add deployment and Add FLP configs as YES and click on next.

    1. Now in deployment configurations select target as Cloud foundry and destination as none.
    2. After adding deployment configurations add Fiori Launchpad Configurations click on finish

    1. Now you have successfully added the UI5 project to your CAP project open app folder there you can see your UI5 project.
    2. Now your CAP is your backend and UI5 is your front-end application.
    3. Let’s develop the UI.
  1. Let’s develop simple UI which shows the data base records and perform the CRUD operations.

Note: For UI development refer SAPUI5 SDK: Demo Kit

    1. Know the MVC (Model, View, Controller) architecture of UI5 application:
      1. Views: Represent the structure of the UI (e.g., XML, HTML).
      2. Controllers: Handle the logic behind the views, including user interaction, data binding, and actions.
      3. Model:  Handling the data.
    2. Now navigate to view folder which is inside the webapp folder and there you can find all the views in my case I created HOME view so in that let’s build the UI.

UI Creation: (Please refer git for full source code)

Source: https://github.com/priyatham14114/employee_CAP.git

    1. Now past the source code provided below (Get it from the git hub).

Source: https://github.com/priyatham14114/employee_CAP.git

    1. Now give cds watch command to run the application. In the web browser you can see something like below with a file in the web Application section click on it you will see your UI.

    1. Now after developing the UI and data bindings in HOME view output will be like this below. (from above image click on /employee_app/webapp)

OData V2 Adapter configuration:

    1. Now let’s make something interesting let’s perform the CREAT, UPDATE DELETE operations, as we discussed earlier, we do write logic in the respective controller so here in my case HOME controller because I’m going to give functionality to the HOME view components (Buttons).
    1. As in this project we are using OData V2 for CRUD operations we need to add OData v2 adapter, so for that please follow the below steps
      1. Go to browser and search OData v2 adapter proxy
      2. Click on NPM web site
      1. Search for @cap-js-community/odata-v2-adapter (latest adapter)
      2. After selecting this adapter scroll down to see something like this below

 

      1. Copy the snippet and create a server.js file in the srv folder paste the snippet in this file.
      2. Run command npm i @cap-js-community/odata-v2-adapter
      1. Now Navigate to manifest.json file to add the ServiceV2 in data sources section and modelV2 in model section as shown below images.

 

            That’s it you now added OData model V2 to the project.

    1. Now go to your controller and write the logic for create, update, delete. Make sure press events matches the same names in both xml file and controller.

Source Code: for full code please refer git hub.

Git: https://github.com/priyatham14114/employee_CAP.git

CRUD Operations:

Create Operation:

onCreate: async function () {
            const that = this,
                oNewData=this.getView().getModel("newEmployeeModel").getData()
            const oModel = this.getOwnerComponent().getModel("ModelV2");
            await oModel.create("/employee_Data", oNewData, {
                success: async function (oData, Resp) {
                    sap.m.MessageToast.show("Created")
                    that.byId("_IDGenTable").getBinding("items").refresh()    //refresh table
                    await that.onClose();
                },
                error: function (error) {
                    sap.m.MessageToast.show("Creation Failed" + error)
                }
            })
 
        }

Delete Operation:      

               onDelete: async function () {
            const that = this;
            const oSelected = this.byId("_IDGenTable").getSelectedItem(),
                userId = oSelected.getBindingContext().getObject().ID
            const oModel = this.getOwnerComponent().getModel("ModelV2");
            await oModel.remove(`/employee_Data('${userId}')`, {
                success: function (oData, response) {
                    sap.m.MessageToast.show("Deleted")
                    that.byId("_IDGenTable").getBinding("items").refresh();
                },
                error: function (error) {
                    sap.m.MessageToast.show("Deletion Failed" + error)
                }
            })
        }

 

Update Operation:

onUpdate: function () {
            const that = this;
            const oPayload = this.getView().getModel("newEmployeeModel").getData();
 
            const oSelected = this.byId("_IDGenTable").getSelectedItem(),
                userId = oSelected.getBindingContext().getObject().ID
 
            const oModel = this.getOwnerComponent().getModel("ModelV2");
            oPayload.department = {}
 
            oPayload.department_ID = this.byId("_IDGenInput4").getValue();
 
            oModel.update(`/employee_Data('${userId}')`, oPayload, {
                success: async function (Resp) {
                    sap.m.MessageToast.show("Updated successfully")
                    that.byId("_IDGenTable").getBinding("items").refresh();
                    await that.onClose();
                },
                error: function (error) {
                    sap.m.MessageToast.show("Update Failed" + error)
                }
            })
 
        }

 

Database connectivity:

So, till now development is completed with all CRUD operations and let’s connect our application to the HANA cloud and let’s work with real time database.

HANA Cloud Instance Subscription:

  1. Go to BTP cockpit there navigate to Instances and Subscriptions sections and click on create.

 

  1. Select service as SAP HANA Cloud, plan as tools and create as shown below.

  1. After successful creation go to your subscriptions there you can see your SAP HANA Cloud click on it and it opens and there you click on the Go to Application as shown below.

  1. You can see something like this below it is informing that you don’t have access to this service get rights you need to add role collections to your user in the security section.

  1. Navigate to your BTP cockpit go to security section and there click on users and assign required role collections to your user as shown below.

  1. Select the below required roles and click on Assign Role Collection

  1. Now go to HANA Cloud try to re-login and you can see Instances page like below and click on Create Instance

  1. Select the type as SAP HANA Cloud, SAP HANA database and sign into the cloud foundry environment and select the space and click on next step.

  1. In general give instance name and set the password click on next step.

  1. In SAP HANA Database section you can see memory and storage of database just click on next step.

  1. Now again click on next as we are using trail instance, we don’t have permission for this section.

  1. Now in next step select allowed connections as ALLOW ALL IP ADDRESSES and click on next.

  1. Now click on Review and create and in next page also click on create your database instance will be created shortly.

 

  1. Now you have you subscribed to HANA services and your HANA data base is ready let’s configure the data base in our application.

HANA Cloud Deployment Configuration:

  1. Go to Business Application Studio (BAS) navigate to your project open terminal and give command cds deploy --to hana this command is used to deploy your CDS (Core Data Services) model to a HANA database. It takes your CDS files (typically in the db/ folder) and compiles them into a format that the HANA database understands — typically SQL statements.
  2. And it adds a HANA instance for current project in the BTP cockpit. (refer image below).

 

 

 

  1. Now run the application using cds watch --profile hybrid it runs the application HANA as its data base.

 

  1. Now perform the CRUD operations, created data will be stored in the HANA cloud.

  1. Let’s check the HANA cloud whether the data is created or not.
  2. Open the HANA database explorer as shown below.

  1. Go to SAP HANA PROJECTS, click on the icon shown in the above image, it opens the HANA database explorer, login with your BTP credentials.
  2. You can see database instance open it and find the tables and click on it you can see your database tables click on any table name and next click on open data.


Author: Administrator

Fri 04 Jul 2025

Category: SAP BTP
Comments: 1
Views: 468

Leonardalcog Guest

Venture into the vast sandbox of EVE Online. Become a legend today. Fight alongside hundreds of thousands of pilots worldwide. [url=https://www.eveonline.com/signup?invc=46758c20-63e3-4816-aa0e-f91cff26ade4]Free registration[/url]

30 23.09.2025


1000

Categories

Recent Blogs

Cloud Foundry Deployment Using CI/CD Pipeline
Category : SAP BTP
Fri 04 Jul 2025
0 Comments
SAP CAP Application Development
Category : SAP BTP
Fri 04 Jul 2025
1 Comments
Custom Headlines for Report (SE38)
Category : SAP ABAP
Mon 30 Jun 2025
0 Comments