SAP Cloud Platform Integration, now commonly known as SAP Integration Suite Cloud Integration, plays an important role in connecting business applications, cloud platforms, and enterprise systems. As organizations move toward cloud based architectures, the ability to build reliable integrations between SAP and non SAP applications has become an essential technical skill.
One of the most useful capabilities in SAP Cloud Integration is Groovy scripting. Groovy allows developers to customize integration flows, manipulate message payloads, extract headers, manage properties, transform data, and handle exceptions. Although standard integration components can handle many requirements, certain business scenarios need additional scripting logic.
For SAP CPI developers, learning practical Groovy scripts is an effective way to improve integration development skills. Instead of relying entirely on predefined mapping and transformation tools, developers can use Groovy to solve complex integration requirements with greater flexibility.
In this guide, we will explore 15 practical SAP CPI Groovy script examples that developers can use in real world integration scenarios in 2026. Each example explains its purpose, provides working code, and highlights situations where it can be useful.
1. Understanding Groovy Scripting in SAP CPI
Groovy is a dynamic programming language that runs on the Java platform. It combines features of Java with a simpler syntax, making it suitable for writing compact scripts.
In SAP Cloud Integration, Groovy scripts are commonly used inside integration flows when standard processing steps are insufficient for a particular requirement.
A Groovy script can access the message body, headers, exchange properties, and other message information through the SAP Cloud Integration message API.
How Groovy Scripts Work in SAP CPI
A Groovy script typically receives a message object from the integration runtime. Developers can use this object to read or modify the message body, retrieve headers, and update exchange properties.
A basic SAP CPI Groovy script looks like this:
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
def body = message.getBody(String)
message.setBody(body)
return message
}
The processData method is the entry point used by the script step. It receives the message, performs the required operations, and returns the modified message.
Where Can You Use Groovy Scripts?
Groovy scripts can be added to an integration flow using a Script step in the SAP Cloud Integration design environment.
Common use cases include:
- Reading and updating message headers.
- Accessing exchange properties.
- Transforming JSON and XML payloads.
- Formatting dates and timestamps.
- Removing unwanted fields.
- Validating incoming messages.
- Handling exceptions and logging relevant information.
A well written script should solve a specific integration requirement without making the integration flow unnecessarily complicated.
2. Top 15 SAP CPI Groovy Script Examples Every Developer Needs
The following examples cover common requirements encountered while developing and maintaining SAP Cloud Integration flows. They are designed as practical starting points and should be tested with your actual payload structure and runtime configuration.
1. Read the Message Body
Reading the message body is one of the most basic requirements in SAP CPI. Developers often need to inspect an incoming payload before performing further processing.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
String body = message.getBody(String)
message.setProperty("OriginalPayload", body)
return message
}
Practical use: This script reads the incoming message body and stores a copy in an exchange property for later processing within the same integration flow.
2. Read and Update Message Headers
Headers contain useful information about an incoming or outgoing message. They can store content types, identifiers, and other technical details.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
def headers = message.getHeaders()
def contentType = message.getHeader("Content-Type", String)
message.setHeader("CustomHeader", "SAPCPI2026")
return message
}
Practical use: This script retrieves the Content Type header and adds a custom header that can be used in subsequent integration steps.
3. Read and Set Exchange Properties
Exchange properties allow developers to store values that can be reused across different processing steps within an integration flow.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
String customerId = "C1001"
message.setProperty("CustomerID", customerId)
def savedCustomer = message.getProperty("CustomerID")
return message
}
Practical use: Store customer identifiers, processing flags, or calculated values that are needed later in the integration flow.
4. Convert JSON Payload into a Map
JSON processing is common when integrating SAP applications with REST APIs and external cloud services. Groovy provides JsonSlurper to parse JSON data.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
def Message processData(Message message) {
String body = message.getBody(String)
def json = new JsonSlurper().parseText(body)
message.setProperty("CustomerName", json.customerName)
return message
}
Sample JSON input:
{
"customerName": "Rahul",
"customerId": "C1001"
}
Practical use: Extract individual values from JSON payloads and use them for routing, validation, or subsequent transformations.
5. Convert a Map into JSON
Sometimes developers need to generate a JSON response after processing data inside an integration flow. Groovy’s JsonOutput makes this straightforward.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonOutput
def Message processData(Message message) {
def response = [
status: "Success",
system: "SAP CPI",
year: 2026
]
message.setBody(JsonOutput.toJson(response))
return message
}
Practical use: Generate a structured JSON response for an external application or REST API.
6. Parse XML Payload Using XmlSlurper
XML is widely used in SAP integration scenarios, particularly when exchanging data between SAP ERP, SAP S/4HANA, and external systems.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.util.XmlSlurper
def Message processData(Message message) {
String body = message.getBody(String)
def xml = new XmlSlurper().parseText(body)
String customer = xml.Customer.Name.text()
message.setProperty("CustomerName", customer)
return message
}
Sample XML input:
<Customer>
<Name>Rahul</Name>
<CustomerID>C1001</CustomerID>
</Customer>
Practical use: Extract values from XML messages when integrating SAP systems with applications that exchange XML documents.
7. Convert Date Formats
Different applications may use different date formats. One system may send dates in yyyy-MM-dd format, while another expects dd-MM-yyyy.
import com.sap.gateway.ip.core.customdev.util.Message
import java.time.LocalDate
import java.time.format.DateTimeFormatter
def Message processData(Message message) {
String inputDate = message.getBody(String).trim()
def inputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd")
def outputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy")
def date = LocalDate.parse(inputDate, inputFormat)
message.setBody(date.format(outputFormat))
return message
}
Practical use: Standardize dates before sending employee, customer, or financial information between applications.
8. Remove Unwanted JSON Fields
External applications sometimes send additional fields that the receiving system does not require. Groovy can remove those fields before forwarding the message.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def Message processData(Message message) {
def data = new JsonSlurper().parseText(message.getBody(String))
data.remove("temporaryField")
data.remove("debugInfo")
message.setBody(JsonOutput.toJson(data))
return message
}
Practical use: Clean JSON payloads before sending data to SAP or third party applications. For nested structures, access the appropriate nested map before removing fields.
9. Generate a Unique Correlation ID
A correlation ID helps developers trace related messages across integration systems. It is especially useful when investigating failed transactions or monitoring multiple requests.
import com.sap.gateway.ip.core.customdev.util.Message
import java.util.UUID
def Message processData(Message message) {
String correlationId = UUID.randomUUID().toString()
message.setHeader("CorrelationID", correlationId)
return message
}
Practical use: Generate a unique identifier that can be passed to downstream systems for transaction tracking.
10. Validate Mandatory JSON Fields
Before sending information to another application, developers should verify that required fields are available.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
def Message processData(Message message) {
def data = new JsonSlurper().parseText(message.getBody(String))
if (!data.customerId || !data.customerName) {
throw new IllegalArgumentException(
"Customer ID and Customer Name are mandatory"
)
}
return message
}
Practical use: Prevent incomplete customer records from being forwarded to the target system. Configure the integration flow’s exception handling to process validation failures appropriately.
11. Split a JSON Array into Individual Records
Some APIs send multiple business records in a single JSON array. In certain scenarios, individual records must be processed separately.
import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def Message processData(Message message) {
def records = new JsonSlurper().parseText(message.getBody(String))
if (!(records instanceof List)) {
throw new IllegalArgumentException("Expected a JSON array")
}
def firstRecord = records ? records[0] : [:]
message.setBody(JsonOutput.toJson(firstRecord))
return message
}
Practical use: This example extracts the first record from a JSON array. For production scenarios requiring every record to be processed independently, use the General Splitter or an appropriate iteration pattern rather than simply selecting the first element.
12. Create a Custom Error Message
Clear error messages make troubleshooting easier and help developers understand why a particular integration message failed.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
String errorMessage = "Customer data validation failed"
message.setProperty("CustomErrorMessage", errorMessage)
return message
}
Practical use: Store a meaningful error description that can be used by an exception subprocess, monitoring process, or downstream error handling logic.
13. Convert a String into Uppercase
Data standardization is useful when different source applications send values in inconsistent formats.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
String body = message.getBody(String)
message.setBody(body.toUpperCase())
return message
}
Practical use: Convert simple text payloads into uppercase when the target application requires a standardized format. Avoid applying this to complete JSON or XML documents because it can change field names and data values.
14. Read Query Parameters from a Header
REST integrations often require query parameters for filtering or retrieving specific records.
import com.sap.gateway.ip.core.customdev.util.Message
def Message processData(Message message) {
def query = message.getHeader("CamelHttpQuery", String)
message.setProperty("RequestQuery", query ?: "")
return message
}
Practical use: Read the HTTP query string when it is available in the integration runtime and store it as an exchange property for subsequent processing. Query parameters may need decoding and validation before use.
15. Log Message Information for Troubleshooting
Logging can help developers understand message processing and identify integration issues. However, sensitive business information should never be written into application logs unnecessarily.
import com.sap.gateway.ip.core.customdev.util.Message
import org.slf4j.LoggerFactory
def Message processData(Message message) {
def log = LoggerFactory.getLogger("SAPCPIIntegration")
log.info("SAP CPI message processing started")
return message
}
Practical use: Record important processing events that help developers troubleshoot integration flows. Follow your organization’s logging and data protection policies.
3. Best Practices for Writing Groovy Scripts in SAP CPI
Writing a script that works is only the first step. Production integration flows must also be maintainable, secure, and efficient.
Keep Scripts Simple and Reusable
Avoid writing unnecessarily complicated code. If a requirement can be handled through standard mapping, routing, or message processing components, consider using those components instead of adding custom scripts.
Handle Exceptions Properly
Use meaningful exception messages and configure exception subprocesses where required. Avoid silently ignoring errors because this can result in incomplete or incorrect business data.
Avoid Exposing Sensitive Information
Customer details, passwords, authentication tokens, and financial information should not be written into logs. Mask sensitive fields whenever diagnostic information is necessary.
Test Scripts with Different Payloads
Test successful messages, missing fields, empty values, invalid JSON, malformed XML, and unexpected data types. Testing only one sample payload is not sufficient for production readiness.
Consider Performance
Avoid repeatedly parsing large payloads and creating unnecessary intermediate objects. For large message processing requirements, evaluate standard integration capabilities and streaming approaches where supported.
4. Common Groovy Scripting Mistakes SAP CPI Developers Should Avoid
Developers often encounter issues because of small mistakes in syntax, payload assumptions, or message handling.
Some common mistakes include:
- Forgetting to return the message object from
processData. - Using incorrect JSON property names.
- Assuming every incoming message contains valid JSON or XML.
- Ignoring null values and empty fields.
- Using unsupported Java or Groovy libraries.
- Logging complete business payloads unnecessarily.
- Using custom scripts when standard integration components are sufficient.
- Not testing scripts against realistic production scenarios.
A good development approach includes understanding the payload, defining the expected output, writing the smallest possible script, and testing both successful and unsuccessful scenarios.
5. How to Practice SAP CPI Groovy Scripting in Real Projects
The best way to improve Groovy scripting skills is to work on integration scenarios that resemble actual business requirements.
For example, consider an integration between SAP S/4HANA and an external customer management application.
The source system sends customer information in XML format, while the receiving application expects JSON. The integration flow may need to extract customer details, validate mandatory fields, convert the date format, generate a correlation ID, and create the target JSON payload.
You can practice this scenario by building an integration flow with the following steps:
- Configure an HTTPS sender or another suitable source adapter.
- Receive a sample customer XML payload.
- Use Groovy to extract required information.
- Validate customer identifiers and mandatory fields.
- Transform the extracted information into JSON.
- Add relevant headers and exchange properties.
- Configure the receiver connection.
- Test successful messages and validation failures.
This exercise combines several scripting techniques and helps you understand how Groovy works within a complete integration flow.
Developers should also become familiar with SAP Cloud Integration message processing, Content Modifier, Message Mapping, Router, Splitter, Gather, and Exception Subprocess components.
6. Career Opportunities for SAP CPI Developers in 2026
SAP CPI skills are valuable for professionals working with enterprise application integration and cloud transformation projects. Organizations need developers who can connect SAP systems with cloud applications, third party services, and external APIs.
Learning Groovy scripting can strengthen your understanding of integration development and prepare you for more advanced responsibilities.
Some relevant skills to develop alongside Groovy include:
- SAP Integration Suite architecture.
- Cloud Integration adapters.
- REST and SOAP APIs.
- JSON and XML processing.
- OAuth and certificate based authentication.
- Message Mapping and XSLT.
- Exception handling and monitoring.
- SAP BTP fundamentals.
- OData services.
- API Management.
A combination of technical knowledge and practical project experience can help developers build a strong foundation for SAP integration careers.
Frequently Asked Questions About SAP CPI Groovy Scripts
1. What is Groovy scripting in SAP CPI?
Groovy scripting in SAP CPI is a programming capability used to customize message processing within integration flows. Developers use it to manipulate payloads, read headers, update properties, validate data, and implement additional processing logic.
2. Which Groovy version is used in SAP CPI?
The available Groovy runtime and supported language features depend on the SAP Cloud Integration runtime. Developers should consult the current SAP documentation and avoid assuming that every feature available in the latest standalone Groovy release is supported.
3. Can we use Java libraries in SAP CPI Groovy scripts?
Some Java libraries and classes are available because Groovy runs on the Java platform. However, availability depends on the runtime and SAP restrictions. Developers should use supported libraries and avoid adding unapproved dependencies.
4. What is the difference between message headers and exchange properties?
Message headers contain information associated with the message and may be relevant to adapters or downstream processing. Exchange properties are internal values used to store information throughout the integration flow. Their scope and behavior should be considered when designing an integration.
5. How do I read a JSON payload in SAP CPI?
You can use Groovy’s JsonSlurper to parse a JSON string into maps and lists. You can then access the required values and update the message body or exchange properties.
6. How do I debug a Groovy script in SAP CPI?
Use the available integration monitoring tools, message processing logs, and controlled logging statements. Test scripts with representative payloads and avoid exposing sensitive information.
7. Is Groovy scripting mandatory for SAP CPI developers?
No. Many integration requirements can be implemented using standard SAP Cloud Integration components. However, Groovy scripting is useful when additional customization, validation, or data processing is required.
8. Where can I practice SAP CPI Groovy scripts?
You can practice using SAP Integration Suite learning environments, SAP documentation, sample integration scenarios, and practical exercises involving JSON, XML, REST APIs, and message processing.
Conclusion
Groovy scripting is an important skill for developers working with SAP Cloud Integration. From reading message bodies and updating headers to validating JSON, processing XML, formatting dates, and handling errors, these 15 SAP CPI Groovy script examples cover several common integration requirements.
However, successful SAP CPI development requires more than memorizing code snippets. Developers must understand integration architecture, message processing, adapters, APIs, security, monitoring, and exception handling.
Start by practicing the basic scripts, gradually combine them into complete integration scenarios, and test your solutions with different payloads. With consistent practice and a strong understanding of SAP Integration Suite, you can develop the technical skills required to build reliable enterprise integrations in 2026.
How to Convert JSON Data Structure to ABAP Structure without ABAP Code or SE11?
ABAP Evolution: From Monolithic Masterpiece
WhatsApp us