In SAP CPI, sometimes you need to enrich your message with data from an external system. Calling a REST API from a Groovy script is a powerful way to do this. You can make HTTP GET, POST, PUT, and DELETE requests to interact with third-party services.
Making a GET Request
The 'HttpUrlConnection' class is a reliable way to make HTTP requests. You can pass parameters, set headers, and retrieve the response. A common use case is fetching customer details from a CRM system.
Example Groovy Script for GET call with Baisc Authentication:
import com.sap.gateway.ip.core.customdev.util.Message import java.util.HashMap import java.net.URL import java.net.HttpURLConnection import java.util.Base64 def Message processData(Message message) { // API endpoint def apiUrl = "https://api.example.com/v1/data" // Username and Password for Basic Auth def username = "yourUsername" def password = "yourPassword" // Encode credentials to Base64 String auth = username + ":" + password byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes("UTF-8")) String authHeader = "Basic " + new String(encodedAuth) // Open connection URL url = new URL(apiUrl) HttpURLConnection connection = (HttpURLConnection) url.openConnection() connection.setRequestMethod("GET") connection.setRequestProperty("Authorization", authHeader) connection.setRequestProperty("Accept", "application/json") connection.setConnectTimeout(10000) // 10 sec timeout connection.setReadTimeout(10000) int responseCode = connection.getResponseCode() String responseBody if (responseCode == HttpURLConnection.HTTP_OK) { responseBody = connection.getInputStream().getText("UTF-8") } else { responseBody = connection.getErrorStream()?.getText("UTF-8") } // Set response as body of message message.setBody(responseBody) // Optionally store response code in header message.setHeader("HTTP_RESPONSE_CODE", responseCode.toString()) return message }
Making POST, PUT, PATCH, DELETE Request with a Payload
A generic Groovy template in SAP CPI where you can call any external API with Basic Authentication, and you can switch between GET, POST, PUT, PATCH, DELETE just by changing the method.
Example Groovy Script template with Basic Authentication:
import com.sap.gateway.ip.core.customdev.util.Message import java.util.HashMap import java.net.URL import java.net.HttpURLConnection import java.util.Base64 def Message processData(Message message) { // === Configuration === def apiUrl = "https://api.example.com/v1/resource" // API endpoint def username = "yourUsername" def password = "yourPassword" def httpMethod = "POST" // Change to GET, PUT, PATCH, DELETE as needed // Body for POST, PUT, PATCH (CPI message body can be used too) def requestBody = message.getBody(java.lang.String) // If empty and you want to hardcode: // def requestBody = '{"id":123, "name":"test"}' // === Basic Auth Header === String auth = username + ":" + password byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes("UTF-8")) String authHeader = "Basic " + new String(encodedAuth) // === Connection Setup === URL url = new URL(apiUrl) HttpURLConnection connection = (HttpURLConnection) url.openConnection() connection.setRequestMethod(httpMethod) connection.setRequestProperty("Authorization", authHeader) connection.setRequestProperty("Content-Type", "application/json") connection.setRequestProperty("Accept", "application/json") connection.setConnectTimeout(15000) connection.setReadTimeout(15000) // === Handle Request Body for POST, PUT, PATCH === if (httpMethod in ["POST", "PUT", "PATCH"]) { connection.setDoOutput(true) connection.getOutputStream().withWriter("UTF-8") { writer -> writer.write(requestBody ?: "") } } // === Get Response === int responseCode = connection.getResponseCode() String responseBody if (responseCode >= 200 && responseCode < 300) { responseBody = connection.getInputStream().getText("UTF-8") } else { responseBody = connection.getErrorStream()?.getText("UTF-8") } // === Set Output === message.setBody(responseBody) message.setHeader("HTTP_RESPONSE_CODE", responseCode.toString()) message.setHeader("HTTP_METHOD_USED", httpMethod) return message }
Using other Authentication Methods
In CPI Groovy, you can also call APIs using other common authentication methods.I’ll give you ready-to-use Groovy code snippets for each type.
Code snippet for Bearer Token (OAuth2 / JWT):
// Normally token is retrieved beforehand via OAuth2 flow String token = "your-access-token-here" connection.setRequestProperty("Authorization", "Bearer " + token)
Code snippet for API Key in Header:
String apiKey = "your-api-key" connection.setRequestProperty("x-api-key", apiKey)
Code snippet for API Key in Query Parameter:
String apiKey = "your-api-key" URL url = new URL("https://api.example.com/v1/data?apikey=" + apiKey) HttpURLConnection connection = (HttpURLConnection) url.openConnection()
Code snippet for OAuth2 Client Credentials (Dynamic Token Fetch):
You need to first fetch a token, then call the API.
import java.net.* import java.io.* // Step 1: Get OAuth2 Token def tokenUrl = "https://auth.example.com/oauth2/token" def clientId = "yourClientId" def clientSecret = "yourClientSecret" String auth = clientId + ":" + clientSecret String authHeader = "Basic " + Base64.encoder.encodeToString(auth.getBytes("UTF-8")) URL url = new URL(tokenUrl) HttpURLConnection conn = (HttpURLConnection) url.openConnection() conn.setRequestMethod("POST") conn.setRequestProperty("Authorization", authHeader) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") conn.setDoOutput(true) def body = "grant_type=client_credentials" conn.getOutputStream().withWriter("UTF-8") { writer -> writer.write(body) } def response = conn.getInputStream().getText("UTF-8") def accessToken = new groovy.json.JsonSlurper().parseText(response).access_token // Step 2: Call API with Bearer Token URL apiUrl = new URL("https://api.example.com/v1/resource") HttpURLConnection apiConn = (HttpURLConnection) apiUrl.openConnection() apiConn.setRequestMethod("GET") apiConn.setRequestProperty("Authorization", "Bearer " + accessToken)
Code snippet for Custom Header Authentication:
connection.setRequestProperty("Auth-Token", "custom-token-value") connection.setRequestProperty("Client-Id", "your-client-id")
Limitaion:
Mutual TLS (Certificate Based Auth) can not be handled directly in Groovy. CPI manages it via Keystore and HTTP adapter with client certificates.From Groovy you cannot directly attach certificates.