Developing a Custom Logic Microservice in SAP Build Code

Objective

After completing this lesson, you will be able to build a microservice using SAP Build Code to extend the standard business logic in SAP Sales Cloud and SAP Service Cloud Version 2.

New Project Creation

In this lesson, you will learn how to create a simple Node.js-based microservice using SAP Business Application Studio and configure it as a deployable application on the SAP Business Technology Platform (BTP). The microservice will be deployed to the Cloud Foundry environment within the subaccount you created earlier, Creating a Subaccount in the SAP BTP Cockpit Using a Booster.

Before we build a Node.js-based microservice, let’s first understand what a microservice is

A microservice is a small, independent application that performs one specific function and can communicate with other systems through APIs or events. In SAP Sales Cloud and SAP Service Cloud Version 2, microservices are often used to extend standard functionalities. For example, to automatically create related business objects, such as Subcases. Each microservice can be developed, deployed, and maintained separately, which makes them flexible and easy to scale on BTP.

To create a Node.js-based microservice, in Business Application Studio, start by creating a new project.

  • Choose New Project from Template from the Welcome page or the File menu.
  • Select Choose Basic Multitarget Application and proceed to the next step.
  • In the Provide a Name screen, enter a unique project name, for example, btp-microservice-subcase
  • Then, choose Finish.

This template creates a minimal Multitarget Application (MTA) structure that can later be deployed to Cloud Foundry, the runtime environment on SAP BTP.

Enter a project name for the new Multitarget Application template in SAP Build Code. The example shows the project name btp-microservice-subcase entered in the “Provide a Name” step.

After finishing the wizard, your new project appears in the Explorer on the left side of the editor. You should see files such as:

  • mta.yaml: defines the build and deployment configuration of your multitarget application.
  • .gitignore: specifies files and folders that should be excluded from source code version control.

Caution

Although the project structure includes an mta.yaml file by default from the MTA template, this file is not used in this demo since we’re using the Cloud Foundry command-line tools for deployment. To keep things simple and focused on learning, the deployment is managed using the manifest.yaml file instead.

At this point, your project only contains the root configuration files. In the next steps, let's add a Node.js module that contains the actual logic of the microservice.

The newly created project btp-microservice-subcase is visible in the workspace. The Explorer shows the project folder containing the initial configuration files .gitignore and mta.yaml.

Node.js Project Environment Setup

To start developing the Node.js project, open a terminal window within SAP Business Application Studio.

From the top menu, choose TerminalNew Terminal.

This opens a command line at the root of your project, where you can run Node.js and npm commands. The terminal will be used to initialize the Node.js project and install the required dependencies for your custom logic. Now you will prepare your project for Node.js development.

In the terminal, execute the following commands:npm init -y and followed by npm install express axios.

The command npm init -y creates a new package.json file with default settings. This file describes your Node.js application and manages its dependencies. The command npm install express axios installs the libraries or dependencies needed for your microservice. They include:

  • Express: which provides a lightweight web application framework that allows you to define REST API endpoints.
  • Axios: which is used to send HTTP requests, for example, to call the SAP Sales Cloud and SAP Service Cloud Version 2 API and create a Subcase.

After running these commands, the package.json, package-lock.json files and the node_modules folder appear in the Explorer.

The package.json, package-lock.json file and the node_modules folder confirm that your Node.js application has been initialized correctly and is ready for development.

In the terminal, the commands npm init -y and npm install express axios are executed. The Explorer now lists the generated package.json and package-lock.json files and the node_modules folder, confirming successful Node.js initialization and dependency installation.

Manifest.yaml File Configuration

The manifest.yaml file defines how your application will be built and deployed in the Cloud Foundry environment within your BTP Subaccount.

It contains important metadata such as the application name, memory allocation, start command, and the buildpack that determines the runtime environment. In addition, the manifest file includes environment variables that store sensitive or environment-specific information your application needs at runtime, such as credentials or API URLs. This enables the deployment of the same code across different environments (e.g., test and production) without modifying the code itself.

Create the file manifest.yaml in the root folder of your project and copy the provided code snippet into it. In the section labeled env, you will see placeholders for the variables:

  • SSC_USER – your SAP Sales Cloud and SAP Service Cloud Version 2 username
  • SSC_PASSWORD – your SAP Sales Cloud and SAP Service Cloud Version 2 password
  • SERVICE_URL – the base URL of your SAP Sales Cloud and SAP Service Cloud Version 2 tenant

Replace only these placeholder values with your own credentials and service URL. All other settings, such as memory size, instance count, and buildpack can remain unchanged. When the build and deployment runs, Cloud Foundry automatically reads the values from this manifest file and uses them to build and start the microservice correctly.

For learning-purposes and to keep this exercise simple, the credentials are written directly into the manifest.yaml file.

Note

Writing the credentials directly into the manifest.yaml file is not considered a best practice and should never be used in production environments.

In a real-world scenario, credentials and other sensitive data need to be stored securely using environment variables outside of the project itself, in the SAP Destination Service, or SAP Credential Store.

Below is the complete manifest.yaml example for your reference. Feel free to modify it to fit your project and environment requirements.

YAML
12345678910111213
applications: - name: btp-microservice-subcase command: node app.js instances: 3 memory: 128M default-route: true buildpack: nodejs_buildpack env: OPTIMIZE_MEMORY: "true" SSC_USER: YourUser SSC_PASSWORD: YourPW SERVICE_URL: https://my1000xxx.de1.demo.crm.cloud.sap

Microservice Logic Implementation

The file, app.js was mentioned in the manifest.yaml earlier as a reference. It contains the main logic of your microservice. It implements how the service reacts when called from SAP Sales Cloud and SAP Service Cloud Version 2 and what actions it performs in response.

In this section, let’s go ahead and create a new file named app.js in the root folder of your project. Then, copy the provided code snippet into this file.

The app.js file displays the Node.js code that defines the microservice logic. The highlighted section includes the/onCreateSubCase function, which receives event notifications from SAP Service Cloud Version 2 and creates a Subcase using the Service Cloud Version 2 API.

The first part of the code handles the setup and authentication:

  • It imports the required Node.js modules or dependencies such as express and axios.
  • It creates a Basic Authentication token using your SAP Sales Cloud and SAP Service Cloud Version 2 credentials, which are stored as environment variables in the manifest.yaml file.
  • It defines a base URL that points to your SAP Sales Cloud and SAP Service Cloud Version 2 API endpoint.
  • It also sets default HTTP headers for Axios to ensure that every API request payload is sent in JSON format with the proper authorization.

The next part defines the Express application and its routes. The app.post('/onCreateSubCase', ...) route, highlighted in the screenshot, is the core of your microservice. This function acts as a webhook endpoint. It is triggered automatically when an event occurs in SAP Sales Cloud and SAP Service Cloud Version 2 (for example, when a new case is created).

Inside this function, the logic performs the following steps:

  1. It reads the event payload (the request body) and extracts key information such as the case ID.
  2. It checks whether the created case already has a parent case.
  3. If the case does not have a parent, the function creates a new Subcase by sending a POST request to the SAP Sales Cloud and SAP Service Cloud Version 2 API endpoint /v1/case-service/cases.

It uses Axios to send this request, with a JSON payload containing information like the subject, type, priority, and relationship to the original case.

There are also several console.log() and console.error() statements included in the code to provide debug information during runtime. These log messages indicate key events such as when the server starts, when a Subcase is created, or if an error occurs during the process. When the microservice is deployed to Cloud Foundry, these log messages can be viewed using the command cf logs <app-name> --recent. This allows you to verify that the microservice is running correctly and helps you troubleshoot any issues that arise during testing.

The new Subcase will automatically appear in SAP Sales Cloud and SAP Service Cloud Version 2, linked to the original case.

In addition, the app.js file defines a health check endpoint (/health). This is a simple GET request that confirms whether the microservice can successfully reach the SAP Sales Cloud and SAP Service Cloud Version 2 API. You can use this endpoint later in the SAP Sales Cloud and SAP Service Cloud Version 2 Autoflow to test if your microservice deployment is running properly.

Here’s the full Node.js code example for your reference. You can use it as-is for the exercise or modify it to implement your own custom logic.

JavaScript
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
var express = require('express'); var app = express(); const axios = require('axios'); // --- Authentication for SAP Service Cloud --- const token = Buffer.from(`${process.env.SSC_USER}:${process.env.SSC_PASSWORD}`).toString('base64'); const base_url = `${process.env.SERVICE_URL}/sap/c4c/api`; // Set default Axios headers axios.defaults.headers.common['Authorization'] = `Basic ${token}`; axios.defaults.headers.common['content-type'] = 'application/json'; app.use(express.json()); console.log('Start....'); // --- Webhook endpoint for custom logic --- app.post('/onCreateSubCase', async function (req, res) { try { // Extract data from event body const data = req.body; const id = data?.data?.currentImage?.id; // Validate if the case has no parent case if (data.data && data.data.currentImage && !data.data.currentImage.parentCaseId) { // Define sub-case payload const subCaseData = { subject: `Sub Case of ${data.data.currentImage.displayId}`, caseType: 'ZCAS', origin: 'MANUAL_DATA_ENTRY', status: '01', priority: '03', account: { id: data.data.currentImage.account.id }, relatedObjects: [ { objectId: id, type: '2886', role: '13' } ] }; // Create sub-case via Service Cloud API const response = await axios.post(`${base_url}/v1/case-service/cases`, subCaseData); console.log('Sub Case created:', response.data); } res.status(200).send('OK'); } catch (error) { console.error('Error creating sub case:', error.message); res.status(500).send('Error creating sub case'); } }); // --- Health check endpoint --- app.get('/health', async function (req, res) { try { // Test connection with the Service Cloud tenant await axios.get(`${base_url}/v1/case-service/cases`); console.log('Healthy - connection to Service Cloud works'); res.send('OK'); } catch (error) { console.error('Health check failed:', error.message); res.status(500).send('Error'); } }); // --- Start server --- app.listen(process.env.PORT || 4000, () => { console.log(`Server running on port ${process.env.PORT || 4000}`); });

Microservice Deployment to the BTP Cloud Foundry Environment

As explained earlier, Creating a Simple Webapp in SAP Build Code and Deploying it to the SAP BTP, Cloud Foundry Environment, use the following cf login command along with the origin key, API endpoint, organization, and space information from your BTP Subaccount to authenticate and connect to the Cloud Foundry environment. This is the same command used in the previous lesson Creating a Simple Webapp in SAP Build Code and Deploying it to the SAP BTP, Cloud Foundry Environment, but you may simply use cf login and then follow the instructions in the terminal if you’re using the default SAP Identity Provider.

cf login --origin learningcx-platform -a https://api.cf.eu10-005.hana.ondemand.com -o "SAP - CX Extensibility_extension-c4h07i" -s dev

If the login is successful, the system confirms that you are authenticated and shows your target organization and space. Once logged in, you can deploy your application using the following command: cf push.

Cloud Foundry now builds and deploys your application according to the configuration in the manifest.yaml file. This process may take a few seconds. After the deployment is complete, Cloud Foundry provides information about the app’s status. Check that the application instances are running and that the memory and disk usage are within the configured limits.

At the end of the log, note the routes displayed: this is the public URL of your microservice. You can open this link in a browser to verify that the service is active and responding. Later, you need this route when embedding the microservice into SAP Sales Cloud and SAP Service Cloud Version 2.

The terminal output shows the deployment process of the microservice to Cloud Foundry. The route URL btp-microservice-subcase.cfapps.eu10-005.hana.ondemand.com is highlighted, indicating that the application was successfully started and is now running on SAP BTP.

However, you don’t need to copy it manually. You can always view the route in the SAP BTP cockpit under the corresponding Cloud Foundry space in your Subaccount.(Go to your Global Account → Subaccount → Cloud Foundry → Spaces → Choose your Space → Choose your application)

The SAP BTP cockpit shows the application overview for the deployed microservice. The screen confirms that the app is in “Started” status and displays the application route URL used for communication with SAP Sales Cloud and SAP Service Cloud Version 2.

Summary

  • Custom Logic and Extensibility

    Custom logic microservices allow developers to extend SAP Sales Cloud and SAP Service Cloud Version 2 without modifying the core system. They communicate through APIs and can be independently deployed and maintained on SAP BTP.

  • Project Setup

    A new project was created using the Basic Multitarget Application template, forming the foundation for the microservice structure and deployment.

  • Node.js Environment Configuration

    The Node.js runtime was initialized and required dependencies were installed using npm init and npm install express axios, preparing the environment for coding.

  • Manifest Configuration

    The manifest.yaml file defines how the service is built and deployed. It includes environment variables (e.g., SSC_USER, SSC_PASSWORD, SERVICE_URL) for connecting securely to SAP Sales Cloud and SAP Service Cloud Version 2.

  • Business Logic Implementation

    The main logic was implemented in app.js, which defines the service endpoint /onCreateSubCase. This endpoint listens to case creation events and automatically creates a related Subcase through the SAP Sales Cloud and SAP Service Cloud Version 2 API.

  • Health Monitoring

    A /health endpoint was added to verify connectivity between the deployed microservice and SAP Sales Cloud and SAP Service Cloud Version 2.

  • Deployment and Verification

    The service was deployed to the Cloud Foundry environment in the BTP Subaccount using cf push. After deployment, the route (URL) was confirmed and can later be used to embed the microservice into SAP Sales Cloud and SAP Service Cloud Version 2.