ShapeNXT Logo
Back to all articles
Groovy Scripting

How to Write Groovy Script in SAP CPI with Real Examples

Master Groovy scripting in SAP Cloud Integration. Learn message object APIs, headers, properties, XML/JSON parsing, and real-world transformation scripts.

S
Senior SAP Integration ArchitectPublished on March 1, 2026
6 min read
How to Write Groovy Script in SAP CPI with Real Examples
Live Project Training & Certification

Want hands-on live project training? Download the 2026 ShapeNXT Syllabus.

Go beyond theory. Build 10+ production-grade enterprise iFlows, master Groovy scripting, and practice on live BTP sandboxes with direct 1-on-1 architect mentorship.

4.8 / 5 Rating (1500+ Learners)• 92% Placement Success
Explore Course

Why Groovy Scripting is Essential in SAP Cloud Integration

While SAP Cloud Platform Integration (CPI / SAP Cloud Integration) provides powerful graphical palettes and standard mapping tools, enterprise integrations frequently encounter complex scenarios that standard components cannot solve. From dynamic header manipulation and in-memory hash lookups to parsing multi-tier nested JSON payloads, Groovy scripting is the ultimate tool in every SAP CPI consultant's toolkit.

Understanding the SAP CPI Message Object

Every Groovy script in SAP CPI executes within a runtime context that provides direct access to the Message object. The org.apache.camel.Message wrapper gives you access to three core components:

  • Body: The main payload (String, InputStream, byte array, or XML/JSON document).
  • Headers: Protocol and transport-level metadata (HTTP headers, query parameters, CamelFileName).
  • Properties (Exchange Properties): Variables available across the entire life of the Integration Flow execution.

Example 1: Accessing and Modifying Headers & Exchange Properties

Here is the standard template used to read an incoming HTTP header, compute a business transaction ID, and store it into an Exchange Property for later audit logging:

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.HashMap

def Message processData(Message message) {
    // 1. Read an incoming header
    def sourceSystem = message.getHeader("SourceSystem", String.class)
    
    // 2. Read an existing Exchange Property
    def orderId = message.getProperty("SalesOrderID")
    
    // 3. Perform business validation or transformation
    def auditTimestamp = new Date().format("yyyy-MM-dd'T'HH:mm:ss'Z'")
    def transactionKey = "${sourceSystem}_${orderId}_${System.currentTimeMillis()}"
    
    // 4. Set new Header and Property values
    message.setHeader("X-Audit-Timestamp", auditTimestamp)
    message.setProperty("TrackingTransactionKey", transactionKey)
    
    return message
}

Example 2: Parsing JSON Payloads using JsonSlurper & JsonOutput

When connecting third-party SaaS applications (like Salesforce or ServiceNow) to SAP S/4HANA via REST APIs, you frequently need to parse and augment JSON payloads directly in memory:

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def Message processData(Message message) {
    // Read the incoming payload as a String
    def body = message.getBody(String.class)
    
    // Parse the JSON payload
    def slurper = new JsonSlurper()
    def parsedData = slurper.parseText(body)
    
    // Augment the JSON data
    parsedData.processedBy = "ShapeNXT-CPI-Engine"
    parsedData.status = "VALIDATED"
    
    // Filter inactive records if present
    if (parsedData.items) {
      parsedData.items = parsedData.items.findAll { it.quantity > 0 }
    }
    
    // Convert back to JSON and write to Message Body
    message.setBody(JsonOutput.toJson(parsedData))
    message.setHeader("Content-Type", "application/json")
    
    return message
}

Best Practices for Writing Enterprise Groovy Scripts

  1. Always stream large payloads: Avoid reading multi-megabyte payloads into memory strings using message.getBody(String.class). Prefer Reader or streaming transformations.
  2. Log selectively: Never log sensitive employee records, credentials, or personal identifying information (PII) into the CPI message log.
  3. Handle null pointers proactively: Use Groovy's safe navigation operator (parsedData?.customer?.id) to avoid abrupt runtime crashes.
Live Project Training & Certification

Want hands-on live project training? Download the 2026 ShapeNXT Syllabus.

Go beyond theory. Build 10+ production-grade enterprise iFlows, master Groovy scripting, and practice on live BTP sandboxes with direct 1-on-1 architect mentorship.

4.8 / 5 Rating (1500+ Learners)• 92% Placement Success
Explore Course